umd.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*!
  2. MIT License
  3. Copyright (c) 2018 Arturas Molcanovas <a.molcanovas@gmail.com>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. */
  20. (function (global, factory) {
  21. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  22. typeof define === 'function' && define.amd ? define('localforage-driver-commons', ['exports'], factory) :
  23. (factory((global.LocalforageDriverCommons = {})));
  24. }(this, (function (exports) { 'use strict';
  25. /**
  26. * Abstracts constructing a Blob object, so it also works in older
  27. * browsers that don't support the native Blob constructor. (i.e.
  28. * old QtWebKit versions, at least).
  29. * Abstracts constructing a Blob object, so it also works in older
  30. * browsers that don't support the native Blob constructor. (i.e.
  31. * old QtWebKit versions, at least).
  32. *
  33. * @param parts
  34. * @param properties
  35. */
  36. function createBlob(parts, properties) {
  37. /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  38. parts = parts || [];
  39. properties = properties || {};
  40. try {
  41. return new Blob(parts, properties);
  42. }
  43. catch (e) {
  44. if (e.name !== 'TypeError') {
  45. throw e;
  46. }
  47. //tslint:disable-next-line:variable-name
  48. var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder
  49. : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder
  50. : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder
  51. : WebKitBlobBuilder;
  52. var builder = new Builder();
  53. for (var i = 0; i < parts.length; i += 1) {
  54. builder.append(parts[i]);
  55. }
  56. return builder.getBlob(properties.type);
  57. }
  58. }
  59. var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
  60. var SERIALIZED_MARKER_LENGTH = "__lfsc__:" /* SERIALIZED_MARKER */.length;
  61. var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + "arbf" /* TYPE_ARRAYBUFFER */.length;
  62. //tslint:disable:no-magic-numbers no-bitwise prefer-switch no-unbound-method
  63. var toString = Object.prototype.toString;
  64. function stringToBuffer(serializedString) {
  65. // Fill the string into a ArrayBuffer.
  66. var bufferLength = serializedString.length * 0.75;
  67. var len = serializedString.length;
  68. if (serializedString[serializedString.length - 1] === '=') {
  69. bufferLength--;
  70. if (serializedString[serializedString.length - 2] === '=') {
  71. bufferLength--;
  72. }
  73. }
  74. var buffer = new ArrayBuffer(bufferLength);
  75. var bytes = new Uint8Array(buffer);
  76. for (var i = 0, p = 0; i < len; i += 4) {
  77. var encoded1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i]);
  78. var encoded2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 1]);
  79. var encoded3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 2]);
  80. var encoded4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */.indexOf(serializedString[i + 3]);
  81. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  82. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  83. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  84. }
  85. return buffer;
  86. }
  87. /**
  88. * Converts a buffer to a string to store, serialized, in the backend
  89. * storage library.
  90. */
  91. function bufferToString(buffer) {
  92. // base64-arraybuffer
  93. var bytes = new Uint8Array(buffer);
  94. var base64String = '';
  95. for (var i = 0; i < bytes.length; i += 3) {
  96. /*jslint bitwise: true */
  97. base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[bytes[i] >> 2];
  98. base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  99. base64String +=
  100. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  101. base64String += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" /* BASE_CHARS */[bytes[i + 2] & 63];
  102. }
  103. if (bytes.length % 3 === 2) {
  104. base64String = base64String.substring(0, base64String.length - 1) + '=';
  105. }
  106. else if (bytes.length % 3 === 1) {
  107. base64String = base64String.substring(0, base64String.length - 2) + '==';
  108. }
  109. return base64String;
  110. }
  111. /**
  112. * Serialize a value, afterwards executing a callback (which usually
  113. * instructs the `setItem()` callback/promise to be executed). This is how
  114. * we store binary data with localStorage.
  115. * @param value
  116. * @param callback
  117. */
  118. function serialize(value, callback) {
  119. var valueType = '';
  120. if (value) {
  121. valueType = toString.call(value);
  122. }
  123. // Cannot use `value instanceof ArrayBuffer` or such here, as these
  124. // checks fail when running the tests using casper.js...
  125. if (value && (valueType === '[object ArrayBuffer]' ||
  126. (value.buffer && toString.call(value.buffer) === '[object ArrayBuffer]'))) {
  127. // Convert binary arrays to a string and prefix the string with
  128. // a special marker.
  129. var buffer = void 0;
  130. var marker = "__lfsc__:" /* SERIALIZED_MARKER */;
  131. if (value instanceof ArrayBuffer) {
  132. buffer = value;
  133. marker += "arbf" /* TYPE_ARRAYBUFFER */;
  134. }
  135. else {
  136. buffer = value.buffer;
  137. if (valueType === '[object Int8Array]') {
  138. marker += "si08" /* TYPE_INT8ARRAY */;
  139. }
  140. else if (valueType === '[object Uint8Array]') {
  141. marker += "ui08" /* TYPE_UINT8ARRAY */;
  142. }
  143. else if (valueType === '[object Uint8ClampedArray]') {
  144. marker += "uic8" /* TYPE_UINT8CLAMPEDARRAY */;
  145. }
  146. else if (valueType === '[object Int16Array]') {
  147. marker += "si16" /* TYPE_INT16ARRAY */;
  148. }
  149. else if (valueType === '[object Uint16Array]') {
  150. marker += "ur16" /* TYPE_UINT16ARRAY */;
  151. }
  152. else if (valueType === '[object Int32Array]') {
  153. marker += "si32" /* TYPE_INT32ARRAY */;
  154. }
  155. else if (valueType === '[object Uint32Array]') {
  156. marker += "ui32" /* TYPE_UINT32ARRAY */;
  157. }
  158. else if (valueType === '[object Float32Array]') {
  159. marker += "fl32" /* TYPE_FLOAT32ARRAY */;
  160. }
  161. else if (valueType === '[object Float64Array]') {
  162. marker += "fl64" /* TYPE_FLOAT64ARRAY */;
  163. }
  164. else {
  165. callback(new Error('Failed to get type for BinaryArray'));
  166. }
  167. }
  168. callback(marker + bufferToString(buffer));
  169. }
  170. else if (valueType === '[object Blob]') {
  171. // Convert the blob to a binaryArray and then to a string.
  172. var fileReader = new FileReader();
  173. fileReader.onload = function () {
  174. // Backwards-compatible prefix for the blob type.
  175. //tslint:disable-next-line:restrict-plus-operands
  176. var str = "~~local_forage_type~" /* BLOB_TYPE_PREFIX */ + value.type + "~" + bufferToString(this.result);
  177. callback("__lfsc__:" /* SERIALIZED_MARKER */ + "blob" /* TYPE_BLOB */ + str);
  178. };
  179. fileReader.readAsArrayBuffer(value);
  180. }
  181. else {
  182. try {
  183. callback(JSON.stringify(value));
  184. }
  185. catch (e) {
  186. console.error('Couldn\'t convert value into a JSON string: ', value);
  187. callback(null, e);
  188. }
  189. }
  190. }
  191. /**
  192. * Deserialize data we've inserted into a value column/field. We place
  193. * special markers into our strings to mark them as encoded; this isn't
  194. * as nice as a meta field, but it's the only sane thing we can do whilst
  195. * keeping localStorage support intact.
  196. *
  197. * Oftentimes this will just deserialize JSON content, but if we have a
  198. * special marker (SERIALIZED_MARKER, defined above), we will extract
  199. * some kind of arraybuffer/binary data/typed array out of the string.
  200. * @param value
  201. */
  202. function deserialize(value) {
  203. // If we haven't marked this string as being specially serialized (i.e.
  204. // something other than serialized JSON), we can just return it and be
  205. // done with it.
  206. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== "__lfsc__:" /* SERIALIZED_MARKER */) {
  207. return JSON.parse(value);
  208. }
  209. // The following code deals with deserializing some kind of Blob or
  210. // TypedArray. First we separate out the type of data we're dealing
  211. // with from the data itself.
  212. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
  213. var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
  214. var blobType;
  215. // Backwards-compatible blob type serialization strategy.
  216. // DBs created with older versions of localForage will simply not have the blob type.
  217. if (type === "blob" /* TYPE_BLOB */ && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
  218. var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
  219. blobType = matcher[1];
  220. serializedString = serializedString.substring(matcher[0].length);
  221. }
  222. var buffer = stringToBuffer(serializedString);
  223. // Return the right type based on the code/type set during
  224. // serialization.
  225. switch (type) {
  226. case "arbf" /* TYPE_ARRAYBUFFER */:
  227. return buffer;
  228. case "blob" /* TYPE_BLOB */:
  229. return createBlob([buffer], { type: blobType });
  230. case "si08" /* TYPE_INT8ARRAY */:
  231. return new Int8Array(buffer);
  232. case "ui08" /* TYPE_UINT8ARRAY */:
  233. return new Uint8Array(buffer);
  234. case "uic8" /* TYPE_UINT8CLAMPEDARRAY */:
  235. return new Uint8ClampedArray(buffer);
  236. case "si16" /* TYPE_INT16ARRAY */:
  237. return new Int16Array(buffer);
  238. case "ur16" /* TYPE_UINT16ARRAY */:
  239. return new Uint16Array(buffer);
  240. case "si32" /* TYPE_INT32ARRAY */:
  241. return new Int32Array(buffer);
  242. case "ui32" /* TYPE_UINT32ARRAY */:
  243. return new Uint32Array(buffer);
  244. case "fl32" /* TYPE_FLOAT32ARRAY */:
  245. return new Float32Array(buffer);
  246. case "fl64" /* TYPE_FLOAT64ARRAY */:
  247. return new Float64Array(buffer);
  248. default:
  249. throw new Error('Unkown type: ' + type);
  250. }
  251. }
  252. /*! *****************************************************************************
  253. Copyright (c) Microsoft Corporation. All rights reserved.
  254. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  255. this file except in compliance with the License. You may obtain a copy of the
  256. License at http://www.apache.org/licenses/LICENSE-2.0
  257. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  258. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  259. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  260. MERCHANTABLITY OR NON-INFRINGEMENT.
  261. See the Apache Version 2.0 License for specific language governing permissions
  262. and limitations under the License.
  263. ***************************************************************************** */
  264. function __values(o) {
  265. var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
  266. if (m) return m.call(o);
  267. return {
  268. next: function () {
  269. if (o && i >= o.length) o = void 0;
  270. return { value: o && o[i++], done: !o };
  271. }
  272. };
  273. }
  274. function clone(obj) {
  275. var e_1, _a;
  276. if (obj === null || typeof (obj) !== 'object' || 'isActiveClone' in obj) {
  277. return obj;
  278. }
  279. var temp = obj instanceof Date ? new Date(obj) : (obj.constructor());
  280. try {
  281. for (var _b = __values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) {
  282. var key = _c.value;
  283. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  284. obj['isActiveClone'] = null;
  285. temp[key] = clone(obj[key]);
  286. delete obj['isActiveClone'];
  287. }
  288. }
  289. }
  290. catch (e_1_1) { e_1 = { error: e_1_1 }; }
  291. finally {
  292. try {
  293. if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
  294. }
  295. finally { if (e_1) throw e_1.error; }
  296. }
  297. return temp;
  298. }
  299. function getKeyPrefix(options, defaultConfig) {
  300. return (options.name || defaultConfig.name) + "/" + (options.storeName || defaultConfig.storeName) + "/";
  301. }
  302. function executeCallback(promise, callback) {
  303. if (callback) {
  304. promise.then(function (result) {
  305. callback(null, result);
  306. }, function (error) {
  307. callback(error);
  308. });
  309. }
  310. }
  311. function getCallback() {
  312. var _args = [];
  313. for (var _i = 0; _i < arguments.length; _i++) {
  314. _args[_i] = arguments[_i];
  315. }
  316. if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
  317. return arguments[arguments.length - 1];
  318. }
  319. }
  320. //tslint:disable-next-line:no-ignored-initial-value
  321. function dropInstanceCommon(options, callback) {
  322. var _this = this;
  323. callback = getCallback.apply(this, arguments);
  324. options = (typeof options !== 'function' && options) || {};
  325. if (!options.name) {
  326. var currentConfig = this.config();
  327. options.name = options.name || currentConfig.name;
  328. options.storeName = options.storeName || currentConfig.storeName;
  329. }
  330. var promise;
  331. if (!options.name) {
  332. promise = Promise.reject('Invalid arguments');
  333. }
  334. else {
  335. promise = new Promise(function (resolve) {
  336. if (!options.storeName) {
  337. resolve(options.name + "/");
  338. }
  339. else {
  340. resolve(getKeyPrefix(options, _this._defaultConfig));
  341. }
  342. });
  343. }
  344. return { promise: promise, callback: callback };
  345. }
  346. function normaliseKey(key) {
  347. // Cast the key to a string, as that's all we can set as a key.
  348. if (typeof key !== 'string') {
  349. console.warn(key + " used as a key, but it is not a string.");
  350. key = String(key);
  351. }
  352. return key;
  353. }
  354. var serialiser = {
  355. bufferToString: bufferToString,
  356. deserialize: deserialize,
  357. serialize: serialize,
  358. stringToBuffer: stringToBuffer
  359. };
  360. exports.serialiser = serialiser;
  361. exports.clone = clone;
  362. exports.getKeyPrefix = getKeyPrefix;
  363. exports.executeCallback = executeCallback;
  364. exports.getCallback = getCallback;
  365. exports.dropInstanceCommon = dropInstanceCommon;
  366. exports.normaliseKey = normaliseKey;
  367. Object.defineProperty(exports, '__esModule', { value: true });
  368. })));
  369. //# sourceMappingURL=umd.js.map