bruce-models 2.9.5 → 2.9.7

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