spire.officejs-core-externs-test 1.0.0

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