UNPKG

100 kBJavaScriptView Raw
1var ionicStorage = (function (exports) {
2 'use strict';
3
4 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5
6 function createCommonjsModule(fn) {
7 var module = { exports: {} };
8 return fn(module, module.exports), module.exports;
9 }
10
11 function commonjsRequire (target) {
12 throw new Error('Could not dynamically require "' + target + '". Please configure the dynamicRequireTargets option of @rollup/plugin-commonjs appropriately for this require call to behave properly.');
13 }
14
15 /*!
16 localForage -- Offline Storage, Improved
17 Version 1.9.0
18 https://localforage.github.io/localForage
19 (c) 2013-2017 Mozilla, Apache License 2.0
20 */
21
22 var localforage = createCommonjsModule(function (module, exports) {
23 (function(f){{module.exports=f();}})(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
24 (function (global){
25 var Mutation = global.MutationObserver || global.WebKitMutationObserver;
26
27 var scheduleDrain;
28
29 {
30 if (Mutation) {
31 var called = 0;
32 var observer = new Mutation(nextTick);
33 var element = global.document.createTextNode('');
34 observer.observe(element, {
35 characterData: true
36 });
37 scheduleDrain = function () {
38 element.data = (called = ++called % 2);
39 };
40 } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
41 var channel = new global.MessageChannel();
42 channel.port1.onmessage = nextTick;
43 scheduleDrain = function () {
44 channel.port2.postMessage(0);
45 };
46 } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
47 scheduleDrain = function () {
48
49 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
50 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
51 var scriptEl = global.document.createElement('script');
52 scriptEl.onreadystatechange = function () {
53 nextTick();
54
55 scriptEl.onreadystatechange = null;
56 scriptEl.parentNode.removeChild(scriptEl);
57 scriptEl = null;
58 };
59 global.document.documentElement.appendChild(scriptEl);
60 };
61 } else {
62 scheduleDrain = function () {
63 setTimeout(nextTick, 0);
64 };
65 }
66 }
67
68 var draining;
69 var queue = [];
70 //named nextTick for less confusing stack traces
71 function nextTick() {
72 draining = true;
73 var i, oldQueue;
74 var len = queue.length;
75 while (len) {
76 oldQueue = queue;
77 queue = [];
78 i = -1;
79 while (++i < len) {
80 oldQueue[i]();
81 }
82 len = queue.length;
83 }
84 draining = false;
85 }
86
87 module.exports = immediate;
88 function immediate(task) {
89 if (queue.push(task) === 1 && !draining) {
90 scheduleDrain();
91 }
92 }
93
94 }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
95 },{}],2:[function(_dereq_,module,exports){
96 var immediate = _dereq_(1);
97
98 /* istanbul ignore next */
99 function INTERNAL() {}
100
101 var handlers = {};
102
103 var REJECTED = ['REJECTED'];
104 var FULFILLED = ['FULFILLED'];
105 var PENDING = ['PENDING'];
106
107 module.exports = Promise;
108
109 function Promise(resolver) {
110 if (typeof resolver !== 'function') {
111 throw new TypeError('resolver must be a function');
112 }
113 this.state = PENDING;
114 this.queue = [];
115 this.outcome = void 0;
116 if (resolver !== INTERNAL) {
117 safelyResolveThenable(this, resolver);
118 }
119 }
120
121 Promise.prototype["catch"] = function (onRejected) {
122 return this.then(null, onRejected);
123 };
124 Promise.prototype.then = function (onFulfilled, onRejected) {
125 if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
126 typeof onRejected !== 'function' && this.state === REJECTED) {
127 return this;
128 }
129 var promise = new this.constructor(INTERNAL);
130 if (this.state !== PENDING) {
131 var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
132 unwrap(promise, resolver, this.outcome);
133 } else {
134 this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
135 }
136
137 return promise;
138 };
139 function QueueItem(promise, onFulfilled, onRejected) {
140 this.promise = promise;
141 if (typeof onFulfilled === 'function') {
142 this.onFulfilled = onFulfilled;
143 this.callFulfilled = this.otherCallFulfilled;
144 }
145 if (typeof onRejected === 'function') {
146 this.onRejected = onRejected;
147 this.callRejected = this.otherCallRejected;
148 }
149 }
150 QueueItem.prototype.callFulfilled = function (value) {
151 handlers.resolve(this.promise, value);
152 };
153 QueueItem.prototype.otherCallFulfilled = function (value) {
154 unwrap(this.promise, this.onFulfilled, value);
155 };
156 QueueItem.prototype.callRejected = function (value) {
157 handlers.reject(this.promise, value);
158 };
159 QueueItem.prototype.otherCallRejected = function (value) {
160 unwrap(this.promise, this.onRejected, value);
161 };
162
163 function unwrap(promise, func, value) {
164 immediate(function () {
165 var returnValue;
166 try {
167 returnValue = func(value);
168 } catch (e) {
169 return handlers.reject(promise, e);
170 }
171 if (returnValue === promise) {
172 handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
173 } else {
174 handlers.resolve(promise, returnValue);
175 }
176 });
177 }
178
179 handlers.resolve = function (self, value) {
180 var result = tryCatch(getThen, value);
181 if (result.status === 'error') {
182 return handlers.reject(self, result.value);
183 }
184 var thenable = result.value;
185
186 if (thenable) {
187 safelyResolveThenable(self, thenable);
188 } else {
189 self.state = FULFILLED;
190 self.outcome = value;
191 var i = -1;
192 var len = self.queue.length;
193 while (++i < len) {
194 self.queue[i].callFulfilled(value);
195 }
196 }
197 return self;
198 };
199 handlers.reject = function (self, error) {
200 self.state = REJECTED;
201 self.outcome = error;
202 var i = -1;
203 var len = self.queue.length;
204 while (++i < len) {
205 self.queue[i].callRejected(error);
206 }
207 return self;
208 };
209
210 function getThen(obj) {
211 // Make sure we only access the accessor once as required by the spec
212 var then = obj && obj.then;
213 if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
214 return function appyThen() {
215 then.apply(obj, arguments);
216 };
217 }
218 }
219
220 function safelyResolveThenable(self, thenable) {
221 // Either fulfill, reject or reject with error
222 var called = false;
223 function onError(value) {
224 if (called) {
225 return;
226 }
227 called = true;
228 handlers.reject(self, value);
229 }
230
231 function onSuccess(value) {
232 if (called) {
233 return;
234 }
235 called = true;
236 handlers.resolve(self, value);
237 }
238
239 function tryToUnwrap() {
240 thenable(onSuccess, onError);
241 }
242
243 var result = tryCatch(tryToUnwrap);
244 if (result.status === 'error') {
245 onError(result.value);
246 }
247 }
248
249 function tryCatch(func, value) {
250 var out = {};
251 try {
252 out.value = func(value);
253 out.status = 'success';
254 } catch (e) {
255 out.status = 'error';
256 out.value = e;
257 }
258 return out;
259 }
260
261 Promise.resolve = resolve;
262 function resolve(value) {
263 if (value instanceof this) {
264 return value;
265 }
266 return handlers.resolve(new this(INTERNAL), value);
267 }
268
269 Promise.reject = reject;
270 function reject(reason) {
271 var promise = new this(INTERNAL);
272 return handlers.reject(promise, reason);
273 }
274
275 Promise.all = all;
276 function all(iterable) {
277 var self = this;
278 if (Object.prototype.toString.call(iterable) !== '[object Array]') {
279 return this.reject(new TypeError('must be an array'));
280 }
281
282 var len = iterable.length;
283 var called = false;
284 if (!len) {
285 return this.resolve([]);
286 }
287
288 var values = new Array(len);
289 var resolved = 0;
290 var i = -1;
291 var promise = new this(INTERNAL);
292
293 while (++i < len) {
294 allResolver(iterable[i], i);
295 }
296 return promise;
297 function allResolver(value, i) {
298 self.resolve(value).then(resolveFromAll, function (error) {
299 if (!called) {
300 called = true;
301 handlers.reject(promise, error);
302 }
303 });
304 function resolveFromAll(outValue) {
305 values[i] = outValue;
306 if (++resolved === len && !called) {
307 called = true;
308 handlers.resolve(promise, values);
309 }
310 }
311 }
312 }
313
314 Promise.race = race;
315 function race(iterable) {
316 var self = this;
317 if (Object.prototype.toString.call(iterable) !== '[object Array]') {
318 return this.reject(new TypeError('must be an array'));
319 }
320
321 var len = iterable.length;
322 var called = false;
323 if (!len) {
324 return this.resolve([]);
325 }
326
327 var i = -1;
328 var promise = new this(INTERNAL);
329
330 while (++i < len) {
331 resolver(iterable[i]);
332 }
333 return promise;
334 function resolver(value) {
335 self.resolve(value).then(function (response) {
336 if (!called) {
337 called = true;
338 handlers.resolve(promise, response);
339 }
340 }, function (error) {
341 if (!called) {
342 called = true;
343 handlers.reject(promise, error);
344 }
345 });
346 }
347 }
348
349 },{"1":1}],3:[function(_dereq_,module,exports){
350 (function (global){
351 if (typeof global.Promise !== 'function') {
352 global.Promise = _dereq_(2);
353 }
354
355 }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
356 },{"2":2}],4:[function(_dereq_,module,exports){
357
358 var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
359
360 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
361
362 function getIDB() {
363 /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
364 try {
365 if (typeof indexedDB !== 'undefined') {
366 return indexedDB;
367 }
368 if (typeof webkitIndexedDB !== 'undefined') {
369 return webkitIndexedDB;
370 }
371 if (typeof mozIndexedDB !== 'undefined') {
372 return mozIndexedDB;
373 }
374 if (typeof OIndexedDB !== 'undefined') {
375 return OIndexedDB;
376 }
377 if (typeof msIndexedDB !== 'undefined') {
378 return msIndexedDB;
379 }
380 } catch (e) {
381 return;
382 }
383 }
384
385 var idb = getIDB();
386
387 function isIndexedDBValid() {
388 try {
389 // Initialize IndexedDB; fall back to vendor-prefixed versions
390 // if needed.
391 if (!idb || !idb.open) {
392 return false;
393 }
394 // We mimic PouchDB here;
395 //
396 // We test for openDatabase because IE Mobile identifies itself
397 // as Safari. Oh the lulz...
398 var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
399
400 var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
401
402 // Safari <10.1 does not meet our requirements for IDB support
403 // (see: https://github.com/pouchdb/pouchdb/issues/5572).
404 // Safari 10.1 shipped with fetch, we can use that to detect it.
405 // Note: this creates issues with `window.fetch` polyfills and
406 // overrides; see:
407 // https://github.com/localForage/localForage/issues/856
408 return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
409 // some outdated implementations of IDB that appear on Samsung
410 // and HTC Android devices <4.4 are missing IDBKeyRange
411 // See: https://github.com/mozilla/localForage/issues/128
412 // See: https://github.com/mozilla/localForage/issues/272
413 typeof IDBKeyRange !== 'undefined';
414 } catch (e) {
415 return false;
416 }
417 }
418
419 // Abstracts constructing a Blob object, so it also works in older
420 // browsers that don't support the native Blob constructor. (i.e.
421 // old QtWebKit versions, at least).
422 // Abstracts constructing a Blob object, so it also works in older
423 // browsers that don't support the native Blob constructor. (i.e.
424 // old QtWebKit versions, at least).
425 function createBlob(parts, properties) {
426 /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
427 parts = parts || [];
428 properties = properties || {};
429 try {
430 return new Blob(parts, properties);
431 } catch (e) {
432 if (e.name !== 'TypeError') {
433 throw e;
434 }
435 var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
436 var builder = new Builder();
437 for (var i = 0; i < parts.length; i += 1) {
438 builder.append(parts[i]);
439 }
440 return builder.getBlob(properties.type);
441 }
442 }
443
444 // This is CommonJS because lie is an external dependency, so Rollup
445 // can just ignore it.
446 if (typeof Promise === 'undefined') {
447 // In the "nopromises" build this will just throw if you don't have
448 // a global promise object, but it would throw anyway later.
449 _dereq_(3);
450 }
451 var Promise$1 = Promise;
452
453 function executeCallback(promise, callback) {
454 if (callback) {
455 promise.then(function (result) {
456 callback(null, result);
457 }, function (error) {
458 callback(error);
459 });
460 }
461 }
462
463 function executeTwoCallbacks(promise, callback, errorCallback) {
464 if (typeof callback === 'function') {
465 promise.then(callback);
466 }
467
468 if (typeof errorCallback === 'function') {
469 promise["catch"](errorCallback);
470 }
471 }
472
473 function normalizeKey(key) {
474 // Cast the key to a string, as that's all we can set as a key.
475 if (typeof key !== 'string') {
476 console.warn(key + ' used as a key, but it is not a string.');
477 key = String(key);
478 }
479
480 return key;
481 }
482
483 function getCallback() {
484 if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
485 return arguments[arguments.length - 1];
486 }
487 }
488
489 // Some code originally from async_storage.js in
490 // [Gaia](https://github.com/mozilla-b2g/gaia).
491
492 var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
493 var supportsBlobs = void 0;
494 var dbContexts = {};
495 var toString = Object.prototype.toString;
496
497 // Transaction Modes
498 var READ_ONLY = 'readonly';
499 var READ_WRITE = 'readwrite';
500
501 // Transform a binary string to an array buffer, because otherwise
502 // weird stuff happens when you try to work with the binary string directly.
503 // It is known.
504 // From http://stackoverflow.com/questions/14967647/ (continues on next line)
505 // encode-decode-image-with-base64-breaks-image (2013-04-21)
506 function _binStringToArrayBuffer(bin) {
507 var length = bin.length;
508 var buf = new ArrayBuffer(length);
509 var arr = new Uint8Array(buf);
510 for (var i = 0; i < length; i++) {
511 arr[i] = bin.charCodeAt(i);
512 }
513 return buf;
514 }
515
516 //
517 // Blobs are not supported in all versions of IndexedDB, notably
518 // Chrome <37 and Android <5. In those versions, storing a blob will throw.
519 //
520 // Various other blob bugs exist in Chrome v37-42 (inclusive).
521 // Detecting them is expensive and confusing to users, and Chrome 37-42
522 // is at very low usage worldwide, so we do a hacky userAgent check instead.
523 //
524 // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
525 // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
526 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
527 //
528 // Code borrowed from PouchDB. See:
529 // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
530 //
531 function _checkBlobSupportWithoutCaching(idb) {
532 return new Promise$1(function (resolve) {
533 var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
534 var blob = createBlob(['']);
535 txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
536
537 txn.onabort = function (e) {
538 // If the transaction aborts now its due to not being able to
539 // write to the database, likely due to the disk being full
540 e.preventDefault();
541 e.stopPropagation();
542 resolve(false);
543 };
544
545 txn.oncomplete = function () {
546 var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
547 var matchedEdge = navigator.userAgent.match(/Edge\//);
548 // MS Edge pretends to be Chrome 42:
549 // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
550 resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
551 };
552 })["catch"](function () {
553 return false; // error, so assume unsupported
554 });
555 }
556
557 function _checkBlobSupport(idb) {
558 if (typeof supportsBlobs === 'boolean') {
559 return Promise$1.resolve(supportsBlobs);
560 }
561 return _checkBlobSupportWithoutCaching(idb).then(function (value) {
562 supportsBlobs = value;
563 return supportsBlobs;
564 });
565 }
566
567 function _deferReadiness(dbInfo) {
568 var dbContext = dbContexts[dbInfo.name];
569
570 // Create a deferred object representing the current database operation.
571 var deferredOperation = {};
572
573 deferredOperation.promise = new Promise$1(function (resolve, reject) {
574 deferredOperation.resolve = resolve;
575 deferredOperation.reject = reject;
576 });
577
578 // Enqueue the deferred operation.
579 dbContext.deferredOperations.push(deferredOperation);
580
581 // Chain its promise to the database readiness.
582 if (!dbContext.dbReady) {
583 dbContext.dbReady = deferredOperation.promise;
584 } else {
585 dbContext.dbReady = dbContext.dbReady.then(function () {
586 return deferredOperation.promise;
587 });
588 }
589 }
590
591 function _advanceReadiness(dbInfo) {
592 var dbContext = dbContexts[dbInfo.name];
593
594 // Dequeue a deferred operation.
595 var deferredOperation = dbContext.deferredOperations.pop();
596
597 // Resolve its promise (which is part of the database readiness
598 // chain of promises).
599 if (deferredOperation) {
600 deferredOperation.resolve();
601 return deferredOperation.promise;
602 }
603 }
604
605 function _rejectReadiness(dbInfo, err) {
606 var dbContext = dbContexts[dbInfo.name];
607
608 // Dequeue a deferred operation.
609 var deferredOperation = dbContext.deferredOperations.pop();
610
611 // Reject its promise (which is part of the database readiness
612 // chain of promises).
613 if (deferredOperation) {
614 deferredOperation.reject(err);
615 return deferredOperation.promise;
616 }
617 }
618
619 function _getConnection(dbInfo, upgradeNeeded) {
620 return new Promise$1(function (resolve, reject) {
621 dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
622
623 if (dbInfo.db) {
624 if (upgradeNeeded) {
625 _deferReadiness(dbInfo);
626 dbInfo.db.close();
627 } else {
628 return resolve(dbInfo.db);
629 }
630 }
631
632 var dbArgs = [dbInfo.name];
633
634 if (upgradeNeeded) {
635 dbArgs.push(dbInfo.version);
636 }
637
638 var openreq = idb.open.apply(idb, dbArgs);
639
640 if (upgradeNeeded) {
641 openreq.onupgradeneeded = function (e) {
642 var db = openreq.result;
643 try {
644 db.createObjectStore(dbInfo.storeName);
645 if (e.oldVersion <= 1) {
646 // Added when support for blob shims was added
647 db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
648 }
649 } catch (ex) {
650 if (ex.name === 'ConstraintError') {
651 console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
652 } else {
653 throw ex;
654 }
655 }
656 };
657 }
658
659 openreq.onerror = function (e) {
660 e.preventDefault();
661 reject(openreq.error);
662 };
663
664 openreq.onsuccess = function () {
665 resolve(openreq.result);
666 _advanceReadiness(dbInfo);
667 };
668 });
669 }
670
671 function _getOriginalConnection(dbInfo) {
672 return _getConnection(dbInfo, false);
673 }
674
675 function _getUpgradedConnection(dbInfo) {
676 return _getConnection(dbInfo, true);
677 }
678
679 function _isUpgradeNeeded(dbInfo, defaultVersion) {
680 if (!dbInfo.db) {
681 return true;
682 }
683
684 var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
685 var isDowngrade = dbInfo.version < dbInfo.db.version;
686 var isUpgrade = dbInfo.version > dbInfo.db.version;
687
688 if (isDowngrade) {
689 // If the version is not the default one
690 // then warn for impossible downgrade.
691 if (dbInfo.version !== defaultVersion) {
692 console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
693 }
694 // Align the versions to prevent errors.
695 dbInfo.version = dbInfo.db.version;
696 }
697
698 if (isUpgrade || isNewStore) {
699 // If the store is new then increment the version (if needed).
700 // This will trigger an "upgradeneeded" event which is required
701 // for creating a store.
702 if (isNewStore) {
703 var incVersion = dbInfo.db.version + 1;
704 if (incVersion > dbInfo.version) {
705 dbInfo.version = incVersion;
706 }
707 }
708
709 return true;
710 }
711
712 return false;
713 }
714
715 // encode a blob for indexeddb engines that don't support blobs
716 function _encodeBlob(blob) {
717 return new Promise$1(function (resolve, reject) {
718 var reader = new FileReader();
719 reader.onerror = reject;
720 reader.onloadend = function (e) {
721 var base64 = btoa(e.target.result || '');
722 resolve({
723 __local_forage_encoded_blob: true,
724 data: base64,
725 type: blob.type
726 });
727 };
728 reader.readAsBinaryString(blob);
729 });
730 }
731
732 // decode an encoded blob
733 function _decodeBlob(encodedBlob) {
734 var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
735 return createBlob([arrayBuff], { type: encodedBlob.type });
736 }
737
738 // is this one of our fancy encoded blobs?
739 function _isEncodedBlob(value) {
740 return value && value.__local_forage_encoded_blob;
741 }
742
743 // Specialize the default `ready()` function by making it dependent
744 // on the current database operations. Thus, the driver will be actually
745 // ready when it's been initialized (default) *and* there are no pending
746 // operations on the database (initiated by some other instances).
747 function _fullyReady(callback) {
748 var self = this;
749
750 var promise = self._initReady().then(function () {
751 var dbContext = dbContexts[self._dbInfo.name];
752
753 if (dbContext && dbContext.dbReady) {
754 return dbContext.dbReady;
755 }
756 });
757
758 executeTwoCallbacks(promise, callback, callback);
759 return promise;
760 }
761
762 // Try to establish a new db connection to replace the
763 // current one which is broken (i.e. experiencing
764 // InvalidStateError while creating a transaction).
765 function _tryReconnect(dbInfo) {
766 _deferReadiness(dbInfo);
767
768 var dbContext = dbContexts[dbInfo.name];
769 var forages = dbContext.forages;
770
771 for (var i = 0; i < forages.length; i++) {
772 var forage = forages[i];
773 if (forage._dbInfo.db) {
774 forage._dbInfo.db.close();
775 forage._dbInfo.db = null;
776 }
777 }
778 dbInfo.db = null;
779
780 return _getOriginalConnection(dbInfo).then(function (db) {
781 dbInfo.db = db;
782 if (_isUpgradeNeeded(dbInfo)) {
783 // Reopen the database for upgrading.
784 return _getUpgradedConnection(dbInfo);
785 }
786 return db;
787 }).then(function (db) {
788 // store the latest db reference
789 // in case the db was upgraded
790 dbInfo.db = dbContext.db = db;
791 for (var i = 0; i < forages.length; i++) {
792 forages[i]._dbInfo.db = db;
793 }
794 })["catch"](function (err) {
795 _rejectReadiness(dbInfo, err);
796 throw err;
797 });
798 }
799
800 // FF doesn't like Promises (micro-tasks) and IDDB store operations,
801 // so we have to do it with callbacks
802 function createTransaction(dbInfo, mode, callback, retries) {
803 if (retries === undefined) {
804 retries = 1;
805 }
806
807 try {
808 var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
809 callback(null, tx);
810 } catch (err) {
811 if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
812 return Promise$1.resolve().then(function () {
813 if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
814 // increase the db version, to create the new ObjectStore
815 if (dbInfo.db) {
816 dbInfo.version = dbInfo.db.version + 1;
817 }
818 // Reopen the database for upgrading.
819 return _getUpgradedConnection(dbInfo);
820 }
821 }).then(function () {
822 return _tryReconnect(dbInfo).then(function () {
823 createTransaction(dbInfo, mode, callback, retries - 1);
824 });
825 })["catch"](callback);
826 }
827
828 callback(err);
829 }
830 }
831
832 function createDbContext() {
833 return {
834 // Running localForages sharing a database.
835 forages: [],
836 // Shared database.
837 db: null,
838 // Database readiness (promise).
839 dbReady: null,
840 // Deferred operations on the database.
841 deferredOperations: []
842 };
843 }
844
845 // Open the IndexedDB database (automatically creates one if one didn't
846 // previously exist), using any options set in the config.
847 function _initStorage(options) {
848 var self = this;
849 var dbInfo = {
850 db: null
851 };
852
853 if (options) {
854 for (var i in options) {
855 dbInfo[i] = options[i];
856 }
857 }
858
859 // Get the current context of the database;
860 var dbContext = dbContexts[dbInfo.name];
861
862 // ...or create a new context.
863 if (!dbContext) {
864 dbContext = createDbContext();
865 // Register the new context in the global container.
866 dbContexts[dbInfo.name] = dbContext;
867 }
868
869 // Register itself as a running localForage in the current context.
870 dbContext.forages.push(self);
871
872 // Replace the default `ready()` function with the specialized one.
873 if (!self._initReady) {
874 self._initReady = self.ready;
875 self.ready = _fullyReady;
876 }
877
878 // Create an array of initialization states of the related localForages.
879 var initPromises = [];
880
881 function ignoreErrors() {
882 // Don't handle errors here,
883 // just makes sure related localForages aren't pending.
884 return Promise$1.resolve();
885 }
886
887 for (var j = 0; j < dbContext.forages.length; j++) {
888 var forage = dbContext.forages[j];
889 if (forage !== self) {
890 // Don't wait for itself...
891 initPromises.push(forage._initReady()["catch"](ignoreErrors));
892 }
893 }
894
895 // Take a snapshot of the related localForages.
896 var forages = dbContext.forages.slice(0);
897
898 // Initialize the connection process only when
899 // all the related localForages aren't pending.
900 return Promise$1.all(initPromises).then(function () {
901 dbInfo.db = dbContext.db;
902 // Get the connection or open a new one without upgrade.
903 return _getOriginalConnection(dbInfo);
904 }).then(function (db) {
905 dbInfo.db = db;
906 if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
907 // Reopen the database for upgrading.
908 return _getUpgradedConnection(dbInfo);
909 }
910 return db;
911 }).then(function (db) {
912 dbInfo.db = dbContext.db = db;
913 self._dbInfo = dbInfo;
914 // Share the final connection amongst related localForages.
915 for (var k = 0; k < forages.length; k++) {
916 var forage = forages[k];
917 if (forage !== self) {
918 // Self is already up-to-date.
919 forage._dbInfo.db = dbInfo.db;
920 forage._dbInfo.version = dbInfo.version;
921 }
922 }
923 });
924 }
925
926 function getItem(key, callback) {
927 var self = this;
928
929 key = normalizeKey(key);
930
931 var promise = new Promise$1(function (resolve, reject) {
932 self.ready().then(function () {
933 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
934 if (err) {
935 return reject(err);
936 }
937
938 try {
939 var store = transaction.objectStore(self._dbInfo.storeName);
940 var req = store.get(key);
941
942 req.onsuccess = function () {
943 var value = req.result;
944 if (value === undefined) {
945 value = null;
946 }
947 if (_isEncodedBlob(value)) {
948 value = _decodeBlob(value);
949 }
950 resolve(value);
951 };
952
953 req.onerror = function () {
954 reject(req.error);
955 };
956 } catch (e) {
957 reject(e);
958 }
959 });
960 })["catch"](reject);
961 });
962
963 executeCallback(promise, callback);
964 return promise;
965 }
966
967 // Iterate over all items stored in database.
968 function iterate(iterator, callback) {
969 var self = this;
970
971 var promise = new Promise$1(function (resolve, reject) {
972 self.ready().then(function () {
973 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
974 if (err) {
975 return reject(err);
976 }
977
978 try {
979 var store = transaction.objectStore(self._dbInfo.storeName);
980 var req = store.openCursor();
981 var iterationNumber = 1;
982
983 req.onsuccess = function () {
984 var cursor = req.result;
985
986 if (cursor) {
987 var value = cursor.value;
988 if (_isEncodedBlob(value)) {
989 value = _decodeBlob(value);
990 }
991 var result = iterator(value, cursor.key, iterationNumber++);
992
993 // when the iterator callback returns any
994 // (non-`undefined`) value, then we stop
995 // the iteration immediately
996 if (result !== void 0) {
997 resolve(result);
998 } else {
999 cursor["continue"]();
1000 }
1001 } else {
1002 resolve();
1003 }
1004 };
1005
1006 req.onerror = function () {
1007 reject(req.error);
1008 };
1009 } catch (e) {
1010 reject(e);
1011 }
1012 });
1013 })["catch"](reject);
1014 });
1015
1016 executeCallback(promise, callback);
1017
1018 return promise;
1019 }
1020
1021 function setItem(key, value, callback) {
1022 var self = this;
1023
1024 key = normalizeKey(key);
1025
1026 var promise = new Promise$1(function (resolve, reject) {
1027 var dbInfo;
1028 self.ready().then(function () {
1029 dbInfo = self._dbInfo;
1030 if (toString.call(value) === '[object Blob]') {
1031 return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
1032 if (blobSupport) {
1033 return value;
1034 }
1035 return _encodeBlob(value);
1036 });
1037 }
1038 return value;
1039 }).then(function (value) {
1040 createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1041 if (err) {
1042 return reject(err);
1043 }
1044
1045 try {
1046 var store = transaction.objectStore(self._dbInfo.storeName);
1047
1048 // The reason we don't _save_ null is because IE 10 does
1049 // not support saving the `null` type in IndexedDB. How
1050 // ironic, given the bug below!
1051 // See: https://github.com/mozilla/localForage/issues/161
1052 if (value === null) {
1053 value = undefined;
1054 }
1055
1056 var req = store.put(value, key);
1057
1058 transaction.oncomplete = function () {
1059 // Cast to undefined so the value passed to
1060 // callback/promise is the same as what one would get out
1061 // of `getItem()` later. This leads to some weirdness
1062 // (setItem('foo', undefined) will return `null`), but
1063 // it's not my fault localStorage is our baseline and that
1064 // it's weird.
1065 if (value === undefined) {
1066 value = null;
1067 }
1068
1069 resolve(value);
1070 };
1071 transaction.onabort = transaction.onerror = function () {
1072 var err = req.error ? req.error : req.transaction.error;
1073 reject(err);
1074 };
1075 } catch (e) {
1076 reject(e);
1077 }
1078 });
1079 })["catch"](reject);
1080 });
1081
1082 executeCallback(promise, callback);
1083 return promise;
1084 }
1085
1086 function removeItem(key, callback) {
1087 var self = this;
1088
1089 key = normalizeKey(key);
1090
1091 var promise = new Promise$1(function (resolve, reject) {
1092 self.ready().then(function () {
1093 createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1094 if (err) {
1095 return reject(err);
1096 }
1097
1098 try {
1099 var store = transaction.objectStore(self._dbInfo.storeName);
1100 // We use a Grunt task to make this safe for IE and some
1101 // versions of Android (including those used by Cordova).
1102 // Normally IE won't like `.delete()` and will insist on
1103 // using `['delete']()`, but we have a build step that
1104 // fixes this for us now.
1105 var req = store["delete"](key);
1106 transaction.oncomplete = function () {
1107 resolve();
1108 };
1109
1110 transaction.onerror = function () {
1111 reject(req.error);
1112 };
1113
1114 // The request will be also be aborted if we've exceeded our storage
1115 // space.
1116 transaction.onabort = function () {
1117 var err = req.error ? req.error : req.transaction.error;
1118 reject(err);
1119 };
1120 } catch (e) {
1121 reject(e);
1122 }
1123 });
1124 })["catch"](reject);
1125 });
1126
1127 executeCallback(promise, callback);
1128 return promise;
1129 }
1130
1131 function clear(callback) {
1132 var self = this;
1133
1134 var promise = new Promise$1(function (resolve, reject) {
1135 self.ready().then(function () {
1136 createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1137 if (err) {
1138 return reject(err);
1139 }
1140
1141 try {
1142 var store = transaction.objectStore(self._dbInfo.storeName);
1143 var req = store.clear();
1144
1145 transaction.oncomplete = function () {
1146 resolve();
1147 };
1148
1149 transaction.onabort = transaction.onerror = function () {
1150 var err = req.error ? req.error : req.transaction.error;
1151 reject(err);
1152 };
1153 } catch (e) {
1154 reject(e);
1155 }
1156 });
1157 })["catch"](reject);
1158 });
1159
1160 executeCallback(promise, callback);
1161 return promise;
1162 }
1163
1164 function length(callback) {
1165 var self = this;
1166
1167 var promise = new Promise$1(function (resolve, reject) {
1168 self.ready().then(function () {
1169 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1170 if (err) {
1171 return reject(err);
1172 }
1173
1174 try {
1175 var store = transaction.objectStore(self._dbInfo.storeName);
1176 var req = store.count();
1177
1178 req.onsuccess = function () {
1179 resolve(req.result);
1180 };
1181
1182 req.onerror = function () {
1183 reject(req.error);
1184 };
1185 } catch (e) {
1186 reject(e);
1187 }
1188 });
1189 })["catch"](reject);
1190 });
1191
1192 executeCallback(promise, callback);
1193 return promise;
1194 }
1195
1196 function key(n, callback) {
1197 var self = this;
1198
1199 var promise = new Promise$1(function (resolve, reject) {
1200 if (n < 0) {
1201 resolve(null);
1202
1203 return;
1204 }
1205
1206 self.ready().then(function () {
1207 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1208 if (err) {
1209 return reject(err);
1210 }
1211
1212 try {
1213 var store = transaction.objectStore(self._dbInfo.storeName);
1214 var advanced = false;
1215 var req = store.openKeyCursor();
1216
1217 req.onsuccess = function () {
1218 var cursor = req.result;
1219 if (!cursor) {
1220 // this means there weren't enough keys
1221 resolve(null);
1222
1223 return;
1224 }
1225
1226 if (n === 0) {
1227 // We have the first key, return it if that's what they
1228 // wanted.
1229 resolve(cursor.key);
1230 } else {
1231 if (!advanced) {
1232 // Otherwise, ask the cursor to skip ahead n
1233 // records.
1234 advanced = true;
1235 cursor.advance(n);
1236 } else {
1237 // When we get here, we've got the nth key.
1238 resolve(cursor.key);
1239 }
1240 }
1241 };
1242
1243 req.onerror = function () {
1244 reject(req.error);
1245 };
1246 } catch (e) {
1247 reject(e);
1248 }
1249 });
1250 })["catch"](reject);
1251 });
1252
1253 executeCallback(promise, callback);
1254 return promise;
1255 }
1256
1257 function keys(callback) {
1258 var self = this;
1259
1260 var promise = new Promise$1(function (resolve, reject) {
1261 self.ready().then(function () {
1262 createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1263 if (err) {
1264 return reject(err);
1265 }
1266
1267 try {
1268 var store = transaction.objectStore(self._dbInfo.storeName);
1269 var req = store.openKeyCursor();
1270 var keys = [];
1271
1272 req.onsuccess = function () {
1273 var cursor = req.result;
1274
1275 if (!cursor) {
1276 resolve(keys);
1277 return;
1278 }
1279
1280 keys.push(cursor.key);
1281 cursor["continue"]();
1282 };
1283
1284 req.onerror = function () {
1285 reject(req.error);
1286 };
1287 } catch (e) {
1288 reject(e);
1289 }
1290 });
1291 })["catch"](reject);
1292 });
1293
1294 executeCallback(promise, callback);
1295 return promise;
1296 }
1297
1298 function dropInstance(options, callback) {
1299 callback = getCallback.apply(this, arguments);
1300
1301 var currentConfig = this.config();
1302 options = typeof options !== 'function' && options || {};
1303 if (!options.name) {
1304 options.name = options.name || currentConfig.name;
1305 options.storeName = options.storeName || currentConfig.storeName;
1306 }
1307
1308 var self = this;
1309 var promise;
1310 if (!options.name) {
1311 promise = Promise$1.reject('Invalid arguments');
1312 } else {
1313 var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
1314
1315 var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
1316 var dbContext = dbContexts[options.name];
1317 var forages = dbContext.forages;
1318 dbContext.db = db;
1319 for (var i = 0; i < forages.length; i++) {
1320 forages[i]._dbInfo.db = db;
1321 }
1322 return db;
1323 });
1324
1325 if (!options.storeName) {
1326 promise = dbPromise.then(function (db) {
1327 _deferReadiness(options);
1328
1329 var dbContext = dbContexts[options.name];
1330 var forages = dbContext.forages;
1331
1332 db.close();
1333 for (var i = 0; i < forages.length; i++) {
1334 var forage = forages[i];
1335 forage._dbInfo.db = null;
1336 }
1337
1338 var dropDBPromise = new Promise$1(function (resolve, reject) {
1339 var req = idb.deleteDatabase(options.name);
1340
1341 req.onerror = req.onblocked = function (err) {
1342 var db = req.result;
1343 if (db) {
1344 db.close();
1345 }
1346 reject(err);
1347 };
1348
1349 req.onsuccess = function () {
1350 var db = req.result;
1351 if (db) {
1352 db.close();
1353 }
1354 resolve(db);
1355 };
1356 });
1357
1358 return dropDBPromise.then(function (db) {
1359 dbContext.db = db;
1360 for (var i = 0; i < forages.length; i++) {
1361 var _forage = forages[i];
1362 _advanceReadiness(_forage._dbInfo);
1363 }
1364 })["catch"](function (err) {
1365 (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1366 throw err;
1367 });
1368 });
1369 } else {
1370 promise = dbPromise.then(function (db) {
1371 if (!db.objectStoreNames.contains(options.storeName)) {
1372 return;
1373 }
1374
1375 var newVersion = db.version + 1;
1376
1377 _deferReadiness(options);
1378
1379 var dbContext = dbContexts[options.name];
1380 var forages = dbContext.forages;
1381
1382 db.close();
1383 for (var i = 0; i < forages.length; i++) {
1384 var forage = forages[i];
1385 forage._dbInfo.db = null;
1386 forage._dbInfo.version = newVersion;
1387 }
1388
1389 var dropObjectPromise = new Promise$1(function (resolve, reject) {
1390 var req = idb.open(options.name, newVersion);
1391
1392 req.onerror = function (err) {
1393 var db = req.result;
1394 db.close();
1395 reject(err);
1396 };
1397
1398 req.onupgradeneeded = function () {
1399 var db = req.result;
1400 db.deleteObjectStore(options.storeName);
1401 };
1402
1403 req.onsuccess = function () {
1404 var db = req.result;
1405 db.close();
1406 resolve(db);
1407 };
1408 });
1409
1410 return dropObjectPromise.then(function (db) {
1411 dbContext.db = db;
1412 for (var j = 0; j < forages.length; j++) {
1413 var _forage2 = forages[j];
1414 _forage2._dbInfo.db = db;
1415 _advanceReadiness(_forage2._dbInfo);
1416 }
1417 })["catch"](function (err) {
1418 (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1419 throw err;
1420 });
1421 });
1422 }
1423 }
1424
1425 executeCallback(promise, callback);
1426 return promise;
1427 }
1428
1429 var asyncStorage = {
1430 _driver: 'asyncStorage',
1431 _initStorage: _initStorage,
1432 _support: isIndexedDBValid(),
1433 iterate: iterate,
1434 getItem: getItem,
1435 setItem: setItem,
1436 removeItem: removeItem,
1437 clear: clear,
1438 length: length,
1439 key: key,
1440 keys: keys,
1441 dropInstance: dropInstance
1442 };
1443
1444 function isWebSQLValid() {
1445 return typeof openDatabase === 'function';
1446 }
1447
1448 // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
1449 // it to Base64, so this is how we store it to prevent very strange errors with less
1450 // verbose ways of binary <-> string data storage.
1451 var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1452
1453 var BLOB_TYPE_PREFIX = '~~local_forage_type~';
1454 var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
1455
1456 var SERIALIZED_MARKER = '__lfsc__:';
1457 var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
1458
1459 // OMG the serializations!
1460 var TYPE_ARRAYBUFFER = 'arbf';
1461 var TYPE_BLOB = 'blob';
1462 var TYPE_INT8ARRAY = 'si08';
1463 var TYPE_UINT8ARRAY = 'ui08';
1464 var TYPE_UINT8CLAMPEDARRAY = 'uic8';
1465 var TYPE_INT16ARRAY = 'si16';
1466 var TYPE_INT32ARRAY = 'si32';
1467 var TYPE_UINT16ARRAY = 'ur16';
1468 var TYPE_UINT32ARRAY = 'ui32';
1469 var TYPE_FLOAT32ARRAY = 'fl32';
1470 var TYPE_FLOAT64ARRAY = 'fl64';
1471 var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
1472
1473 var toString$1 = Object.prototype.toString;
1474
1475 function stringToBuffer(serializedString) {
1476 // Fill the string into a ArrayBuffer.
1477 var bufferLength = serializedString.length * 0.75;
1478 var len = serializedString.length;
1479 var i;
1480 var p = 0;
1481 var encoded1, encoded2, encoded3, encoded4;
1482
1483 if (serializedString[serializedString.length - 1] === '=') {
1484 bufferLength--;
1485 if (serializedString[serializedString.length - 2] === '=') {
1486 bufferLength--;
1487 }
1488 }
1489
1490 var buffer = new ArrayBuffer(bufferLength);
1491 var bytes = new Uint8Array(buffer);
1492
1493 for (i = 0; i < len; i += 4) {
1494 encoded1 = BASE_CHARS.indexOf(serializedString[i]);
1495 encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
1496 encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
1497 encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
1498
1499 /*jslint bitwise: true */
1500 bytes[p++] = encoded1 << 2 | encoded2 >> 4;
1501 bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
1502 bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
1503 }
1504 return buffer;
1505 }
1506
1507 // Converts a buffer to a string to store, serialized, in the backend
1508 // storage library.
1509 function bufferToString(buffer) {
1510 // base64-arraybuffer
1511 var bytes = new Uint8Array(buffer);
1512 var base64String = '';
1513 var i;
1514
1515 for (i = 0; i < bytes.length; i += 3) {
1516 /*jslint bitwise: true */
1517 base64String += BASE_CHARS[bytes[i] >> 2];
1518 base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
1519 base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
1520 base64String += BASE_CHARS[bytes[i + 2] & 63];
1521 }
1522
1523 if (bytes.length % 3 === 2) {
1524 base64String = base64String.substring(0, base64String.length - 1) + '=';
1525 } else if (bytes.length % 3 === 1) {
1526 base64String = base64String.substring(0, base64String.length - 2) + '==';
1527 }
1528
1529 return base64String;
1530 }
1531
1532 // Serialize a value, afterwards executing a callback (which usually
1533 // instructs the `setItem()` callback/promise to be executed). This is how
1534 // we store binary data with localStorage.
1535 function serialize(value, callback) {
1536 var valueType = '';
1537 if (value) {
1538 valueType = toString$1.call(value);
1539 }
1540
1541 // Cannot use `value instanceof ArrayBuffer` or such here, as these
1542 // checks fail when running the tests using casper.js...
1543 //
1544 // TODO: See why those tests fail and use a better solution.
1545 if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
1546 // Convert binary arrays to a string and prefix the string with
1547 // a special marker.
1548 var buffer;
1549 var marker = SERIALIZED_MARKER;
1550
1551 if (value instanceof ArrayBuffer) {
1552 buffer = value;
1553 marker += TYPE_ARRAYBUFFER;
1554 } else {
1555 buffer = value.buffer;
1556
1557 if (valueType === '[object Int8Array]') {
1558 marker += TYPE_INT8ARRAY;
1559 } else if (valueType === '[object Uint8Array]') {
1560 marker += TYPE_UINT8ARRAY;
1561 } else if (valueType === '[object Uint8ClampedArray]') {
1562 marker += TYPE_UINT8CLAMPEDARRAY;
1563 } else if (valueType === '[object Int16Array]') {
1564 marker += TYPE_INT16ARRAY;
1565 } else if (valueType === '[object Uint16Array]') {
1566 marker += TYPE_UINT16ARRAY;
1567 } else if (valueType === '[object Int32Array]') {
1568 marker += TYPE_INT32ARRAY;
1569 } else if (valueType === '[object Uint32Array]') {
1570 marker += TYPE_UINT32ARRAY;
1571 } else if (valueType === '[object Float32Array]') {
1572 marker += TYPE_FLOAT32ARRAY;
1573 } else if (valueType === '[object Float64Array]') {
1574 marker += TYPE_FLOAT64ARRAY;
1575 } else {
1576 callback(new Error('Failed to get type for BinaryArray'));
1577 }
1578 }
1579
1580 callback(marker + bufferToString(buffer));
1581 } else if (valueType === '[object Blob]') {
1582 // Conver the blob to a binaryArray and then to a string.
1583 var fileReader = new FileReader();
1584
1585 fileReader.onload = function () {
1586 // Backwards-compatible prefix for the blob type.
1587 var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
1588
1589 callback(SERIALIZED_MARKER + TYPE_BLOB + str);
1590 };
1591
1592 fileReader.readAsArrayBuffer(value);
1593 } else {
1594 try {
1595 callback(JSON.stringify(value));
1596 } catch (e) {
1597 console.error("Couldn't convert value into a JSON string: ", value);
1598
1599 callback(null, e);
1600 }
1601 }
1602 }
1603
1604 // Deserialize data we've inserted into a value column/field. We place
1605 // special markers into our strings to mark them as encoded; this isn't
1606 // as nice as a meta field, but it's the only sane thing we can do whilst
1607 // keeping localStorage support intact.
1608 //
1609 // Oftentimes this will just deserialize JSON content, but if we have a
1610 // special marker (SERIALIZED_MARKER, defined above), we will extract
1611 // some kind of arraybuffer/binary data/typed array out of the string.
1612 function deserialize(value) {
1613 // If we haven't marked this string as being specially serialized (i.e.
1614 // something other than serialized JSON), we can just return it and be
1615 // done with it.
1616 if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
1617 return JSON.parse(value);
1618 }
1619
1620 // The following code deals with deserializing some kind of Blob or
1621 // TypedArray. First we separate out the type of data we're dealing
1622 // with from the data itself.
1623 var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
1624 var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
1625
1626 var blobType;
1627 // Backwards-compatible blob type serialization strategy.
1628 // DBs created with older versions of localForage will simply not have the blob type.
1629 if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
1630 var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
1631 blobType = matcher[1];
1632 serializedString = serializedString.substring(matcher[0].length);
1633 }
1634 var buffer = stringToBuffer(serializedString);
1635
1636 // Return the right type based on the code/type set during
1637 // serialization.
1638 switch (type) {
1639 case TYPE_ARRAYBUFFER:
1640 return buffer;
1641 case TYPE_BLOB:
1642 return createBlob([buffer], { type: blobType });
1643 case TYPE_INT8ARRAY:
1644 return new Int8Array(buffer);
1645 case TYPE_UINT8ARRAY:
1646 return new Uint8Array(buffer);
1647 case TYPE_UINT8CLAMPEDARRAY:
1648 return new Uint8ClampedArray(buffer);
1649 case TYPE_INT16ARRAY:
1650 return new Int16Array(buffer);
1651 case TYPE_UINT16ARRAY:
1652 return new Uint16Array(buffer);
1653 case TYPE_INT32ARRAY:
1654 return new Int32Array(buffer);
1655 case TYPE_UINT32ARRAY:
1656 return new Uint32Array(buffer);
1657 case TYPE_FLOAT32ARRAY:
1658 return new Float32Array(buffer);
1659 case TYPE_FLOAT64ARRAY:
1660 return new Float64Array(buffer);
1661 default:
1662 throw new Error('Unkown type: ' + type);
1663 }
1664 }
1665
1666 var localforageSerializer = {
1667 serialize: serialize,
1668 deserialize: deserialize,
1669 stringToBuffer: stringToBuffer,
1670 bufferToString: bufferToString
1671 };
1672
1673 /*
1674 * Includes code from:
1675 *
1676 * base64-arraybuffer
1677 * https://github.com/niklasvh/base64-arraybuffer
1678 *
1679 * Copyright (c) 2012 Niklas von Hertzen
1680 * Licensed under the MIT license.
1681 */
1682
1683 function createDbTable(t, dbInfo, callback, errorCallback) {
1684 t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
1685 }
1686
1687 // Open the WebSQL database (automatically creates one if one didn't
1688 // previously exist), using any options set in the config.
1689 function _initStorage$1(options) {
1690 var self = this;
1691 var dbInfo = {
1692 db: null
1693 };
1694
1695 if (options) {
1696 for (var i in options) {
1697 dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
1698 }
1699 }
1700
1701 var dbInfoPromise = new Promise$1(function (resolve, reject) {
1702 // Open the database; the openDatabase API will automatically
1703 // create it for us if it doesn't exist.
1704 try {
1705 dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
1706 } catch (e) {
1707 return reject(e);
1708 }
1709
1710 // Create our key/value table if it doesn't exist.
1711 dbInfo.db.transaction(function (t) {
1712 createDbTable(t, dbInfo, function () {
1713 self._dbInfo = dbInfo;
1714 resolve();
1715 }, function (t, error) {
1716 reject(error);
1717 });
1718 }, reject);
1719 });
1720
1721 dbInfo.serializer = localforageSerializer;
1722 return dbInfoPromise;
1723 }
1724
1725 function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
1726 t.executeSql(sqlStatement, args, callback, function (t, error) {
1727 if (error.code === error.SYNTAX_ERR) {
1728 t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
1729 if (!results.rows.length) {
1730 // if the table is missing (was deleted)
1731 // re-create it table and retry
1732 createDbTable(t, dbInfo, function () {
1733 t.executeSql(sqlStatement, args, callback, errorCallback);
1734 }, errorCallback);
1735 } else {
1736 errorCallback(t, error);
1737 }
1738 }, errorCallback);
1739 } else {
1740 errorCallback(t, error);
1741 }
1742 }, errorCallback);
1743 }
1744
1745 function getItem$1(key, callback) {
1746 var self = this;
1747
1748 key = normalizeKey(key);
1749
1750 var promise = new Promise$1(function (resolve, reject) {
1751 self.ready().then(function () {
1752 var dbInfo = self._dbInfo;
1753 dbInfo.db.transaction(function (t) {
1754 tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
1755 var result = results.rows.length ? results.rows.item(0).value : null;
1756
1757 // Check to see if this is serialized content we need to
1758 // unpack.
1759 if (result) {
1760 result = dbInfo.serializer.deserialize(result);
1761 }
1762
1763 resolve(result);
1764 }, function (t, error) {
1765 reject(error);
1766 });
1767 });
1768 })["catch"](reject);
1769 });
1770
1771 executeCallback(promise, callback);
1772 return promise;
1773 }
1774
1775 function iterate$1(iterator, callback) {
1776 var self = this;
1777
1778 var promise = new Promise$1(function (resolve, reject) {
1779 self.ready().then(function () {
1780 var dbInfo = self._dbInfo;
1781
1782 dbInfo.db.transaction(function (t) {
1783 tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
1784 var rows = results.rows;
1785 var length = rows.length;
1786
1787 for (var i = 0; i < length; i++) {
1788 var item = rows.item(i);
1789 var result = item.value;
1790
1791 // Check to see if this is serialized content
1792 // we need to unpack.
1793 if (result) {
1794 result = dbInfo.serializer.deserialize(result);
1795 }
1796
1797 result = iterator(result, item.key, i + 1);
1798
1799 // void(0) prevents problems with redefinition
1800 // of `undefined`.
1801 if (result !== void 0) {
1802 resolve(result);
1803 return;
1804 }
1805 }
1806
1807 resolve();
1808 }, function (t, error) {
1809 reject(error);
1810 });
1811 });
1812 })["catch"](reject);
1813 });
1814
1815 executeCallback(promise, callback);
1816 return promise;
1817 }
1818
1819 function _setItem(key, value, callback, retriesLeft) {
1820 var self = this;
1821
1822 key = normalizeKey(key);
1823
1824 var promise = new Promise$1(function (resolve, reject) {
1825 self.ready().then(function () {
1826 // The localStorage API doesn't return undefined values in an
1827 // "expected" way, so undefined is always cast to null in all
1828 // drivers. See: https://github.com/mozilla/localForage/pull/42
1829 if (value === undefined) {
1830 value = null;
1831 }
1832
1833 // Save the original value to pass to the callback.
1834 var originalValue = value;
1835
1836 var dbInfo = self._dbInfo;
1837 dbInfo.serializer.serialize(value, function (value, error) {
1838 if (error) {
1839 reject(error);
1840 } else {
1841 dbInfo.db.transaction(function (t) {
1842 tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
1843 resolve(originalValue);
1844 }, function (t, error) {
1845 reject(error);
1846 });
1847 }, function (sqlError) {
1848 // The transaction failed; check
1849 // to see if it's a quota error.
1850 if (sqlError.code === sqlError.QUOTA_ERR) {
1851 // We reject the callback outright for now, but
1852 // it's worth trying to re-run the transaction.
1853 // Even if the user accepts the prompt to use
1854 // more storage on Safari, this error will
1855 // be called.
1856 //
1857 // Try to re-run the transaction.
1858 if (retriesLeft > 0) {
1859 resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
1860 return;
1861 }
1862 reject(sqlError);
1863 }
1864 });
1865 }
1866 });
1867 })["catch"](reject);
1868 });
1869
1870 executeCallback(promise, callback);
1871 return promise;
1872 }
1873
1874 function setItem$1(key, value, callback) {
1875 return _setItem.apply(this, [key, value, callback, 1]);
1876 }
1877
1878 function removeItem$1(key, callback) {
1879 var self = this;
1880
1881 key = normalizeKey(key);
1882
1883 var promise = new Promise$1(function (resolve, reject) {
1884 self.ready().then(function () {
1885 var dbInfo = self._dbInfo;
1886 dbInfo.db.transaction(function (t) {
1887 tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
1888 resolve();
1889 }, function (t, error) {
1890 reject(error);
1891 });
1892 });
1893 })["catch"](reject);
1894 });
1895
1896 executeCallback(promise, callback);
1897 return promise;
1898 }
1899
1900 // Deletes every item in the table.
1901 // TODO: Find out if this resets the AUTO_INCREMENT number.
1902 function clear$1(callback) {
1903 var self = this;
1904
1905 var promise = new Promise$1(function (resolve, reject) {
1906 self.ready().then(function () {
1907 var dbInfo = self._dbInfo;
1908 dbInfo.db.transaction(function (t) {
1909 tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
1910 resolve();
1911 }, function (t, error) {
1912 reject(error);
1913 });
1914 });
1915 })["catch"](reject);
1916 });
1917
1918 executeCallback(promise, callback);
1919 return promise;
1920 }
1921
1922 // Does a simple `COUNT(key)` to get the number of items stored in
1923 // localForage.
1924 function length$1(callback) {
1925 var self = this;
1926
1927 var promise = new Promise$1(function (resolve, reject) {
1928 self.ready().then(function () {
1929 var dbInfo = self._dbInfo;
1930 dbInfo.db.transaction(function (t) {
1931 // Ahhh, SQL makes this one soooooo easy.
1932 tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
1933 var result = results.rows.item(0).c;
1934 resolve(result);
1935 }, function (t, error) {
1936 reject(error);
1937 });
1938 });
1939 })["catch"](reject);
1940 });
1941
1942 executeCallback(promise, callback);
1943 return promise;
1944 }
1945
1946 // Return the key located at key index X; essentially gets the key from a
1947 // `WHERE id = ?`. This is the most efficient way I can think to implement
1948 // this rarely-used (in my experience) part of the API, but it can seem
1949 // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
1950 // the ID of each key will change every time it's updated. Perhaps a stored
1951 // procedure for the `setItem()` SQL would solve this problem?
1952 // TODO: Don't change ID on `setItem()`.
1953 function key$1(n, callback) {
1954 var self = this;
1955
1956 var promise = new Promise$1(function (resolve, reject) {
1957 self.ready().then(function () {
1958 var dbInfo = self._dbInfo;
1959 dbInfo.db.transaction(function (t) {
1960 tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
1961 var result = results.rows.length ? results.rows.item(0).key : null;
1962 resolve(result);
1963 }, function (t, error) {
1964 reject(error);
1965 });
1966 });
1967 })["catch"](reject);
1968 });
1969
1970 executeCallback(promise, callback);
1971 return promise;
1972 }
1973
1974 function keys$1(callback) {
1975 var self = this;
1976
1977 var promise = new Promise$1(function (resolve, reject) {
1978 self.ready().then(function () {
1979 var dbInfo = self._dbInfo;
1980 dbInfo.db.transaction(function (t) {
1981 tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
1982 var keys = [];
1983
1984 for (var i = 0; i < results.rows.length; i++) {
1985 keys.push(results.rows.item(i).key);
1986 }
1987
1988 resolve(keys);
1989 }, function (t, error) {
1990 reject(error);
1991 });
1992 });
1993 })["catch"](reject);
1994 });
1995
1996 executeCallback(promise, callback);
1997 return promise;
1998 }
1999
2000 // https://www.w3.org/TR/webdatabase/#databases
2001 // > There is no way to enumerate or delete the databases available for an origin from this API.
2002 function getAllStoreNames(db) {
2003 return new Promise$1(function (resolve, reject) {
2004 db.transaction(function (t) {
2005 t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
2006 var storeNames = [];
2007
2008 for (var i = 0; i < results.rows.length; i++) {
2009 storeNames.push(results.rows.item(i).name);
2010 }
2011
2012 resolve({
2013 db: db,
2014 storeNames: storeNames
2015 });
2016 }, function (t, error) {
2017 reject(error);
2018 });
2019 }, function (sqlError) {
2020 reject(sqlError);
2021 });
2022 });
2023 }
2024
2025 function dropInstance$1(options, callback) {
2026 callback = getCallback.apply(this, arguments);
2027
2028 var currentConfig = this.config();
2029 options = typeof options !== 'function' && options || {};
2030 if (!options.name) {
2031 options.name = options.name || currentConfig.name;
2032 options.storeName = options.storeName || currentConfig.storeName;
2033 }
2034
2035 var self = this;
2036 var promise;
2037 if (!options.name) {
2038 promise = Promise$1.reject('Invalid arguments');
2039 } else {
2040 promise = new Promise$1(function (resolve) {
2041 var db;
2042 if (options.name === currentConfig.name) {
2043 // use the db reference of the current instance
2044 db = self._dbInfo.db;
2045 } else {
2046 db = openDatabase(options.name, '', '', 0);
2047 }
2048
2049 if (!options.storeName) {
2050 // drop all database tables
2051 resolve(getAllStoreNames(db));
2052 } else {
2053 resolve({
2054 db: db,
2055 storeNames: [options.storeName]
2056 });
2057 }
2058 }).then(function (operationInfo) {
2059 return new Promise$1(function (resolve, reject) {
2060 operationInfo.db.transaction(function (t) {
2061 function dropTable(storeName) {
2062 return new Promise$1(function (resolve, reject) {
2063 t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
2064 resolve();
2065 }, function (t, error) {
2066 reject(error);
2067 });
2068 });
2069 }
2070
2071 var operations = [];
2072 for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
2073 operations.push(dropTable(operationInfo.storeNames[i]));
2074 }
2075
2076 Promise$1.all(operations).then(function () {
2077 resolve();
2078 })["catch"](function (e) {
2079 reject(e);
2080 });
2081 }, function (sqlError) {
2082 reject(sqlError);
2083 });
2084 });
2085 });
2086 }
2087
2088 executeCallback(promise, callback);
2089 return promise;
2090 }
2091
2092 var webSQLStorage = {
2093 _driver: 'webSQLStorage',
2094 _initStorage: _initStorage$1,
2095 _support: isWebSQLValid(),
2096 iterate: iterate$1,
2097 getItem: getItem$1,
2098 setItem: setItem$1,
2099 removeItem: removeItem$1,
2100 clear: clear$1,
2101 length: length$1,
2102 key: key$1,
2103 keys: keys$1,
2104 dropInstance: dropInstance$1
2105 };
2106
2107 function isLocalStorageValid() {
2108 try {
2109 return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
2110 // in IE8 typeof localStorage.setItem === 'object'
2111 !!localStorage.setItem;
2112 } catch (e) {
2113 return false;
2114 }
2115 }
2116
2117 function _getKeyPrefix(options, defaultConfig) {
2118 var keyPrefix = options.name + '/';
2119
2120 if (options.storeName !== defaultConfig.storeName) {
2121 keyPrefix += options.storeName + '/';
2122 }
2123 return keyPrefix;
2124 }
2125
2126 // Check if localStorage throws when saving an item
2127 function checkIfLocalStorageThrows() {
2128 var localStorageTestKey = '_localforage_support_test';
2129
2130 try {
2131 localStorage.setItem(localStorageTestKey, true);
2132 localStorage.removeItem(localStorageTestKey);
2133
2134 return false;
2135 } catch (e) {
2136 return true;
2137 }
2138 }
2139
2140 // Check if localStorage is usable and allows to save an item
2141 // This method checks if localStorage is usable in Safari Private Browsing
2142 // mode, or in any other case where the available quota for localStorage
2143 // is 0 and there wasn't any saved items yet.
2144 function _isLocalStorageUsable() {
2145 return !checkIfLocalStorageThrows() || localStorage.length > 0;
2146 }
2147
2148 // Config the localStorage backend, using options set in the config.
2149 function _initStorage$2(options) {
2150 var self = this;
2151 var dbInfo = {};
2152 if (options) {
2153 for (var i in options) {
2154 dbInfo[i] = options[i];
2155 }
2156 }
2157
2158 dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
2159
2160 if (!_isLocalStorageUsable()) {
2161 return Promise$1.reject();
2162 }
2163
2164 self._dbInfo = dbInfo;
2165 dbInfo.serializer = localforageSerializer;
2166
2167 return Promise$1.resolve();
2168 }
2169
2170 // Remove all keys from the datastore, effectively destroying all data in
2171 // the app's key/value store!
2172 function clear$2(callback) {
2173 var self = this;
2174 var promise = self.ready().then(function () {
2175 var keyPrefix = self._dbInfo.keyPrefix;
2176
2177 for (var i = localStorage.length - 1; i >= 0; i--) {
2178 var key = localStorage.key(i);
2179
2180 if (key.indexOf(keyPrefix) === 0) {
2181 localStorage.removeItem(key);
2182 }
2183 }
2184 });
2185
2186 executeCallback(promise, callback);
2187 return promise;
2188 }
2189
2190 // Retrieve an item from the store. Unlike the original async_storage
2191 // library in Gaia, we don't modify return values at all. If a key's value
2192 // is `undefined`, we pass that value to the callback function.
2193 function getItem$2(key, callback) {
2194 var self = this;
2195
2196 key = normalizeKey(key);
2197
2198 var promise = self.ready().then(function () {
2199 var dbInfo = self._dbInfo;
2200 var result = localStorage.getItem(dbInfo.keyPrefix + key);
2201
2202 // If a result was found, parse it from the serialized
2203 // string into a JS object. If result isn't truthy, the key
2204 // is likely undefined and we'll pass it straight to the
2205 // callback.
2206 if (result) {
2207 result = dbInfo.serializer.deserialize(result);
2208 }
2209
2210 return result;
2211 });
2212
2213 executeCallback(promise, callback);
2214 return promise;
2215 }
2216
2217 // Iterate over all items in the store.
2218 function iterate$2(iterator, callback) {
2219 var self = this;
2220
2221 var promise = self.ready().then(function () {
2222 var dbInfo = self._dbInfo;
2223 var keyPrefix = dbInfo.keyPrefix;
2224 var keyPrefixLength = keyPrefix.length;
2225 var length = localStorage.length;
2226
2227 // We use a dedicated iterator instead of the `i` variable below
2228 // so other keys we fetch in localStorage aren't counted in
2229 // the `iterationNumber` argument passed to the `iterate()`
2230 // callback.
2231 //
2232 // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
2233 var iterationNumber = 1;
2234
2235 for (var i = 0; i < length; i++) {
2236 var key = localStorage.key(i);
2237 if (key.indexOf(keyPrefix) !== 0) {
2238 continue;
2239 }
2240 var value = localStorage.getItem(key);
2241
2242 // If a result was found, parse it from the serialized
2243 // string into a JS object. If result isn't truthy, the
2244 // key is likely undefined and we'll pass it straight
2245 // to the iterator.
2246 if (value) {
2247 value = dbInfo.serializer.deserialize(value);
2248 }
2249
2250 value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
2251
2252 if (value !== void 0) {
2253 return value;
2254 }
2255 }
2256 });
2257
2258 executeCallback(promise, callback);
2259 return promise;
2260 }
2261
2262 // Same as localStorage's key() method, except takes a callback.
2263 function key$2(n, callback) {
2264 var self = this;
2265 var promise = self.ready().then(function () {
2266 var dbInfo = self._dbInfo;
2267 var result;
2268 try {
2269 result = localStorage.key(n);
2270 } catch (error) {
2271 result = null;
2272 }
2273
2274 // Remove the prefix from the key, if a key is found.
2275 if (result) {
2276 result = result.substring(dbInfo.keyPrefix.length);
2277 }
2278
2279 return result;
2280 });
2281
2282 executeCallback(promise, callback);
2283 return promise;
2284 }
2285
2286 function keys$2(callback) {
2287 var self = this;
2288 var promise = self.ready().then(function () {
2289 var dbInfo = self._dbInfo;
2290 var length = localStorage.length;
2291 var keys = [];
2292
2293 for (var i = 0; i < length; i++) {
2294 var itemKey = localStorage.key(i);
2295 if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
2296 keys.push(itemKey.substring(dbInfo.keyPrefix.length));
2297 }
2298 }
2299
2300 return keys;
2301 });
2302
2303 executeCallback(promise, callback);
2304 return promise;
2305 }
2306
2307 // Supply the number of keys in the datastore to the callback function.
2308 function length$2(callback) {
2309 var self = this;
2310 var promise = self.keys().then(function (keys) {
2311 return keys.length;
2312 });
2313
2314 executeCallback(promise, callback);
2315 return promise;
2316 }
2317
2318 // Remove an item from the store, nice and simple.
2319 function removeItem$2(key, callback) {
2320 var self = this;
2321
2322 key = normalizeKey(key);
2323
2324 var promise = self.ready().then(function () {
2325 var dbInfo = self._dbInfo;
2326 localStorage.removeItem(dbInfo.keyPrefix + key);
2327 });
2328
2329 executeCallback(promise, callback);
2330 return promise;
2331 }
2332
2333 // Set a key's value and run an optional callback once the value is set.
2334 // Unlike Gaia's implementation, the callback function is passed the value,
2335 // in case you want to operate on that value only after you're sure it
2336 // saved, or something like that.
2337 function setItem$2(key, value, callback) {
2338 var self = this;
2339
2340 key = normalizeKey(key);
2341
2342 var promise = self.ready().then(function () {
2343 // Convert undefined values to null.
2344 // https://github.com/mozilla/localForage/pull/42
2345 if (value === undefined) {
2346 value = null;
2347 }
2348
2349 // Save the original value to pass to the callback.
2350 var originalValue = value;
2351
2352 return new Promise$1(function (resolve, reject) {
2353 var dbInfo = self._dbInfo;
2354 dbInfo.serializer.serialize(value, function (value, error) {
2355 if (error) {
2356 reject(error);
2357 } else {
2358 try {
2359 localStorage.setItem(dbInfo.keyPrefix + key, value);
2360 resolve(originalValue);
2361 } catch (e) {
2362 // localStorage capacity exceeded.
2363 // TODO: Make this a specific error/event.
2364 if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
2365 reject(e);
2366 }
2367 reject(e);
2368 }
2369 }
2370 });
2371 });
2372 });
2373
2374 executeCallback(promise, callback);
2375 return promise;
2376 }
2377
2378 function dropInstance$2(options, callback) {
2379 callback = getCallback.apply(this, arguments);
2380
2381 options = typeof options !== 'function' && options || {};
2382 if (!options.name) {
2383 var currentConfig = this.config();
2384 options.name = options.name || currentConfig.name;
2385 options.storeName = options.storeName || currentConfig.storeName;
2386 }
2387
2388 var self = this;
2389 var promise;
2390 if (!options.name) {
2391 promise = Promise$1.reject('Invalid arguments');
2392 } else {
2393 promise = new Promise$1(function (resolve) {
2394 if (!options.storeName) {
2395 resolve(options.name + '/');
2396 } else {
2397 resolve(_getKeyPrefix(options, self._defaultConfig));
2398 }
2399 }).then(function (keyPrefix) {
2400 for (var i = localStorage.length - 1; i >= 0; i--) {
2401 var key = localStorage.key(i);
2402
2403 if (key.indexOf(keyPrefix) === 0) {
2404 localStorage.removeItem(key);
2405 }
2406 }
2407 });
2408 }
2409
2410 executeCallback(promise, callback);
2411 return promise;
2412 }
2413
2414 var localStorageWrapper = {
2415 _driver: 'localStorageWrapper',
2416 _initStorage: _initStorage$2,
2417 _support: isLocalStorageValid(),
2418 iterate: iterate$2,
2419 getItem: getItem$2,
2420 setItem: setItem$2,
2421 removeItem: removeItem$2,
2422 clear: clear$2,
2423 length: length$2,
2424 key: key$2,
2425 keys: keys$2,
2426 dropInstance: dropInstance$2
2427 };
2428
2429 var sameValue = function sameValue(x, y) {
2430 return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
2431 };
2432
2433 var includes = function includes(array, searchElement) {
2434 var len = array.length;
2435 var i = 0;
2436 while (i < len) {
2437 if (sameValue(array[i], searchElement)) {
2438 return true;
2439 }
2440 i++;
2441 }
2442
2443 return false;
2444 };
2445
2446 var isArray = Array.isArray || function (arg) {
2447 return Object.prototype.toString.call(arg) === '[object Array]';
2448 };
2449
2450 // Drivers are stored here when `defineDriver()` is called.
2451 // They are shared across all instances of localForage.
2452 var DefinedDrivers = {};
2453
2454 var DriverSupport = {};
2455
2456 var DefaultDrivers = {
2457 INDEXEDDB: asyncStorage,
2458 WEBSQL: webSQLStorage,
2459 LOCALSTORAGE: localStorageWrapper
2460 };
2461
2462 var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
2463
2464 var OptionalDriverMethods = ['dropInstance'];
2465
2466 var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
2467
2468 var DefaultConfig = {
2469 description: '',
2470 driver: DefaultDriverOrder.slice(),
2471 name: 'localforage',
2472 // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
2473 // we can use without a prompt.
2474 size: 4980736,
2475 storeName: 'keyvaluepairs',
2476 version: 1.0
2477 };
2478
2479 function callWhenReady(localForageInstance, libraryMethod) {
2480 localForageInstance[libraryMethod] = function () {
2481 var _args = arguments;
2482 return localForageInstance.ready().then(function () {
2483 return localForageInstance[libraryMethod].apply(localForageInstance, _args);
2484 });
2485 };
2486 }
2487
2488 function extend() {
2489 for (var i = 1; i < arguments.length; i++) {
2490 var arg = arguments[i];
2491
2492 if (arg) {
2493 for (var _key in arg) {
2494 if (arg.hasOwnProperty(_key)) {
2495 if (isArray(arg[_key])) {
2496 arguments[0][_key] = arg[_key].slice();
2497 } else {
2498 arguments[0][_key] = arg[_key];
2499 }
2500 }
2501 }
2502 }
2503 }
2504
2505 return arguments[0];
2506 }
2507
2508 var LocalForage = function () {
2509 function LocalForage(options) {
2510 _classCallCheck(this, LocalForage);
2511
2512 for (var driverTypeKey in DefaultDrivers) {
2513 if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
2514 var driver = DefaultDrivers[driverTypeKey];
2515 var driverName = driver._driver;
2516 this[driverTypeKey] = driverName;
2517
2518 if (!DefinedDrivers[driverName]) {
2519 // we don't need to wait for the promise,
2520 // since the default drivers can be defined
2521 // in a blocking manner
2522 this.defineDriver(driver);
2523 }
2524 }
2525 }
2526
2527 this._defaultConfig = extend({}, DefaultConfig);
2528 this._config = extend({}, this._defaultConfig, options);
2529 this._driverSet = null;
2530 this._initDriver = null;
2531 this._ready = false;
2532 this._dbInfo = null;
2533
2534 this._wrapLibraryMethodsWithReady();
2535 this.setDriver(this._config.driver)["catch"](function () {});
2536 }
2537
2538 // Set any config values for localForage; can be called anytime before
2539 // the first API call (e.g. `getItem`, `setItem`).
2540 // We loop through options so we don't overwrite existing config
2541 // values.
2542
2543
2544 LocalForage.prototype.config = function config(options) {
2545 // If the options argument is an object, we use it to set values.
2546 // Otherwise, we return either a specified config value or all
2547 // config values.
2548 if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
2549 // If localforage is ready and fully initialized, we can't set
2550 // any new configuration values. Instead, we return an error.
2551 if (this._ready) {
2552 return new Error("Can't call config() after localforage " + 'has been used.');
2553 }
2554
2555 for (var i in options) {
2556 if (i === 'storeName') {
2557 options[i] = options[i].replace(/\W/g, '_');
2558 }
2559
2560 if (i === 'version' && typeof options[i] !== 'number') {
2561 return new Error('Database version must be a number.');
2562 }
2563
2564 this._config[i] = options[i];
2565 }
2566
2567 // after all config options are set and
2568 // the driver option is used, try setting it
2569 if ('driver' in options && options.driver) {
2570 return this.setDriver(this._config.driver);
2571 }
2572
2573 return true;
2574 } else if (typeof options === 'string') {
2575 return this._config[options];
2576 } else {
2577 return this._config;
2578 }
2579 };
2580
2581 // Used to define a custom driver, shared across all instances of
2582 // localForage.
2583
2584
2585 LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
2586 var promise = new Promise$1(function (resolve, reject) {
2587 try {
2588 var driverName = driverObject._driver;
2589 var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
2590
2591 // A driver name should be defined and not overlap with the
2592 // library-defined, default drivers.
2593 if (!driverObject._driver) {
2594 reject(complianceError);
2595 return;
2596 }
2597
2598 var driverMethods = LibraryMethods.concat('_initStorage');
2599 for (var i = 0, len = driverMethods.length; i < len; i++) {
2600 var driverMethodName = driverMethods[i];
2601
2602 // when the property is there,
2603 // it should be a method even when optional
2604 var isRequired = !includes(OptionalDriverMethods, driverMethodName);
2605 if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
2606 reject(complianceError);
2607 return;
2608 }
2609 }
2610
2611 var configureMissingMethods = function configureMissingMethods() {
2612 var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
2613 return function () {
2614 var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
2615 var promise = Promise$1.reject(error);
2616 executeCallback(promise, arguments[arguments.length - 1]);
2617 return promise;
2618 };
2619 };
2620
2621 for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
2622 var optionalDriverMethod = OptionalDriverMethods[_i];
2623 if (!driverObject[optionalDriverMethod]) {
2624 driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
2625 }
2626 }
2627 };
2628
2629 configureMissingMethods();
2630
2631 var setDriverSupport = function setDriverSupport(support) {
2632 if (DefinedDrivers[driverName]) {
2633 console.info('Redefining LocalForage driver: ' + driverName);
2634 }
2635 DefinedDrivers[driverName] = driverObject;
2636 DriverSupport[driverName] = support;
2637 // don't use a then, so that we can define
2638 // drivers that have simple _support methods
2639 // in a blocking manner
2640 resolve();
2641 };
2642
2643 if ('_support' in driverObject) {
2644 if (driverObject._support && typeof driverObject._support === 'function') {
2645 driverObject._support().then(setDriverSupport, reject);
2646 } else {
2647 setDriverSupport(!!driverObject._support);
2648 }
2649 } else {
2650 setDriverSupport(true);
2651 }
2652 } catch (e) {
2653 reject(e);
2654 }
2655 });
2656
2657 executeTwoCallbacks(promise, callback, errorCallback);
2658 return promise;
2659 };
2660
2661 LocalForage.prototype.driver = function driver() {
2662 return this._driver || null;
2663 };
2664
2665 LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
2666 var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
2667
2668 executeTwoCallbacks(getDriverPromise, callback, errorCallback);
2669 return getDriverPromise;
2670 };
2671
2672 LocalForage.prototype.getSerializer = function getSerializer(callback) {
2673 var serializerPromise = Promise$1.resolve(localforageSerializer);
2674 executeTwoCallbacks(serializerPromise, callback);
2675 return serializerPromise;
2676 };
2677
2678 LocalForage.prototype.ready = function ready(callback) {
2679 var self = this;
2680
2681 var promise = self._driverSet.then(function () {
2682 if (self._ready === null) {
2683 self._ready = self._initDriver();
2684 }
2685
2686 return self._ready;
2687 });
2688
2689 executeTwoCallbacks(promise, callback, callback);
2690 return promise;
2691 };
2692
2693 LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
2694 var self = this;
2695
2696 if (!isArray(drivers)) {
2697 drivers = [drivers];
2698 }
2699
2700 var supportedDrivers = this._getSupportedDrivers(drivers);
2701
2702 function setDriverToConfig() {
2703 self._config.driver = self.driver();
2704 }
2705
2706 function extendSelfWithDriver(driver) {
2707 self._extend(driver);
2708 setDriverToConfig();
2709
2710 self._ready = self._initStorage(self._config);
2711 return self._ready;
2712 }
2713
2714 function initDriver(supportedDrivers) {
2715 return function () {
2716 var currentDriverIndex = 0;
2717
2718 function driverPromiseLoop() {
2719 while (currentDriverIndex < supportedDrivers.length) {
2720 var driverName = supportedDrivers[currentDriverIndex];
2721 currentDriverIndex++;
2722
2723 self._dbInfo = null;
2724 self._ready = null;
2725
2726 return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
2727 }
2728
2729 setDriverToConfig();
2730 var error = new Error('No available storage method found.');
2731 self._driverSet = Promise$1.reject(error);
2732 return self._driverSet;
2733 }
2734
2735 return driverPromiseLoop();
2736 };
2737 }
2738
2739 // There might be a driver initialization in progress
2740 // so wait for it to finish in order to avoid a possible
2741 // race condition to set _dbInfo
2742 var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
2743 return Promise$1.resolve();
2744 }) : Promise$1.resolve();
2745
2746 this._driverSet = oldDriverSetDone.then(function () {
2747 var driverName = supportedDrivers[0];
2748 self._dbInfo = null;
2749 self._ready = null;
2750
2751 return self.getDriver(driverName).then(function (driver) {
2752 self._driver = driver._driver;
2753 setDriverToConfig();
2754 self._wrapLibraryMethodsWithReady();
2755 self._initDriver = initDriver(supportedDrivers);
2756 });
2757 })["catch"](function () {
2758 setDriverToConfig();
2759 var error = new Error('No available storage method found.');
2760 self._driverSet = Promise$1.reject(error);
2761 return self._driverSet;
2762 });
2763
2764 executeTwoCallbacks(this._driverSet, callback, errorCallback);
2765 return this._driverSet;
2766 };
2767
2768 LocalForage.prototype.supports = function supports(driverName) {
2769 return !!DriverSupport[driverName];
2770 };
2771
2772 LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
2773 extend(this, libraryMethodsAndProperties);
2774 };
2775
2776 LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
2777 var supportedDrivers = [];
2778 for (var i = 0, len = drivers.length; i < len; i++) {
2779 var driverName = drivers[i];
2780 if (this.supports(driverName)) {
2781 supportedDrivers.push(driverName);
2782 }
2783 }
2784 return supportedDrivers;
2785 };
2786
2787 LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
2788 // Add a stub for each driver API method that delays the call to the
2789 // corresponding driver method until localForage is ready. These stubs
2790 // will be replaced by the driver methods as soon as the driver is
2791 // loaded, so there is no performance impact.
2792 for (var i = 0, len = LibraryMethods.length; i < len; i++) {
2793 callWhenReady(this, LibraryMethods[i]);
2794 }
2795 };
2796
2797 LocalForage.prototype.createInstance = function createInstance(options) {
2798 return new LocalForage(options);
2799 };
2800
2801 return LocalForage;
2802 }();
2803
2804 // The actual localForage object that we expose as a module or via a
2805 // global. It's extended by pulling in one of our other libraries.
2806
2807
2808 var localforage_js = new LocalForage();
2809
2810 module.exports = localforage_js;
2811
2812 },{"3":3}]},{},[4])(4)
2813 });
2814 });
2815
2816 /** @hidden */
2817 const Drivers = {
2818 SecureStorage: 'ionicSecureStorage',
2819 IndexedDB: localforage.INDEXEDDB,
2820 LocalStorage: localforage.LOCALSTORAGE
2821 };
2822 const defaultConfig = {
2823 name: '_ionicstorage',
2824 storeName: '_ionickv',
2825 dbKey: '_ionickey',
2826 driverOrder: [
2827 Drivers.SecureStorage,
2828 Drivers.IndexedDB,
2829 Drivers.LocalStorage
2830 ]
2831 };
2832 class Storage {
2833 /**
2834 * Create a new Storage instance using the order of drivers and any additional config
2835 * options to pass to LocalForage.
2836 *
2837 * Possible default driverOrder options are: ['indexeddb', 'localstorage'] and the
2838 * default is that exact ordering.
2839 *
2840 * When using Ionic Secure Storage (enterprise only), use ['ionicSecureStorage', 'indexeddb', 'localstorage'] to ensure
2841 * Secure Storage is used when available, or fall back to IndexedDB or LocalStorage on the web.
2842 */
2843 constructor(config = defaultConfig) {
2844 this._db = null;
2845 this._secureStorageDriver = null;
2846 const actualConfig = Object.assign({}, defaultConfig, config || {});
2847 this._config = actualConfig;
2848 }
2849 async create() {
2850 const db = localforage.createInstance(this._config);
2851 this._db = db;
2852 await db.setDriver(this._config.driverOrder || []);
2853 return this;
2854 }
2855 /**
2856 * Define a new Driver. Must be called before
2857 * initializing the database. Example:
2858 *
2859 * await storage.defineDriver(myDriver);
2860 * await storage.create();
2861 */
2862 async defineDriver(driver) {
2863 if (driver._driver === Drivers.SecureStorage) {
2864 this._secureStorageDriver = driver;
2865 }
2866 return localforage.defineDriver(driver);
2867 }
2868 /**
2869 * Get the name of the driver being used.
2870 * @returns Name of the driver
2871 */
2872 get driver() {
2873 var _a;
2874 return ((_a = this._db) === null || _a === void 0 ? void 0 : _a.driver()) || null;
2875 }
2876 assertDb() {
2877 if (!this._db) {
2878 throw new Error('Database not created. Must call create() first');
2879 }
2880 return this._db;
2881 }
2882 /**
2883 * Get the value associated with the given key.
2884 * @param key the key to identify this value
2885 * @returns Returns a promise with the value of the given key
2886 */
2887 get(key) {
2888 const db = this.assertDb();
2889 return db.getItem(key);
2890 }
2891 /**
2892 * Set the value for the given key.
2893 * @param key the key to identify this value
2894 * @param value the value for this key
2895 * @returns Returns a promise that resolves when the key and value are set
2896 */
2897 set(key, value) {
2898 const db = this.assertDb();
2899 return db.setItem(key, value);
2900 }
2901 /**
2902 * Remove any value associated with this key.
2903 * @param key the key to identify this value
2904 * @returns Returns a promise that resolves when the value is removed
2905 */
2906 remove(key) {
2907 const db = this.assertDb();
2908 return db.removeItem(key);
2909 }
2910 /**
2911 * Clear the entire key value store. WARNING: HOT!
2912 * @returns Returns a promise that resolves when the store is cleared
2913 */
2914 clear() {
2915 const db = this.assertDb();
2916 return db.clear();
2917 }
2918 /**
2919 * @returns Returns a promise that resolves with the number of keys stored.
2920 */
2921 length() {
2922 const db = this.assertDb();
2923 return db.length();
2924 }
2925 /**
2926 * @returns Returns a promise that resolves with the keys in the store.
2927 */
2928 keys() {
2929 const db = this.assertDb();
2930 return db.keys();
2931 }
2932 /**
2933 * Iterate through each key,value pair.
2934 * @param iteratorCallback a callback of the form (value, key, iterationNumber)
2935 * @returns Returns a promise that resolves when the iteration has finished.
2936 */
2937 forEach(iteratorCallback) {
2938 const db = this.assertDb();
2939 return db.iterate(iteratorCallback);
2940 }
2941 setEncryptionKey(key) {
2942 var _a;
2943 if (!this._secureStorageDriver) {
2944 throw new Error('@ionic-enterprise/secure-storage not installed. Encryption support not available');
2945 }
2946 else {
2947 (_a = this._secureStorageDriver) === null || _a === void 0 ? void 0 : _a.setEncryptionKey(key);
2948 }
2949 }
2950 }
2951
2952 exports.Drivers = Drivers;
2953 exports.Storage = Storage;
2954
2955 Object.defineProperty(exports, '__esModule', { value: true });
2956
2957 return exports;
2958
2959}({}));
2960//# sourceMappingURL=ionic-storage.js.map