bruce-models 2.0.5 → 2.0.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.
Files changed (82) hide show
  1. package/dist/bruce-models.es5.js +3294 -356
  2. package/dist/bruce-models.es5.js.map +1 -1
  3. package/dist/bruce-models.umd.js +3293 -354
  4. package/dist/bruce-models.umd.js.map +1 -1
  5. package/dist/lib/account/account.js +9 -9
  6. package/dist/lib/account/account.js.map +1 -1
  7. package/dist/lib/ann-document/ann-document.js +4 -4
  8. package/dist/lib/ann-document/ann-document.js.map +1 -1
  9. package/dist/lib/api/abstract-api.js +25 -21
  10. package/dist/lib/api/abstract-api.js.map +1 -1
  11. package/dist/lib/api/api.js +1 -1
  12. package/dist/lib/api/api.js.map +1 -1
  13. package/dist/lib/api/bruce-api.js +2 -1
  14. package/dist/lib/api/bruce-api.js.map +1 -1
  15. package/dist/lib/api/cam-api.js +2 -1
  16. package/dist/lib/api/cam-api.js.map +1 -1
  17. package/dist/lib/api/global-api.js +2 -1
  18. package/dist/lib/api/global-api.js.map +1 -1
  19. package/dist/lib/api/idm-api.js +2 -1
  20. package/dist/lib/api/idm-api.js.map +1 -1
  21. package/dist/lib/bruce-models.js +1 -0
  22. package/dist/lib/bruce-models.js.map +1 -1
  23. package/dist/lib/client-file/client-file.js +2 -2
  24. package/dist/lib/client-file/client-file.js.map +1 -1
  25. package/dist/lib/common/cache.js +222 -130
  26. package/dist/lib/common/cache.js.map +1 -1
  27. package/dist/lib/common/lru-cache.js +26 -0
  28. package/dist/lib/common/lru-cache.js.map +1 -0
  29. package/dist/lib/custom-form/custom-form.js +6 -6
  30. package/dist/lib/custom-form/custom-form.js.map +1 -1
  31. package/dist/lib/entity/entity-attachment-type.js +2 -2
  32. package/dist/lib/entity/entity-attachment-type.js.map +1 -1
  33. package/dist/lib/entity/entity-attachment.js +3 -3
  34. package/dist/lib/entity/entity-attachment.js.map +1 -1
  35. package/dist/lib/entity/entity-comment.js +4 -4
  36. package/dist/lib/entity/entity-comment.js.map +1 -1
  37. package/dist/lib/entity/entity-coords.js +2 -2
  38. package/dist/lib/entity/entity-coords.js.map +1 -1
  39. package/dist/lib/entity/entity-link.js +4 -4
  40. package/dist/lib/entity/entity-link.js.map +1 -1
  41. package/dist/lib/entity/entity-lod-category.js +4 -4
  42. package/dist/lib/entity/entity-lod-category.js.map +1 -1
  43. package/dist/lib/entity/entity-lod.js +6 -6
  44. package/dist/lib/entity/entity-lod.js.map +1 -1
  45. package/dist/lib/entity/entity-relation-type.js +4 -4
  46. package/dist/lib/entity/entity-relation-type.js.map +1 -1
  47. package/dist/lib/entity/entity-relation.js +15 -15
  48. package/dist/lib/entity/entity-relation.js.map +1 -1
  49. package/dist/lib/entity/entity-source.js +2 -2
  50. package/dist/lib/entity/entity-source.js.map +1 -1
  51. package/dist/lib/entity/entity-tag.js +6 -6
  52. package/dist/lib/entity/entity-tag.js.map +1 -1
  53. package/dist/lib/entity/entity-type.js +6 -5
  54. package/dist/lib/entity/entity-type.js.map +1 -1
  55. package/dist/lib/entity/entity.js +5 -5
  56. package/dist/lib/entity/entity.js.map +1 -1
  57. package/dist/lib/entity/getters/entity-filter-getter.js +1 -4
  58. package/dist/lib/entity/getters/entity-filter-getter.js.map +1 -1
  59. package/dist/lib/import/imported-file.js +4 -4
  60. package/dist/lib/import/imported-file.js.map +1 -1
  61. package/dist/lib/plugin/plugin.js +4 -4
  62. package/dist/lib/plugin/plugin.js.map +1 -1
  63. package/dist/lib/program-key/program-key.js +4 -4
  64. package/dist/lib/program-key/program-key.js.map +1 -1
  65. package/dist/lib/project/project-view-bookmark.js +6 -6
  66. package/dist/lib/project/project-view-bookmark.js.map +1 -1
  67. package/dist/lib/project/project-view.js +4 -4
  68. package/dist/lib/project/project-view.js.map +1 -1
  69. package/dist/lib/style/style.js +46 -42
  70. package/dist/lib/style/style.js.map +1 -1
  71. package/dist/lib/tileset/tileset.js +12 -12
  72. package/dist/lib/tileset/tileset.js.map +1 -1
  73. package/dist/lib/user/session.js +2 -2
  74. package/dist/lib/user/session.js.map +1 -1
  75. package/dist/lib/user/user.js +20 -20
  76. package/dist/lib/user/user.js.map +1 -1
  77. package/dist/types/api/abstract-api.d.ts +3 -2
  78. package/dist/types/api/api.d.ts +1 -1
  79. package/dist/types/bruce-models.d.ts +1 -0
  80. package/dist/types/common/cache.d.ts +9 -15
  81. package/dist/types/common/lru-cache.d.ts +7 -0
  82. package/package.json +2 -1
@@ -69,7 +69,7 @@
69
69
  ECacheKey["ImportedFile"] = "importedfile";
70
70
  ECacheKey["Plugin"] = "plugin";
71
71
  })(ECacheKey = Api.ECacheKey || (Api.ECacheKey = {}));
72
- Api.DEFAULT_CACHE_DURATION = 60 * 5; // 5 minutes.
72
+ Api.DEFAULT_CACHE_DURATION = 60; // 1 minute.
73
73
  Api.TEMPLATE_ACCOUNT_ID = "template";
74
74
  Api.ACCESS_TOKEN_HEADER = "X-Access-Token";
75
75
  /**
@@ -138,7 +138,7 @@
138
138
  throw ("Doc ID is required.");
139
139
  }
140
140
  const key = GetCacheKey(docId);
141
- const cacheData = api.GetCacheItem(key, reqParams);
141
+ const cacheData = yield api.GetCacheItem(key, reqParams);
142
142
  if (cacheData) {
143
143
  return cacheData;
144
144
  }
@@ -153,7 +153,7 @@
153
153
  rej(e);
154
154
  }
155
155
  }));
156
- api.SetCacheItem({
156
+ yield api.SetCacheItem({
157
157
  key,
158
158
  value: prom,
159
159
  req: reqParams
@@ -168,7 +168,7 @@
168
168
  if (!type) {
169
169
  type = "";
170
170
  }
171
- const cacheData = api.GetCacheItem(GetListCacheKey(type), reqParams);
171
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(type), reqParams);
172
172
  if (cacheData) {
173
173
  return cacheData;
174
174
  }
@@ -184,7 +184,7 @@
184
184
  rej(e);
185
185
  }
186
186
  }));
187
- api.SetCacheItem({
187
+ yield api.SetCacheItem({
188
188
  key: GetListCacheKey(type),
189
189
  value: req,
190
190
  req: reqParams
@@ -218,7 +218,7 @@
218
218
  if (!id) {
219
219
  throw ("Id is required.");
220
220
  }
221
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
221
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
222
222
  if (cacheData) {
223
223
  return cacheData;
224
224
  }
@@ -233,7 +233,7 @@
233
233
  rej(err);
234
234
  }
235
235
  }));
236
- api.SetCacheItem({
236
+ yield api.SetCacheItem({
237
237
  key: GetCacheKey(id),
238
238
  value: prom,
239
239
  req: reqParams
@@ -249,7 +249,7 @@
249
249
  throw ("Id is required.");
250
250
  }
251
251
  yield api.DELETE(`customForm/${id}`, exports.Api.PrepReqParams(reqParams));
252
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.CustomForm);
252
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.CustomForm);
253
253
  });
254
254
  }
255
255
  CustomForm.Delete = Delete;
@@ -257,7 +257,7 @@
257
257
  return __awaiter(this, void 0, void 0, function* () {
258
258
  const { api, entityTypeId: typeId, req: reqParams } = params;
259
259
  const url = typeId ? `entityType/${typeId}/customForms` : "customForms";
260
- const cacheData = api.GetCacheItem(GetListCacheKey(typeId), reqParams);
260
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(typeId), reqParams);
261
261
  if (cacheData) {
262
262
  return cacheData;
263
263
  }
@@ -267,7 +267,7 @@
267
267
  forms: data.Items
268
268
  };
269
269
  });
270
- api.SetCacheItem({
270
+ yield api.SetCacheItem({
271
271
  key: GetListCacheKey(typeId),
272
272
  value: prom,
273
273
  req: reqParams
@@ -283,7 +283,7 @@
283
283
  data.ID = 0;
284
284
  }
285
285
  const res = yield api.POST(`customForm/${data.ID}`, data, exports.Api.PrepReqParams(reqParams));
286
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.CustomForm);
286
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.CustomForm);
287
287
  return {
288
288
  form: res
289
289
  };
@@ -315,43 +315,3020 @@
315
315
  })(EFlowDirection = CustomFormContent.EFlowDirection || (CustomFormContent.EFlowDirection = {}));
316
316
  })(exports.CustomFormContent || (exports.CustomFormContent = {}));
317
317
 
318
- class CacheItem {
318
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
319
+
320
+ function commonjsRequire () {
321
+ throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
322
+ }
323
+
324
+ function createCommonjsModule(fn, module) {
325
+ return module = { exports: {} }, fn(module, module.exports), module.exports;
326
+ }
327
+
328
+ var localforage = createCommonjsModule(function (module, exports) {
329
+ /*!
330
+ localForage -- Offline Storage, Improved
331
+ Version 1.10.0
332
+ https://localforage.github.io/localForage
333
+ (c) 2013-2017 Mozilla, Apache License 2.0
334
+ */
335
+ (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){
336
+ (function (global){
337
+ var Mutation = global.MutationObserver || global.WebKitMutationObserver;
338
+
339
+ var scheduleDrain;
340
+
341
+ {
342
+ if (Mutation) {
343
+ var called = 0;
344
+ var observer = new Mutation(nextTick);
345
+ var element = global.document.createTextNode('');
346
+ observer.observe(element, {
347
+ characterData: true
348
+ });
349
+ scheduleDrain = function () {
350
+ element.data = (called = ++called % 2);
351
+ };
352
+ } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
353
+ var channel = new global.MessageChannel();
354
+ channel.port1.onmessage = nextTick;
355
+ scheduleDrain = function () {
356
+ channel.port2.postMessage(0);
357
+ };
358
+ } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
359
+ scheduleDrain = function () {
360
+
361
+ // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
362
+ // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
363
+ var scriptEl = global.document.createElement('script');
364
+ scriptEl.onreadystatechange = function () {
365
+ nextTick();
366
+
367
+ scriptEl.onreadystatechange = null;
368
+ scriptEl.parentNode.removeChild(scriptEl);
369
+ scriptEl = null;
370
+ };
371
+ global.document.documentElement.appendChild(scriptEl);
372
+ };
373
+ } else {
374
+ scheduleDrain = function () {
375
+ setTimeout(nextTick, 0);
376
+ };
377
+ }
378
+ }
379
+
380
+ var draining;
381
+ var queue = [];
382
+ //named nextTick for less confusing stack traces
383
+ function nextTick() {
384
+ draining = true;
385
+ var i, oldQueue;
386
+ var len = queue.length;
387
+ while (len) {
388
+ oldQueue = queue;
389
+ queue = [];
390
+ i = -1;
391
+ while (++i < len) {
392
+ oldQueue[i]();
393
+ }
394
+ len = queue.length;
395
+ }
396
+ draining = false;
397
+ }
398
+
399
+ module.exports = immediate;
400
+ function immediate(task) {
401
+ if (queue.push(task) === 1 && !draining) {
402
+ scheduleDrain();
403
+ }
404
+ }
405
+
406
+ }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
407
+ },{}],2:[function(_dereq_,module,exports){
408
+ var immediate = _dereq_(1);
409
+
410
+ /* istanbul ignore next */
411
+ function INTERNAL() {}
412
+
413
+ var handlers = {};
414
+
415
+ var REJECTED = ['REJECTED'];
416
+ var FULFILLED = ['FULFILLED'];
417
+ var PENDING = ['PENDING'];
418
+
419
+ module.exports = Promise;
420
+
421
+ function Promise(resolver) {
422
+ if (typeof resolver !== 'function') {
423
+ throw new TypeError('resolver must be a function');
424
+ }
425
+ this.state = PENDING;
426
+ this.queue = [];
427
+ this.outcome = void 0;
428
+ if (resolver !== INTERNAL) {
429
+ safelyResolveThenable(this, resolver);
430
+ }
431
+ }
432
+
433
+ Promise.prototype["catch"] = function (onRejected) {
434
+ return this.then(null, onRejected);
435
+ };
436
+ Promise.prototype.then = function (onFulfilled, onRejected) {
437
+ if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
438
+ typeof onRejected !== 'function' && this.state === REJECTED) {
439
+ return this;
440
+ }
441
+ var promise = new this.constructor(INTERNAL);
442
+ if (this.state !== PENDING) {
443
+ var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
444
+ unwrap(promise, resolver, this.outcome);
445
+ } else {
446
+ this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
447
+ }
448
+
449
+ return promise;
450
+ };
451
+ function QueueItem(promise, onFulfilled, onRejected) {
452
+ this.promise = promise;
453
+ if (typeof onFulfilled === 'function') {
454
+ this.onFulfilled = onFulfilled;
455
+ this.callFulfilled = this.otherCallFulfilled;
456
+ }
457
+ if (typeof onRejected === 'function') {
458
+ this.onRejected = onRejected;
459
+ this.callRejected = this.otherCallRejected;
460
+ }
461
+ }
462
+ QueueItem.prototype.callFulfilled = function (value) {
463
+ handlers.resolve(this.promise, value);
464
+ };
465
+ QueueItem.prototype.otherCallFulfilled = function (value) {
466
+ unwrap(this.promise, this.onFulfilled, value);
467
+ };
468
+ QueueItem.prototype.callRejected = function (value) {
469
+ handlers.reject(this.promise, value);
470
+ };
471
+ QueueItem.prototype.otherCallRejected = function (value) {
472
+ unwrap(this.promise, this.onRejected, value);
473
+ };
474
+
475
+ function unwrap(promise, func, value) {
476
+ immediate(function () {
477
+ var returnValue;
478
+ try {
479
+ returnValue = func(value);
480
+ } catch (e) {
481
+ return handlers.reject(promise, e);
482
+ }
483
+ if (returnValue === promise) {
484
+ handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
485
+ } else {
486
+ handlers.resolve(promise, returnValue);
487
+ }
488
+ });
489
+ }
490
+
491
+ handlers.resolve = function (self, value) {
492
+ var result = tryCatch(getThen, value);
493
+ if (result.status === 'error') {
494
+ return handlers.reject(self, result.value);
495
+ }
496
+ var thenable = result.value;
497
+
498
+ if (thenable) {
499
+ safelyResolveThenable(self, thenable);
500
+ } else {
501
+ self.state = FULFILLED;
502
+ self.outcome = value;
503
+ var i = -1;
504
+ var len = self.queue.length;
505
+ while (++i < len) {
506
+ self.queue[i].callFulfilled(value);
507
+ }
508
+ }
509
+ return self;
510
+ };
511
+ handlers.reject = function (self, error) {
512
+ self.state = REJECTED;
513
+ self.outcome = error;
514
+ var i = -1;
515
+ var len = self.queue.length;
516
+ while (++i < len) {
517
+ self.queue[i].callRejected(error);
518
+ }
519
+ return self;
520
+ };
521
+
522
+ function getThen(obj) {
523
+ // Make sure we only access the accessor once as required by the spec
524
+ var then = obj && obj.then;
525
+ if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {
526
+ return function appyThen() {
527
+ then.apply(obj, arguments);
528
+ };
529
+ }
530
+ }
531
+
532
+ function safelyResolveThenable(self, thenable) {
533
+ // Either fulfill, reject or reject with error
534
+ var called = false;
535
+ function onError(value) {
536
+ if (called) {
537
+ return;
538
+ }
539
+ called = true;
540
+ handlers.reject(self, value);
541
+ }
542
+
543
+ function onSuccess(value) {
544
+ if (called) {
545
+ return;
546
+ }
547
+ called = true;
548
+ handlers.resolve(self, value);
549
+ }
550
+
551
+ function tryToUnwrap() {
552
+ thenable(onSuccess, onError);
553
+ }
554
+
555
+ var result = tryCatch(tryToUnwrap);
556
+ if (result.status === 'error') {
557
+ onError(result.value);
558
+ }
559
+ }
560
+
561
+ function tryCatch(func, value) {
562
+ var out = {};
563
+ try {
564
+ out.value = func(value);
565
+ out.status = 'success';
566
+ } catch (e) {
567
+ out.status = 'error';
568
+ out.value = e;
569
+ }
570
+ return out;
571
+ }
572
+
573
+ Promise.resolve = resolve;
574
+ function resolve(value) {
575
+ if (value instanceof this) {
576
+ return value;
577
+ }
578
+ return handlers.resolve(new this(INTERNAL), value);
579
+ }
580
+
581
+ Promise.reject = reject;
582
+ function reject(reason) {
583
+ var promise = new this(INTERNAL);
584
+ return handlers.reject(promise, reason);
585
+ }
586
+
587
+ Promise.all = all;
588
+ function all(iterable) {
589
+ var self = this;
590
+ if (Object.prototype.toString.call(iterable) !== '[object Array]') {
591
+ return this.reject(new TypeError('must be an array'));
592
+ }
593
+
594
+ var len = iterable.length;
595
+ var called = false;
596
+ if (!len) {
597
+ return this.resolve([]);
598
+ }
599
+
600
+ var values = new Array(len);
601
+ var resolved = 0;
602
+ var i = -1;
603
+ var promise = new this(INTERNAL);
604
+
605
+ while (++i < len) {
606
+ allResolver(iterable[i], i);
607
+ }
608
+ return promise;
609
+ function allResolver(value, i) {
610
+ self.resolve(value).then(resolveFromAll, function (error) {
611
+ if (!called) {
612
+ called = true;
613
+ handlers.reject(promise, error);
614
+ }
615
+ });
616
+ function resolveFromAll(outValue) {
617
+ values[i] = outValue;
618
+ if (++resolved === len && !called) {
619
+ called = true;
620
+ handlers.resolve(promise, values);
621
+ }
622
+ }
623
+ }
624
+ }
625
+
626
+ Promise.race = race;
627
+ function race(iterable) {
628
+ var self = this;
629
+ if (Object.prototype.toString.call(iterable) !== '[object Array]') {
630
+ return this.reject(new TypeError('must be an array'));
631
+ }
632
+
633
+ var len = iterable.length;
634
+ var called = false;
635
+ if (!len) {
636
+ return this.resolve([]);
637
+ }
638
+
639
+ var i = -1;
640
+ var promise = new this(INTERNAL);
641
+
642
+ while (++i < len) {
643
+ resolver(iterable[i]);
644
+ }
645
+ return promise;
646
+ function resolver(value) {
647
+ self.resolve(value).then(function (response) {
648
+ if (!called) {
649
+ called = true;
650
+ handlers.resolve(promise, response);
651
+ }
652
+ }, function (error) {
653
+ if (!called) {
654
+ called = true;
655
+ handlers.reject(promise, error);
656
+ }
657
+ });
658
+ }
659
+ }
660
+
661
+ },{"1":1}],3:[function(_dereq_,module,exports){
662
+ (function (global){
663
+ if (typeof global.Promise !== 'function') {
664
+ global.Promise = _dereq_(2);
665
+ }
666
+
667
+ }).call(this,typeof commonjsGlobal !== "undefined" ? commonjsGlobal : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {});
668
+ },{"2":2}],4:[function(_dereq_,module,exports){
669
+
670
+ 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; };
671
+
672
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
673
+
674
+ function getIDB() {
675
+ /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
676
+ try {
677
+ if (typeof indexedDB !== 'undefined') {
678
+ return indexedDB;
679
+ }
680
+ if (typeof webkitIndexedDB !== 'undefined') {
681
+ return webkitIndexedDB;
682
+ }
683
+ if (typeof mozIndexedDB !== 'undefined') {
684
+ return mozIndexedDB;
685
+ }
686
+ if (typeof OIndexedDB !== 'undefined') {
687
+ return OIndexedDB;
688
+ }
689
+ if (typeof msIndexedDB !== 'undefined') {
690
+ return msIndexedDB;
691
+ }
692
+ } catch (e) {
693
+ return;
694
+ }
695
+ }
696
+
697
+ var idb = getIDB();
698
+
699
+ function isIndexedDBValid() {
700
+ try {
701
+ // Initialize IndexedDB; fall back to vendor-prefixed versions
702
+ // if needed.
703
+ if (!idb || !idb.open) {
704
+ return false;
705
+ }
706
+ // We mimic PouchDB here;
707
+ //
708
+ // We test for openDatabase because IE Mobile identifies itself
709
+ // as Safari. Oh the lulz...
710
+ var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
711
+
712
+ var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;
713
+
714
+ // Safari <10.1 does not meet our requirements for IDB support
715
+ // (see: https://github.com/pouchdb/pouchdb/issues/5572).
716
+ // Safari 10.1 shipped with fetch, we can use that to detect it.
717
+ // Note: this creates issues with `window.fetch` polyfills and
718
+ // overrides; see:
719
+ // https://github.com/localForage/localForage/issues/856
720
+ return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
721
+ // some outdated implementations of IDB that appear on Samsung
722
+ // and HTC Android devices <4.4 are missing IDBKeyRange
723
+ // See: https://github.com/mozilla/localForage/issues/128
724
+ // See: https://github.com/mozilla/localForage/issues/272
725
+ typeof IDBKeyRange !== 'undefined';
726
+ } catch (e) {
727
+ return false;
728
+ }
729
+ }
730
+
731
+ // Abstracts constructing a Blob object, so it also works in older
732
+ // browsers that don't support the native Blob constructor. (i.e.
733
+ // old QtWebKit versions, at least).
734
+ // Abstracts constructing a Blob object, so it also works in older
735
+ // browsers that don't support the native Blob constructor. (i.e.
736
+ // old QtWebKit versions, at least).
737
+ function createBlob(parts, properties) {
738
+ /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
739
+ parts = parts || [];
740
+ properties = properties || {};
741
+ try {
742
+ return new Blob(parts, properties);
743
+ } catch (e) {
744
+ if (e.name !== 'TypeError') {
745
+ throw e;
746
+ }
747
+ var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
748
+ var builder = new Builder();
749
+ for (var i = 0; i < parts.length; i += 1) {
750
+ builder.append(parts[i]);
751
+ }
752
+ return builder.getBlob(properties.type);
753
+ }
754
+ }
755
+
756
+ // This is CommonJS because lie is an external dependency, so Rollup
757
+ // can just ignore it.
758
+ if (typeof Promise === 'undefined') {
759
+ // In the "nopromises" build this will just throw if you don't have
760
+ // a global promise object, but it would throw anyway later.
761
+ _dereq_(3);
762
+ }
763
+ var Promise$1 = Promise;
764
+
765
+ function executeCallback(promise, callback) {
766
+ if (callback) {
767
+ promise.then(function (result) {
768
+ callback(null, result);
769
+ }, function (error) {
770
+ callback(error);
771
+ });
772
+ }
773
+ }
774
+
775
+ function executeTwoCallbacks(promise, callback, errorCallback) {
776
+ if (typeof callback === 'function') {
777
+ promise.then(callback);
778
+ }
779
+
780
+ if (typeof errorCallback === 'function') {
781
+ promise["catch"](errorCallback);
782
+ }
783
+ }
784
+
785
+ function normalizeKey(key) {
786
+ // Cast the key to a string, as that's all we can set as a key.
787
+ if (typeof key !== 'string') {
788
+ console.warn(key + ' used as a key, but it is not a string.');
789
+ key = String(key);
790
+ }
791
+
792
+ return key;
793
+ }
794
+
795
+ function getCallback() {
796
+ if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {
797
+ return arguments[arguments.length - 1];
798
+ }
799
+ }
800
+
801
+ // Some code originally from async_storage.js in
802
+ // [Gaia](https://github.com/mozilla-b2g/gaia).
803
+
804
+ var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
805
+ var supportsBlobs = void 0;
806
+ var dbContexts = {};
807
+ var toString = Object.prototype.toString;
808
+
809
+ // Transaction Modes
810
+ var READ_ONLY = 'readonly';
811
+ var READ_WRITE = 'readwrite';
812
+
813
+ // Transform a binary string to an array buffer, because otherwise
814
+ // weird stuff happens when you try to work with the binary string directly.
815
+ // It is known.
816
+ // From http://stackoverflow.com/questions/14967647/ (continues on next line)
817
+ // encode-decode-image-with-base64-breaks-image (2013-04-21)
818
+ function _binStringToArrayBuffer(bin) {
819
+ var length = bin.length;
820
+ var buf = new ArrayBuffer(length);
821
+ var arr = new Uint8Array(buf);
822
+ for (var i = 0; i < length; i++) {
823
+ arr[i] = bin.charCodeAt(i);
824
+ }
825
+ return buf;
826
+ }
827
+
828
+ //
829
+ // Blobs are not supported in all versions of IndexedDB, notably
830
+ // Chrome <37 and Android <5. In those versions, storing a blob will throw.
831
+ //
832
+ // Various other blob bugs exist in Chrome v37-42 (inclusive).
833
+ // Detecting them is expensive and confusing to users, and Chrome 37-42
834
+ // is at very low usage worldwide, so we do a hacky userAgent check instead.
835
+ //
836
+ // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
837
+ // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
838
+ // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
839
+ //
840
+ // Code borrowed from PouchDB. See:
841
+ // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
842
+ //
843
+ function _checkBlobSupportWithoutCaching(idb) {
844
+ return new Promise$1(function (resolve) {
845
+ var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
846
+ var blob = createBlob(['']);
847
+ txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
848
+
849
+ txn.onabort = function (e) {
850
+ // If the transaction aborts now its due to not being able to
851
+ // write to the database, likely due to the disk being full
852
+ e.preventDefault();
853
+ e.stopPropagation();
854
+ resolve(false);
855
+ };
856
+
857
+ txn.oncomplete = function () {
858
+ var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
859
+ var matchedEdge = navigator.userAgent.match(/Edge\//);
860
+ // MS Edge pretends to be Chrome 42:
861
+ // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
862
+ resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
863
+ };
864
+ })["catch"](function () {
865
+ return false; // error, so assume unsupported
866
+ });
867
+ }
868
+
869
+ function _checkBlobSupport(idb) {
870
+ if (typeof supportsBlobs === 'boolean') {
871
+ return Promise$1.resolve(supportsBlobs);
872
+ }
873
+ return _checkBlobSupportWithoutCaching(idb).then(function (value) {
874
+ supportsBlobs = value;
875
+ return supportsBlobs;
876
+ });
877
+ }
878
+
879
+ function _deferReadiness(dbInfo) {
880
+ var dbContext = dbContexts[dbInfo.name];
881
+
882
+ // Create a deferred object representing the current database operation.
883
+ var deferredOperation = {};
884
+
885
+ deferredOperation.promise = new Promise$1(function (resolve, reject) {
886
+ deferredOperation.resolve = resolve;
887
+ deferredOperation.reject = reject;
888
+ });
889
+
890
+ // Enqueue the deferred operation.
891
+ dbContext.deferredOperations.push(deferredOperation);
892
+
893
+ // Chain its promise to the database readiness.
894
+ if (!dbContext.dbReady) {
895
+ dbContext.dbReady = deferredOperation.promise;
896
+ } else {
897
+ dbContext.dbReady = dbContext.dbReady.then(function () {
898
+ return deferredOperation.promise;
899
+ });
900
+ }
901
+ }
902
+
903
+ function _advanceReadiness(dbInfo) {
904
+ var dbContext = dbContexts[dbInfo.name];
905
+
906
+ // Dequeue a deferred operation.
907
+ var deferredOperation = dbContext.deferredOperations.pop();
908
+
909
+ // Resolve its promise (which is part of the database readiness
910
+ // chain of promises).
911
+ if (deferredOperation) {
912
+ deferredOperation.resolve();
913
+ return deferredOperation.promise;
914
+ }
915
+ }
916
+
917
+ function _rejectReadiness(dbInfo, err) {
918
+ var dbContext = dbContexts[dbInfo.name];
919
+
920
+ // Dequeue a deferred operation.
921
+ var deferredOperation = dbContext.deferredOperations.pop();
922
+
923
+ // Reject its promise (which is part of the database readiness
924
+ // chain of promises).
925
+ if (deferredOperation) {
926
+ deferredOperation.reject(err);
927
+ return deferredOperation.promise;
928
+ }
929
+ }
930
+
931
+ function _getConnection(dbInfo, upgradeNeeded) {
932
+ return new Promise$1(function (resolve, reject) {
933
+ dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
934
+
935
+ if (dbInfo.db) {
936
+ if (upgradeNeeded) {
937
+ _deferReadiness(dbInfo);
938
+ dbInfo.db.close();
939
+ } else {
940
+ return resolve(dbInfo.db);
941
+ }
942
+ }
943
+
944
+ var dbArgs = [dbInfo.name];
945
+
946
+ if (upgradeNeeded) {
947
+ dbArgs.push(dbInfo.version);
948
+ }
949
+
950
+ var openreq = idb.open.apply(idb, dbArgs);
951
+
952
+ if (upgradeNeeded) {
953
+ openreq.onupgradeneeded = function (e) {
954
+ var db = openreq.result;
955
+ try {
956
+ db.createObjectStore(dbInfo.storeName);
957
+ if (e.oldVersion <= 1) {
958
+ // Added when support for blob shims was added
959
+ db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
960
+ }
961
+ } catch (ex) {
962
+ if (ex.name === 'ConstraintError') {
963
+ console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
964
+ } else {
965
+ throw ex;
966
+ }
967
+ }
968
+ };
969
+ }
970
+
971
+ openreq.onerror = function (e) {
972
+ e.preventDefault();
973
+ reject(openreq.error);
974
+ };
975
+
976
+ openreq.onsuccess = function () {
977
+ var db = openreq.result;
978
+ db.onversionchange = function (e) {
979
+ // Triggered when the database is modified (e.g. adding an objectStore) or
980
+ // deleted (even when initiated by other sessions in different tabs).
981
+ // Closing the connection here prevents those operations from being blocked.
982
+ // If the database is accessed again later by this instance, the connection
983
+ // will be reopened or the database recreated as needed.
984
+ e.target.close();
985
+ };
986
+ resolve(db);
987
+ _advanceReadiness(dbInfo);
988
+ };
989
+ });
990
+ }
991
+
992
+ function _getOriginalConnection(dbInfo) {
993
+ return _getConnection(dbInfo, false);
994
+ }
995
+
996
+ function _getUpgradedConnection(dbInfo) {
997
+ return _getConnection(dbInfo, true);
998
+ }
999
+
1000
+ function _isUpgradeNeeded(dbInfo, defaultVersion) {
1001
+ if (!dbInfo.db) {
1002
+ return true;
1003
+ }
1004
+
1005
+ var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
1006
+ var isDowngrade = dbInfo.version < dbInfo.db.version;
1007
+ var isUpgrade = dbInfo.version > dbInfo.db.version;
1008
+
1009
+ if (isDowngrade) {
1010
+ // If the version is not the default one
1011
+ // then warn for impossible downgrade.
1012
+ if (dbInfo.version !== defaultVersion) {
1013
+ console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
1014
+ }
1015
+ // Align the versions to prevent errors.
1016
+ dbInfo.version = dbInfo.db.version;
1017
+ }
1018
+
1019
+ if (isUpgrade || isNewStore) {
1020
+ // If the store is new then increment the version (if needed).
1021
+ // This will trigger an "upgradeneeded" event which is required
1022
+ // for creating a store.
1023
+ if (isNewStore) {
1024
+ var incVersion = dbInfo.db.version + 1;
1025
+ if (incVersion > dbInfo.version) {
1026
+ dbInfo.version = incVersion;
1027
+ }
1028
+ }
1029
+
1030
+ return true;
1031
+ }
1032
+
1033
+ return false;
1034
+ }
1035
+
1036
+ // encode a blob for indexeddb engines that don't support blobs
1037
+ function _encodeBlob(blob) {
1038
+ return new Promise$1(function (resolve, reject) {
1039
+ var reader = new FileReader();
1040
+ reader.onerror = reject;
1041
+ reader.onloadend = function (e) {
1042
+ var base64 = btoa(e.target.result || '');
1043
+ resolve({
1044
+ __local_forage_encoded_blob: true,
1045
+ data: base64,
1046
+ type: blob.type
1047
+ });
1048
+ };
1049
+ reader.readAsBinaryString(blob);
1050
+ });
1051
+ }
1052
+
1053
+ // decode an encoded blob
1054
+ function _decodeBlob(encodedBlob) {
1055
+ var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
1056
+ return createBlob([arrayBuff], { type: encodedBlob.type });
1057
+ }
1058
+
1059
+ // is this one of our fancy encoded blobs?
1060
+ function _isEncodedBlob(value) {
1061
+ return value && value.__local_forage_encoded_blob;
1062
+ }
1063
+
1064
+ // Specialize the default `ready()` function by making it dependent
1065
+ // on the current database operations. Thus, the driver will be actually
1066
+ // ready when it's been initialized (default) *and* there are no pending
1067
+ // operations on the database (initiated by some other instances).
1068
+ function _fullyReady(callback) {
1069
+ var self = this;
1070
+
1071
+ var promise = self._initReady().then(function () {
1072
+ var dbContext = dbContexts[self._dbInfo.name];
1073
+
1074
+ if (dbContext && dbContext.dbReady) {
1075
+ return dbContext.dbReady;
1076
+ }
1077
+ });
1078
+
1079
+ executeTwoCallbacks(promise, callback, callback);
1080
+ return promise;
1081
+ }
1082
+
1083
+ // Try to establish a new db connection to replace the
1084
+ // current one which is broken (i.e. experiencing
1085
+ // InvalidStateError while creating a transaction).
1086
+ function _tryReconnect(dbInfo) {
1087
+ _deferReadiness(dbInfo);
1088
+
1089
+ var dbContext = dbContexts[dbInfo.name];
1090
+ var forages = dbContext.forages;
1091
+
1092
+ for (var i = 0; i < forages.length; i++) {
1093
+ var forage = forages[i];
1094
+ if (forage._dbInfo.db) {
1095
+ forage._dbInfo.db.close();
1096
+ forage._dbInfo.db = null;
1097
+ }
1098
+ }
1099
+ dbInfo.db = null;
1100
+
1101
+ return _getOriginalConnection(dbInfo).then(function (db) {
1102
+ dbInfo.db = db;
1103
+ if (_isUpgradeNeeded(dbInfo)) {
1104
+ // Reopen the database for upgrading.
1105
+ return _getUpgradedConnection(dbInfo);
1106
+ }
1107
+ return db;
1108
+ }).then(function (db) {
1109
+ // store the latest db reference
1110
+ // in case the db was upgraded
1111
+ dbInfo.db = dbContext.db = db;
1112
+ for (var i = 0; i < forages.length; i++) {
1113
+ forages[i]._dbInfo.db = db;
1114
+ }
1115
+ })["catch"](function (err) {
1116
+ _rejectReadiness(dbInfo, err);
1117
+ throw err;
1118
+ });
1119
+ }
1120
+
1121
+ // FF doesn't like Promises (micro-tasks) and IDDB store operations,
1122
+ // so we have to do it with callbacks
1123
+ function createTransaction(dbInfo, mode, callback, retries) {
1124
+ if (retries === undefined) {
1125
+ retries = 1;
1126
+ }
1127
+
1128
+ try {
1129
+ var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
1130
+ callback(null, tx);
1131
+ } catch (err) {
1132
+ if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
1133
+ return Promise$1.resolve().then(function () {
1134
+ if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
1135
+ // increase the db version, to create the new ObjectStore
1136
+ if (dbInfo.db) {
1137
+ dbInfo.version = dbInfo.db.version + 1;
1138
+ }
1139
+ // Reopen the database for upgrading.
1140
+ return _getUpgradedConnection(dbInfo);
1141
+ }
1142
+ }).then(function () {
1143
+ return _tryReconnect(dbInfo).then(function () {
1144
+ createTransaction(dbInfo, mode, callback, retries - 1);
1145
+ });
1146
+ })["catch"](callback);
1147
+ }
1148
+
1149
+ callback(err);
1150
+ }
1151
+ }
1152
+
1153
+ function createDbContext() {
1154
+ return {
1155
+ // Running localForages sharing a database.
1156
+ forages: [],
1157
+ // Shared database.
1158
+ db: null,
1159
+ // Database readiness (promise).
1160
+ dbReady: null,
1161
+ // Deferred operations on the database.
1162
+ deferredOperations: []
1163
+ };
1164
+ }
1165
+
1166
+ // Open the IndexedDB database (automatically creates one if one didn't
1167
+ // previously exist), using any options set in the config.
1168
+ function _initStorage(options) {
1169
+ var self = this;
1170
+ var dbInfo = {
1171
+ db: null
1172
+ };
1173
+
1174
+ if (options) {
1175
+ for (var i in options) {
1176
+ dbInfo[i] = options[i];
1177
+ }
1178
+ }
1179
+
1180
+ // Get the current context of the database;
1181
+ var dbContext = dbContexts[dbInfo.name];
1182
+
1183
+ // ...or create a new context.
1184
+ if (!dbContext) {
1185
+ dbContext = createDbContext();
1186
+ // Register the new context in the global container.
1187
+ dbContexts[dbInfo.name] = dbContext;
1188
+ }
1189
+
1190
+ // Register itself as a running localForage in the current context.
1191
+ dbContext.forages.push(self);
1192
+
1193
+ // Replace the default `ready()` function with the specialized one.
1194
+ if (!self._initReady) {
1195
+ self._initReady = self.ready;
1196
+ self.ready = _fullyReady;
1197
+ }
1198
+
1199
+ // Create an array of initialization states of the related localForages.
1200
+ var initPromises = [];
1201
+
1202
+ function ignoreErrors() {
1203
+ // Don't handle errors here,
1204
+ // just makes sure related localForages aren't pending.
1205
+ return Promise$1.resolve();
1206
+ }
1207
+
1208
+ for (var j = 0; j < dbContext.forages.length; j++) {
1209
+ var forage = dbContext.forages[j];
1210
+ if (forage !== self) {
1211
+ // Don't wait for itself...
1212
+ initPromises.push(forage._initReady()["catch"](ignoreErrors));
1213
+ }
1214
+ }
1215
+
1216
+ // Take a snapshot of the related localForages.
1217
+ var forages = dbContext.forages.slice(0);
1218
+
1219
+ // Initialize the connection process only when
1220
+ // all the related localForages aren't pending.
1221
+ return Promise$1.all(initPromises).then(function () {
1222
+ dbInfo.db = dbContext.db;
1223
+ // Get the connection or open a new one without upgrade.
1224
+ return _getOriginalConnection(dbInfo);
1225
+ }).then(function (db) {
1226
+ dbInfo.db = db;
1227
+ if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
1228
+ // Reopen the database for upgrading.
1229
+ return _getUpgradedConnection(dbInfo);
1230
+ }
1231
+ return db;
1232
+ }).then(function (db) {
1233
+ dbInfo.db = dbContext.db = db;
1234
+ self._dbInfo = dbInfo;
1235
+ // Share the final connection amongst related localForages.
1236
+ for (var k = 0; k < forages.length; k++) {
1237
+ var forage = forages[k];
1238
+ if (forage !== self) {
1239
+ // Self is already up-to-date.
1240
+ forage._dbInfo.db = dbInfo.db;
1241
+ forage._dbInfo.version = dbInfo.version;
1242
+ }
1243
+ }
1244
+ });
1245
+ }
1246
+
1247
+ function getItem(key, callback) {
1248
+ var self = this;
1249
+
1250
+ key = normalizeKey(key);
1251
+
1252
+ var promise = new Promise$1(function (resolve, reject) {
1253
+ self.ready().then(function () {
1254
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1255
+ if (err) {
1256
+ return reject(err);
1257
+ }
1258
+
1259
+ try {
1260
+ var store = transaction.objectStore(self._dbInfo.storeName);
1261
+ var req = store.get(key);
1262
+
1263
+ req.onsuccess = function () {
1264
+ var value = req.result;
1265
+ if (value === undefined) {
1266
+ value = null;
1267
+ }
1268
+ if (_isEncodedBlob(value)) {
1269
+ value = _decodeBlob(value);
1270
+ }
1271
+ resolve(value);
1272
+ };
1273
+
1274
+ req.onerror = function () {
1275
+ reject(req.error);
1276
+ };
1277
+ } catch (e) {
1278
+ reject(e);
1279
+ }
1280
+ });
1281
+ })["catch"](reject);
1282
+ });
1283
+
1284
+ executeCallback(promise, callback);
1285
+ return promise;
1286
+ }
1287
+
1288
+ // Iterate over all items stored in database.
1289
+ function iterate(iterator, callback) {
1290
+ var self = this;
1291
+
1292
+ var promise = new Promise$1(function (resolve, reject) {
1293
+ self.ready().then(function () {
1294
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1295
+ if (err) {
1296
+ return reject(err);
1297
+ }
1298
+
1299
+ try {
1300
+ var store = transaction.objectStore(self._dbInfo.storeName);
1301
+ var req = store.openCursor();
1302
+ var iterationNumber = 1;
1303
+
1304
+ req.onsuccess = function () {
1305
+ var cursor = req.result;
1306
+
1307
+ if (cursor) {
1308
+ var value = cursor.value;
1309
+ if (_isEncodedBlob(value)) {
1310
+ value = _decodeBlob(value);
1311
+ }
1312
+ var result = iterator(value, cursor.key, iterationNumber++);
1313
+
1314
+ // when the iterator callback returns any
1315
+ // (non-`undefined`) value, then we stop
1316
+ // the iteration immediately
1317
+ if (result !== void 0) {
1318
+ resolve(result);
1319
+ } else {
1320
+ cursor["continue"]();
1321
+ }
1322
+ } else {
1323
+ resolve();
1324
+ }
1325
+ };
1326
+
1327
+ req.onerror = function () {
1328
+ reject(req.error);
1329
+ };
1330
+ } catch (e) {
1331
+ reject(e);
1332
+ }
1333
+ });
1334
+ })["catch"](reject);
1335
+ });
1336
+
1337
+ executeCallback(promise, callback);
1338
+
1339
+ return promise;
1340
+ }
1341
+
1342
+ function setItem(key, value, callback) {
1343
+ var self = this;
1344
+
1345
+ key = normalizeKey(key);
1346
+
1347
+ var promise = new Promise$1(function (resolve, reject) {
1348
+ var dbInfo;
1349
+ self.ready().then(function () {
1350
+ dbInfo = self._dbInfo;
1351
+ if (toString.call(value) === '[object Blob]') {
1352
+ return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
1353
+ if (blobSupport) {
1354
+ return value;
1355
+ }
1356
+ return _encodeBlob(value);
1357
+ });
1358
+ }
1359
+ return value;
1360
+ }).then(function (value) {
1361
+ createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1362
+ if (err) {
1363
+ return reject(err);
1364
+ }
1365
+
1366
+ try {
1367
+ var store = transaction.objectStore(self._dbInfo.storeName);
1368
+
1369
+ // The reason we don't _save_ null is because IE 10 does
1370
+ // not support saving the `null` type in IndexedDB. How
1371
+ // ironic, given the bug below!
1372
+ // See: https://github.com/mozilla/localForage/issues/161
1373
+ if (value === null) {
1374
+ value = undefined;
1375
+ }
1376
+
1377
+ var req = store.put(value, key);
1378
+
1379
+ transaction.oncomplete = function () {
1380
+ // Cast to undefined so the value passed to
1381
+ // callback/promise is the same as what one would get out
1382
+ // of `getItem()` later. This leads to some weirdness
1383
+ // (setItem('foo', undefined) will return `null`), but
1384
+ // it's not my fault localStorage is our baseline and that
1385
+ // it's weird.
1386
+ if (value === undefined) {
1387
+ value = null;
1388
+ }
1389
+
1390
+ resolve(value);
1391
+ };
1392
+ transaction.onabort = transaction.onerror = function () {
1393
+ var err = req.error ? req.error : req.transaction.error;
1394
+ reject(err);
1395
+ };
1396
+ } catch (e) {
1397
+ reject(e);
1398
+ }
1399
+ });
1400
+ })["catch"](reject);
1401
+ });
1402
+
1403
+ executeCallback(promise, callback);
1404
+ return promise;
1405
+ }
1406
+
1407
+ function removeItem(key, callback) {
1408
+ var self = this;
1409
+
1410
+ key = normalizeKey(key);
1411
+
1412
+ var promise = new Promise$1(function (resolve, reject) {
1413
+ self.ready().then(function () {
1414
+ createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1415
+ if (err) {
1416
+ return reject(err);
1417
+ }
1418
+
1419
+ try {
1420
+ var store = transaction.objectStore(self._dbInfo.storeName);
1421
+ // We use a Grunt task to make this safe for IE and some
1422
+ // versions of Android (including those used by Cordova).
1423
+ // Normally IE won't like `.delete()` and will insist on
1424
+ // using `['delete']()`, but we have a build step that
1425
+ // fixes this for us now.
1426
+ var req = store["delete"](key);
1427
+ transaction.oncomplete = function () {
1428
+ resolve();
1429
+ };
1430
+
1431
+ transaction.onerror = function () {
1432
+ reject(req.error);
1433
+ };
1434
+
1435
+ // The request will be also be aborted if we've exceeded our storage
1436
+ // space.
1437
+ transaction.onabort = function () {
1438
+ var err = req.error ? req.error : req.transaction.error;
1439
+ reject(err);
1440
+ };
1441
+ } catch (e) {
1442
+ reject(e);
1443
+ }
1444
+ });
1445
+ })["catch"](reject);
1446
+ });
1447
+
1448
+ executeCallback(promise, callback);
1449
+ return promise;
1450
+ }
1451
+
1452
+ function clear(callback) {
1453
+ var self = this;
1454
+
1455
+ var promise = new Promise$1(function (resolve, reject) {
1456
+ self.ready().then(function () {
1457
+ createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
1458
+ if (err) {
1459
+ return reject(err);
1460
+ }
1461
+
1462
+ try {
1463
+ var store = transaction.objectStore(self._dbInfo.storeName);
1464
+ var req = store.clear();
1465
+
1466
+ transaction.oncomplete = function () {
1467
+ resolve();
1468
+ };
1469
+
1470
+ transaction.onabort = transaction.onerror = function () {
1471
+ var err = req.error ? req.error : req.transaction.error;
1472
+ reject(err);
1473
+ };
1474
+ } catch (e) {
1475
+ reject(e);
1476
+ }
1477
+ });
1478
+ })["catch"](reject);
1479
+ });
1480
+
1481
+ executeCallback(promise, callback);
1482
+ return promise;
1483
+ }
1484
+
1485
+ function length(callback) {
1486
+ var self = this;
1487
+
1488
+ var promise = new Promise$1(function (resolve, reject) {
1489
+ self.ready().then(function () {
1490
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1491
+ if (err) {
1492
+ return reject(err);
1493
+ }
1494
+
1495
+ try {
1496
+ var store = transaction.objectStore(self._dbInfo.storeName);
1497
+ var req = store.count();
1498
+
1499
+ req.onsuccess = function () {
1500
+ resolve(req.result);
1501
+ };
1502
+
1503
+ req.onerror = function () {
1504
+ reject(req.error);
1505
+ };
1506
+ } catch (e) {
1507
+ reject(e);
1508
+ }
1509
+ });
1510
+ })["catch"](reject);
1511
+ });
1512
+
1513
+ executeCallback(promise, callback);
1514
+ return promise;
1515
+ }
1516
+
1517
+ function key(n, callback) {
1518
+ var self = this;
1519
+
1520
+ var promise = new Promise$1(function (resolve, reject) {
1521
+ if (n < 0) {
1522
+ resolve(null);
1523
+
1524
+ return;
1525
+ }
1526
+
1527
+ self.ready().then(function () {
1528
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1529
+ if (err) {
1530
+ return reject(err);
1531
+ }
1532
+
1533
+ try {
1534
+ var store = transaction.objectStore(self._dbInfo.storeName);
1535
+ var advanced = false;
1536
+ var req = store.openKeyCursor();
1537
+
1538
+ req.onsuccess = function () {
1539
+ var cursor = req.result;
1540
+ if (!cursor) {
1541
+ // this means there weren't enough keys
1542
+ resolve(null);
1543
+
1544
+ return;
1545
+ }
1546
+
1547
+ if (n === 0) {
1548
+ // We have the first key, return it if that's what they
1549
+ // wanted.
1550
+ resolve(cursor.key);
1551
+ } else {
1552
+ if (!advanced) {
1553
+ // Otherwise, ask the cursor to skip ahead n
1554
+ // records.
1555
+ advanced = true;
1556
+ cursor.advance(n);
1557
+ } else {
1558
+ // When we get here, we've got the nth key.
1559
+ resolve(cursor.key);
1560
+ }
1561
+ }
1562
+ };
1563
+
1564
+ req.onerror = function () {
1565
+ reject(req.error);
1566
+ };
1567
+ } catch (e) {
1568
+ reject(e);
1569
+ }
1570
+ });
1571
+ })["catch"](reject);
1572
+ });
1573
+
1574
+ executeCallback(promise, callback);
1575
+ return promise;
1576
+ }
1577
+
1578
+ function keys(callback) {
1579
+ var self = this;
1580
+
1581
+ var promise = new Promise$1(function (resolve, reject) {
1582
+ self.ready().then(function () {
1583
+ createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
1584
+ if (err) {
1585
+ return reject(err);
1586
+ }
1587
+
1588
+ try {
1589
+ var store = transaction.objectStore(self._dbInfo.storeName);
1590
+ var req = store.openKeyCursor();
1591
+ var keys = [];
1592
+
1593
+ req.onsuccess = function () {
1594
+ var cursor = req.result;
1595
+
1596
+ if (!cursor) {
1597
+ resolve(keys);
1598
+ return;
1599
+ }
1600
+
1601
+ keys.push(cursor.key);
1602
+ cursor["continue"]();
1603
+ };
1604
+
1605
+ req.onerror = function () {
1606
+ reject(req.error);
1607
+ };
1608
+ } catch (e) {
1609
+ reject(e);
1610
+ }
1611
+ });
1612
+ })["catch"](reject);
1613
+ });
1614
+
1615
+ executeCallback(promise, callback);
1616
+ return promise;
1617
+ }
1618
+
1619
+ function dropInstance(options, callback) {
1620
+ callback = getCallback.apply(this, arguments);
1621
+
1622
+ var currentConfig = this.config();
1623
+ options = typeof options !== 'function' && options || {};
1624
+ if (!options.name) {
1625
+ options.name = options.name || currentConfig.name;
1626
+ options.storeName = options.storeName || currentConfig.storeName;
1627
+ }
1628
+
1629
+ var self = this;
1630
+ var promise;
1631
+ if (!options.name) {
1632
+ promise = Promise$1.reject('Invalid arguments');
1633
+ } else {
1634
+ var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
1635
+
1636
+ var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
1637
+ var dbContext = dbContexts[options.name];
1638
+ var forages = dbContext.forages;
1639
+ dbContext.db = db;
1640
+ for (var i = 0; i < forages.length; i++) {
1641
+ forages[i]._dbInfo.db = db;
1642
+ }
1643
+ return db;
1644
+ });
1645
+
1646
+ if (!options.storeName) {
1647
+ promise = dbPromise.then(function (db) {
1648
+ _deferReadiness(options);
1649
+
1650
+ var dbContext = dbContexts[options.name];
1651
+ var forages = dbContext.forages;
1652
+
1653
+ db.close();
1654
+ for (var i = 0; i < forages.length; i++) {
1655
+ var forage = forages[i];
1656
+ forage._dbInfo.db = null;
1657
+ }
1658
+
1659
+ var dropDBPromise = new Promise$1(function (resolve, reject) {
1660
+ var req = idb.deleteDatabase(options.name);
1661
+
1662
+ req.onerror = function () {
1663
+ var db = req.result;
1664
+ if (db) {
1665
+ db.close();
1666
+ }
1667
+ reject(req.error);
1668
+ };
1669
+
1670
+ req.onblocked = function () {
1671
+ // Closing all open connections in onversionchange handler should prevent this situation, but if
1672
+ // we do get here, it just means the request remains pending - eventually it will succeed or error
1673
+ console.warn('dropInstance blocked for database "' + options.name + '" until all open connections are closed');
1674
+ };
1675
+
1676
+ req.onsuccess = function () {
1677
+ var db = req.result;
1678
+ if (db) {
1679
+ db.close();
1680
+ }
1681
+ resolve(db);
1682
+ };
1683
+ });
1684
+
1685
+ return dropDBPromise.then(function (db) {
1686
+ dbContext.db = db;
1687
+ for (var i = 0; i < forages.length; i++) {
1688
+ var _forage = forages[i];
1689
+ _advanceReadiness(_forage._dbInfo);
1690
+ }
1691
+ })["catch"](function (err) {
1692
+ (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1693
+ throw err;
1694
+ });
1695
+ });
1696
+ } else {
1697
+ promise = dbPromise.then(function (db) {
1698
+ if (!db.objectStoreNames.contains(options.storeName)) {
1699
+ return;
1700
+ }
1701
+
1702
+ var newVersion = db.version + 1;
1703
+
1704
+ _deferReadiness(options);
1705
+
1706
+ var dbContext = dbContexts[options.name];
1707
+ var forages = dbContext.forages;
1708
+
1709
+ db.close();
1710
+ for (var i = 0; i < forages.length; i++) {
1711
+ var forage = forages[i];
1712
+ forage._dbInfo.db = null;
1713
+ forage._dbInfo.version = newVersion;
1714
+ }
1715
+
1716
+ var dropObjectPromise = new Promise$1(function (resolve, reject) {
1717
+ var req = idb.open(options.name, newVersion);
1718
+
1719
+ req.onerror = function (err) {
1720
+ var db = req.result;
1721
+ db.close();
1722
+ reject(err);
1723
+ };
1724
+
1725
+ req.onupgradeneeded = function () {
1726
+ var db = req.result;
1727
+ db.deleteObjectStore(options.storeName);
1728
+ };
1729
+
1730
+ req.onsuccess = function () {
1731
+ var db = req.result;
1732
+ db.close();
1733
+ resolve(db);
1734
+ };
1735
+ });
1736
+
1737
+ return dropObjectPromise.then(function (db) {
1738
+ dbContext.db = db;
1739
+ for (var j = 0; j < forages.length; j++) {
1740
+ var _forage2 = forages[j];
1741
+ _forage2._dbInfo.db = db;
1742
+ _advanceReadiness(_forage2._dbInfo);
1743
+ }
1744
+ })["catch"](function (err) {
1745
+ (_rejectReadiness(options, err) || Promise$1.resolve())["catch"](function () {});
1746
+ throw err;
1747
+ });
1748
+ });
1749
+ }
1750
+ }
1751
+
1752
+ executeCallback(promise, callback);
1753
+ return promise;
1754
+ }
1755
+
1756
+ var asyncStorage = {
1757
+ _driver: 'asyncStorage',
1758
+ _initStorage: _initStorage,
1759
+ _support: isIndexedDBValid(),
1760
+ iterate: iterate,
1761
+ getItem: getItem,
1762
+ setItem: setItem,
1763
+ removeItem: removeItem,
1764
+ clear: clear,
1765
+ length: length,
1766
+ key: key,
1767
+ keys: keys,
1768
+ dropInstance: dropInstance
1769
+ };
1770
+
1771
+ function isWebSQLValid() {
1772
+ return typeof openDatabase === 'function';
1773
+ }
1774
+
1775
+ // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
1776
+ // it to Base64, so this is how we store it to prevent very strange errors with less
1777
+ // verbose ways of binary <-> string data storage.
1778
+ var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1779
+
1780
+ var BLOB_TYPE_PREFIX = '~~local_forage_type~';
1781
+ var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
1782
+
1783
+ var SERIALIZED_MARKER = '__lfsc__:';
1784
+ var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
1785
+
1786
+ // OMG the serializations!
1787
+ var TYPE_ARRAYBUFFER = 'arbf';
1788
+ var TYPE_BLOB = 'blob';
1789
+ var TYPE_INT8ARRAY = 'si08';
1790
+ var TYPE_UINT8ARRAY = 'ui08';
1791
+ var TYPE_UINT8CLAMPEDARRAY = 'uic8';
1792
+ var TYPE_INT16ARRAY = 'si16';
1793
+ var TYPE_INT32ARRAY = 'si32';
1794
+ var TYPE_UINT16ARRAY = 'ur16';
1795
+ var TYPE_UINT32ARRAY = 'ui32';
1796
+ var TYPE_FLOAT32ARRAY = 'fl32';
1797
+ var TYPE_FLOAT64ARRAY = 'fl64';
1798
+ var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
1799
+
1800
+ var toString$1 = Object.prototype.toString;
1801
+
1802
+ function stringToBuffer(serializedString) {
1803
+ // Fill the string into a ArrayBuffer.
1804
+ var bufferLength = serializedString.length * 0.75;
1805
+ var len = serializedString.length;
1806
+ var i;
1807
+ var p = 0;
1808
+ var encoded1, encoded2, encoded3, encoded4;
1809
+
1810
+ if (serializedString[serializedString.length - 1] === '=') {
1811
+ bufferLength--;
1812
+ if (serializedString[serializedString.length - 2] === '=') {
1813
+ bufferLength--;
1814
+ }
1815
+ }
1816
+
1817
+ var buffer = new ArrayBuffer(bufferLength);
1818
+ var bytes = new Uint8Array(buffer);
1819
+
1820
+ for (i = 0; i < len; i += 4) {
1821
+ encoded1 = BASE_CHARS.indexOf(serializedString[i]);
1822
+ encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
1823
+ encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
1824
+ encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
1825
+
1826
+ /*jslint bitwise: true */
1827
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
1828
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
1829
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
1830
+ }
1831
+ return buffer;
1832
+ }
1833
+
1834
+ // Converts a buffer to a string to store, serialized, in the backend
1835
+ // storage library.
1836
+ function bufferToString(buffer) {
1837
+ // base64-arraybuffer
1838
+ var bytes = new Uint8Array(buffer);
1839
+ var base64String = '';
1840
+ var i;
1841
+
1842
+ for (i = 0; i < bytes.length; i += 3) {
1843
+ /*jslint bitwise: true */
1844
+ base64String += BASE_CHARS[bytes[i] >> 2];
1845
+ base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
1846
+ base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
1847
+ base64String += BASE_CHARS[bytes[i + 2] & 63];
1848
+ }
1849
+
1850
+ if (bytes.length % 3 === 2) {
1851
+ base64String = base64String.substring(0, base64String.length - 1) + '=';
1852
+ } else if (bytes.length % 3 === 1) {
1853
+ base64String = base64String.substring(0, base64String.length - 2) + '==';
1854
+ }
1855
+
1856
+ return base64String;
1857
+ }
1858
+
1859
+ // Serialize a value, afterwards executing a callback (which usually
1860
+ // instructs the `setItem()` callback/promise to be executed). This is how
1861
+ // we store binary data with localStorage.
1862
+ function serialize(value, callback) {
1863
+ var valueType = '';
1864
+ if (value) {
1865
+ valueType = toString$1.call(value);
1866
+ }
1867
+
1868
+ // Cannot use `value instanceof ArrayBuffer` or such here, as these
1869
+ // checks fail when running the tests using casper.js...
1870
+ //
1871
+ // TODO: See why those tests fail and use a better solution.
1872
+ if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
1873
+ // Convert binary arrays to a string and prefix the string with
1874
+ // a special marker.
1875
+ var buffer;
1876
+ var marker = SERIALIZED_MARKER;
1877
+
1878
+ if (value instanceof ArrayBuffer) {
1879
+ buffer = value;
1880
+ marker += TYPE_ARRAYBUFFER;
1881
+ } else {
1882
+ buffer = value.buffer;
1883
+
1884
+ if (valueType === '[object Int8Array]') {
1885
+ marker += TYPE_INT8ARRAY;
1886
+ } else if (valueType === '[object Uint8Array]') {
1887
+ marker += TYPE_UINT8ARRAY;
1888
+ } else if (valueType === '[object Uint8ClampedArray]') {
1889
+ marker += TYPE_UINT8CLAMPEDARRAY;
1890
+ } else if (valueType === '[object Int16Array]') {
1891
+ marker += TYPE_INT16ARRAY;
1892
+ } else if (valueType === '[object Uint16Array]') {
1893
+ marker += TYPE_UINT16ARRAY;
1894
+ } else if (valueType === '[object Int32Array]') {
1895
+ marker += TYPE_INT32ARRAY;
1896
+ } else if (valueType === '[object Uint32Array]') {
1897
+ marker += TYPE_UINT32ARRAY;
1898
+ } else if (valueType === '[object Float32Array]') {
1899
+ marker += TYPE_FLOAT32ARRAY;
1900
+ } else if (valueType === '[object Float64Array]') {
1901
+ marker += TYPE_FLOAT64ARRAY;
1902
+ } else {
1903
+ callback(new Error('Failed to get type for BinaryArray'));
1904
+ }
1905
+ }
1906
+
1907
+ callback(marker + bufferToString(buffer));
1908
+ } else if (valueType === '[object Blob]') {
1909
+ // Conver the blob to a binaryArray and then to a string.
1910
+ var fileReader = new FileReader();
1911
+
1912
+ fileReader.onload = function () {
1913
+ // Backwards-compatible prefix for the blob type.
1914
+ var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
1915
+
1916
+ callback(SERIALIZED_MARKER + TYPE_BLOB + str);
1917
+ };
1918
+
1919
+ fileReader.readAsArrayBuffer(value);
1920
+ } else {
1921
+ try {
1922
+ callback(JSON.stringify(value));
1923
+ } catch (e) {
1924
+ console.error("Couldn't convert value into a JSON string: ", value);
1925
+
1926
+ callback(null, e);
1927
+ }
1928
+ }
1929
+ }
1930
+
1931
+ // Deserialize data we've inserted into a value column/field. We place
1932
+ // special markers into our strings to mark them as encoded; this isn't
1933
+ // as nice as a meta field, but it's the only sane thing we can do whilst
1934
+ // keeping localStorage support intact.
1935
+ //
1936
+ // Oftentimes this will just deserialize JSON content, but if we have a
1937
+ // special marker (SERIALIZED_MARKER, defined above), we will extract
1938
+ // some kind of arraybuffer/binary data/typed array out of the string.
1939
+ function deserialize(value) {
1940
+ // If we haven't marked this string as being specially serialized (i.e.
1941
+ // something other than serialized JSON), we can just return it and be
1942
+ // done with it.
1943
+ if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
1944
+ return JSON.parse(value);
1945
+ }
1946
+
1947
+ // The following code deals with deserializing some kind of Blob or
1948
+ // TypedArray. First we separate out the type of data we're dealing
1949
+ // with from the data itself.
1950
+ var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
1951
+ var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
1952
+
1953
+ var blobType;
1954
+ // Backwards-compatible blob type serialization strategy.
1955
+ // DBs created with older versions of localForage will simply not have the blob type.
1956
+ if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
1957
+ var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
1958
+ blobType = matcher[1];
1959
+ serializedString = serializedString.substring(matcher[0].length);
1960
+ }
1961
+ var buffer = stringToBuffer(serializedString);
1962
+
1963
+ // Return the right type based on the code/type set during
1964
+ // serialization.
1965
+ switch (type) {
1966
+ case TYPE_ARRAYBUFFER:
1967
+ return buffer;
1968
+ case TYPE_BLOB:
1969
+ return createBlob([buffer], { type: blobType });
1970
+ case TYPE_INT8ARRAY:
1971
+ return new Int8Array(buffer);
1972
+ case TYPE_UINT8ARRAY:
1973
+ return new Uint8Array(buffer);
1974
+ case TYPE_UINT8CLAMPEDARRAY:
1975
+ return new Uint8ClampedArray(buffer);
1976
+ case TYPE_INT16ARRAY:
1977
+ return new Int16Array(buffer);
1978
+ case TYPE_UINT16ARRAY:
1979
+ return new Uint16Array(buffer);
1980
+ case TYPE_INT32ARRAY:
1981
+ return new Int32Array(buffer);
1982
+ case TYPE_UINT32ARRAY:
1983
+ return new Uint32Array(buffer);
1984
+ case TYPE_FLOAT32ARRAY:
1985
+ return new Float32Array(buffer);
1986
+ case TYPE_FLOAT64ARRAY:
1987
+ return new Float64Array(buffer);
1988
+ default:
1989
+ throw new Error('Unkown type: ' + type);
1990
+ }
1991
+ }
1992
+
1993
+ var localforageSerializer = {
1994
+ serialize: serialize,
1995
+ deserialize: deserialize,
1996
+ stringToBuffer: stringToBuffer,
1997
+ bufferToString: bufferToString
1998
+ };
1999
+
2000
+ /*
2001
+ * Includes code from:
2002
+ *
2003
+ * base64-arraybuffer
2004
+ * https://github.com/niklasvh/base64-arraybuffer
2005
+ *
2006
+ * Copyright (c) 2012 Niklas von Hertzen
2007
+ * Licensed under the MIT license.
2008
+ */
2009
+
2010
+ function createDbTable(t, dbInfo, callback, errorCallback) {
2011
+ t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);
2012
+ }
2013
+
2014
+ // Open the WebSQL database (automatically creates one if one didn't
2015
+ // previously exist), using any options set in the config.
2016
+ function _initStorage$1(options) {
2017
+ var self = this;
2018
+ var dbInfo = {
2019
+ db: null
2020
+ };
2021
+
2022
+ if (options) {
2023
+ for (var i in options) {
2024
+ dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
2025
+ }
2026
+ }
2027
+
2028
+ var dbInfoPromise = new Promise$1(function (resolve, reject) {
2029
+ // Open the database; the openDatabase API will automatically
2030
+ // create it for us if it doesn't exist.
2031
+ try {
2032
+ dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
2033
+ } catch (e) {
2034
+ return reject(e);
2035
+ }
2036
+
2037
+ // Create our key/value table if it doesn't exist.
2038
+ dbInfo.db.transaction(function (t) {
2039
+ createDbTable(t, dbInfo, function () {
2040
+ self._dbInfo = dbInfo;
2041
+ resolve();
2042
+ }, function (t, error) {
2043
+ reject(error);
2044
+ });
2045
+ }, reject);
2046
+ });
2047
+
2048
+ dbInfo.serializer = localforageSerializer;
2049
+ return dbInfoPromise;
2050
+ }
2051
+
2052
+ function tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {
2053
+ t.executeSql(sqlStatement, args, callback, function (t, error) {
2054
+ if (error.code === error.SYNTAX_ERR) {
2055
+ t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name = ?", [dbInfo.storeName], function (t, results) {
2056
+ if (!results.rows.length) {
2057
+ // if the table is missing (was deleted)
2058
+ // re-create it table and retry
2059
+ createDbTable(t, dbInfo, function () {
2060
+ t.executeSql(sqlStatement, args, callback, errorCallback);
2061
+ }, errorCallback);
2062
+ } else {
2063
+ errorCallback(t, error);
2064
+ }
2065
+ }, errorCallback);
2066
+ } else {
2067
+ errorCallback(t, error);
2068
+ }
2069
+ }, errorCallback);
2070
+ }
2071
+
2072
+ function getItem$1(key, callback) {
2073
+ var self = this;
2074
+
2075
+ key = normalizeKey(key);
2076
+
2077
+ var promise = new Promise$1(function (resolve, reject) {
2078
+ self.ready().then(function () {
2079
+ var dbInfo = self._dbInfo;
2080
+ dbInfo.db.transaction(function (t) {
2081
+ tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
2082
+ var result = results.rows.length ? results.rows.item(0).value : null;
2083
+
2084
+ // Check to see if this is serialized content we need to
2085
+ // unpack.
2086
+ if (result) {
2087
+ result = dbInfo.serializer.deserialize(result);
2088
+ }
2089
+
2090
+ resolve(result);
2091
+ }, function (t, error) {
2092
+ reject(error);
2093
+ });
2094
+ });
2095
+ })["catch"](reject);
2096
+ });
2097
+
2098
+ executeCallback(promise, callback);
2099
+ return promise;
2100
+ }
2101
+
2102
+ function iterate$1(iterator, callback) {
2103
+ var self = this;
2104
+
2105
+ var promise = new Promise$1(function (resolve, reject) {
2106
+ self.ready().then(function () {
2107
+ var dbInfo = self._dbInfo;
2108
+
2109
+ dbInfo.db.transaction(function (t) {
2110
+ tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
2111
+ var rows = results.rows;
2112
+ var length = rows.length;
2113
+
2114
+ for (var i = 0; i < length; i++) {
2115
+ var item = rows.item(i);
2116
+ var result = item.value;
2117
+
2118
+ // Check to see if this is serialized content
2119
+ // we need to unpack.
2120
+ if (result) {
2121
+ result = dbInfo.serializer.deserialize(result);
2122
+ }
2123
+
2124
+ result = iterator(result, item.key, i + 1);
2125
+
2126
+ // void(0) prevents problems with redefinition
2127
+ // of `undefined`.
2128
+ if (result !== void 0) {
2129
+ resolve(result);
2130
+ return;
2131
+ }
2132
+ }
2133
+
2134
+ resolve();
2135
+ }, function (t, error) {
2136
+ reject(error);
2137
+ });
2138
+ });
2139
+ })["catch"](reject);
2140
+ });
2141
+
2142
+ executeCallback(promise, callback);
2143
+ return promise;
2144
+ }
2145
+
2146
+ function _setItem(key, value, callback, retriesLeft) {
2147
+ var self = this;
2148
+
2149
+ key = normalizeKey(key);
2150
+
2151
+ var promise = new Promise$1(function (resolve, reject) {
2152
+ self.ready().then(function () {
2153
+ // The localStorage API doesn't return undefined values in an
2154
+ // "expected" way, so undefined is always cast to null in all
2155
+ // drivers. See: https://github.com/mozilla/localForage/pull/42
2156
+ if (value === undefined) {
2157
+ value = null;
2158
+ }
2159
+
2160
+ // Save the original value to pass to the callback.
2161
+ var originalValue = value;
2162
+
2163
+ var dbInfo = self._dbInfo;
2164
+ dbInfo.serializer.serialize(value, function (value, error) {
2165
+ if (error) {
2166
+ reject(error);
2167
+ } else {
2168
+ dbInfo.db.transaction(function (t) {
2169
+ tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {
2170
+ resolve(originalValue);
2171
+ }, function (t, error) {
2172
+ reject(error);
2173
+ });
2174
+ }, function (sqlError) {
2175
+ // The transaction failed; check
2176
+ // to see if it's a quota error.
2177
+ if (sqlError.code === sqlError.QUOTA_ERR) {
2178
+ // We reject the callback outright for now, but
2179
+ // it's worth trying to re-run the transaction.
2180
+ // Even if the user accepts the prompt to use
2181
+ // more storage on Safari, this error will
2182
+ // be called.
2183
+ //
2184
+ // Try to re-run the transaction.
2185
+ if (retriesLeft > 0) {
2186
+ resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));
2187
+ return;
2188
+ }
2189
+ reject(sqlError);
2190
+ }
2191
+ });
2192
+ }
2193
+ });
2194
+ })["catch"](reject);
2195
+ });
2196
+
2197
+ executeCallback(promise, callback);
2198
+ return promise;
2199
+ }
2200
+
2201
+ function setItem$1(key, value, callback) {
2202
+ return _setItem.apply(this, [key, value, callback, 1]);
2203
+ }
2204
+
2205
+ function removeItem$1(key, callback) {
2206
+ var self = this;
2207
+
2208
+ key = normalizeKey(key);
2209
+
2210
+ var promise = new Promise$1(function (resolve, reject) {
2211
+ self.ready().then(function () {
2212
+ var dbInfo = self._dbInfo;
2213
+ dbInfo.db.transaction(function (t) {
2214
+ tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
2215
+ resolve();
2216
+ }, function (t, error) {
2217
+ reject(error);
2218
+ });
2219
+ });
2220
+ })["catch"](reject);
2221
+ });
2222
+
2223
+ executeCallback(promise, callback);
2224
+ return promise;
2225
+ }
2226
+
2227
+ // Deletes every item in the table.
2228
+ // TODO: Find out if this resets the AUTO_INCREMENT number.
2229
+ function clear$1(callback) {
2230
+ var self = this;
2231
+
2232
+ var promise = new Promise$1(function (resolve, reject) {
2233
+ self.ready().then(function () {
2234
+ var dbInfo = self._dbInfo;
2235
+ dbInfo.db.transaction(function (t) {
2236
+ tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {
2237
+ resolve();
2238
+ }, function (t, error) {
2239
+ reject(error);
2240
+ });
2241
+ });
2242
+ })["catch"](reject);
2243
+ });
2244
+
2245
+ executeCallback(promise, callback);
2246
+ return promise;
2247
+ }
2248
+
2249
+ // Does a simple `COUNT(key)` to get the number of items stored in
2250
+ // localForage.
2251
+ function length$1(callback) {
2252
+ var self = this;
2253
+
2254
+ var promise = new Promise$1(function (resolve, reject) {
2255
+ self.ready().then(function () {
2256
+ var dbInfo = self._dbInfo;
2257
+ dbInfo.db.transaction(function (t) {
2258
+ // Ahhh, SQL makes this one soooooo easy.
2259
+ tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
2260
+ var result = results.rows.item(0).c;
2261
+ resolve(result);
2262
+ }, function (t, error) {
2263
+ reject(error);
2264
+ });
2265
+ });
2266
+ })["catch"](reject);
2267
+ });
2268
+
2269
+ executeCallback(promise, callback);
2270
+ return promise;
2271
+ }
2272
+
2273
+ // Return the key located at key index X; essentially gets the key from a
2274
+ // `WHERE id = ?`. This is the most efficient way I can think to implement
2275
+ // this rarely-used (in my experience) part of the API, but it can seem
2276
+ // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
2277
+ // the ID of each key will change every time it's updated. Perhaps a stored
2278
+ // procedure for the `setItem()` SQL would solve this problem?
2279
+ // TODO: Don't change ID on `setItem()`.
2280
+ function key$1(n, callback) {
2281
+ var self = this;
2282
+
2283
+ var promise = new Promise$1(function (resolve, reject) {
2284
+ self.ready().then(function () {
2285
+ var dbInfo = self._dbInfo;
2286
+ dbInfo.db.transaction(function (t) {
2287
+ tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
2288
+ var result = results.rows.length ? results.rows.item(0).key : null;
2289
+ resolve(result);
2290
+ }, function (t, error) {
2291
+ reject(error);
2292
+ });
2293
+ });
2294
+ })["catch"](reject);
2295
+ });
2296
+
2297
+ executeCallback(promise, callback);
2298
+ return promise;
2299
+ }
2300
+
2301
+ function keys$1(callback) {
2302
+ var self = this;
2303
+
2304
+ var promise = new Promise$1(function (resolve, reject) {
2305
+ self.ready().then(function () {
2306
+ var dbInfo = self._dbInfo;
2307
+ dbInfo.db.transaction(function (t) {
2308
+ tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
2309
+ var keys = [];
2310
+
2311
+ for (var i = 0; i < results.rows.length; i++) {
2312
+ keys.push(results.rows.item(i).key);
2313
+ }
2314
+
2315
+ resolve(keys);
2316
+ }, function (t, error) {
2317
+ reject(error);
2318
+ });
2319
+ });
2320
+ })["catch"](reject);
2321
+ });
2322
+
2323
+ executeCallback(promise, callback);
2324
+ return promise;
2325
+ }
2326
+
2327
+ // https://www.w3.org/TR/webdatabase/#databases
2328
+ // > There is no way to enumerate or delete the databases available for an origin from this API.
2329
+ function getAllStoreNames(db) {
2330
+ return new Promise$1(function (resolve, reject) {
2331
+ db.transaction(function (t) {
2332
+ t.executeSql('SELECT name FROM sqlite_master ' + "WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'", [], function (t, results) {
2333
+ var storeNames = [];
2334
+
2335
+ for (var i = 0; i < results.rows.length; i++) {
2336
+ storeNames.push(results.rows.item(i).name);
2337
+ }
2338
+
2339
+ resolve({
2340
+ db: db,
2341
+ storeNames: storeNames
2342
+ });
2343
+ }, function (t, error) {
2344
+ reject(error);
2345
+ });
2346
+ }, function (sqlError) {
2347
+ reject(sqlError);
2348
+ });
2349
+ });
2350
+ }
2351
+
2352
+ function dropInstance$1(options, callback) {
2353
+ callback = getCallback.apply(this, arguments);
2354
+
2355
+ var currentConfig = this.config();
2356
+ options = typeof options !== 'function' && options || {};
2357
+ if (!options.name) {
2358
+ options.name = options.name || currentConfig.name;
2359
+ options.storeName = options.storeName || currentConfig.storeName;
2360
+ }
2361
+
2362
+ var self = this;
2363
+ var promise;
2364
+ if (!options.name) {
2365
+ promise = Promise$1.reject('Invalid arguments');
2366
+ } else {
2367
+ promise = new Promise$1(function (resolve) {
2368
+ var db;
2369
+ if (options.name === currentConfig.name) {
2370
+ // use the db reference of the current instance
2371
+ db = self._dbInfo.db;
2372
+ } else {
2373
+ db = openDatabase(options.name, '', '', 0);
2374
+ }
2375
+
2376
+ if (!options.storeName) {
2377
+ // drop all database tables
2378
+ resolve(getAllStoreNames(db));
2379
+ } else {
2380
+ resolve({
2381
+ db: db,
2382
+ storeNames: [options.storeName]
2383
+ });
2384
+ }
2385
+ }).then(function (operationInfo) {
2386
+ return new Promise$1(function (resolve, reject) {
2387
+ operationInfo.db.transaction(function (t) {
2388
+ function dropTable(storeName) {
2389
+ return new Promise$1(function (resolve, reject) {
2390
+ t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {
2391
+ resolve();
2392
+ }, function (t, error) {
2393
+ reject(error);
2394
+ });
2395
+ });
2396
+ }
2397
+
2398
+ var operations = [];
2399
+ for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {
2400
+ operations.push(dropTable(operationInfo.storeNames[i]));
2401
+ }
2402
+
2403
+ Promise$1.all(operations).then(function () {
2404
+ resolve();
2405
+ })["catch"](function (e) {
2406
+ reject(e);
2407
+ });
2408
+ }, function (sqlError) {
2409
+ reject(sqlError);
2410
+ });
2411
+ });
2412
+ });
2413
+ }
2414
+
2415
+ executeCallback(promise, callback);
2416
+ return promise;
2417
+ }
2418
+
2419
+ var webSQLStorage = {
2420
+ _driver: 'webSQLStorage',
2421
+ _initStorage: _initStorage$1,
2422
+ _support: isWebSQLValid(),
2423
+ iterate: iterate$1,
2424
+ getItem: getItem$1,
2425
+ setItem: setItem$1,
2426
+ removeItem: removeItem$1,
2427
+ clear: clear$1,
2428
+ length: length$1,
2429
+ key: key$1,
2430
+ keys: keys$1,
2431
+ dropInstance: dropInstance$1
2432
+ };
2433
+
2434
+ function isLocalStorageValid() {
2435
+ try {
2436
+ return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&
2437
+ // in IE8 typeof localStorage.setItem === 'object'
2438
+ !!localStorage.setItem;
2439
+ } catch (e) {
2440
+ return false;
2441
+ }
2442
+ }
2443
+
2444
+ function _getKeyPrefix(options, defaultConfig) {
2445
+ var keyPrefix = options.name + '/';
2446
+
2447
+ if (options.storeName !== defaultConfig.storeName) {
2448
+ keyPrefix += options.storeName + '/';
2449
+ }
2450
+ return keyPrefix;
2451
+ }
2452
+
2453
+ // Check if localStorage throws when saving an item
2454
+ function checkIfLocalStorageThrows() {
2455
+ var localStorageTestKey = '_localforage_support_test';
2456
+
2457
+ try {
2458
+ localStorage.setItem(localStorageTestKey, true);
2459
+ localStorage.removeItem(localStorageTestKey);
2460
+
2461
+ return false;
2462
+ } catch (e) {
2463
+ return true;
2464
+ }
2465
+ }
2466
+
2467
+ // Check if localStorage is usable and allows to save an item
2468
+ // This method checks if localStorage is usable in Safari Private Browsing
2469
+ // mode, or in any other case where the available quota for localStorage
2470
+ // is 0 and there wasn't any saved items yet.
2471
+ function _isLocalStorageUsable() {
2472
+ return !checkIfLocalStorageThrows() || localStorage.length > 0;
2473
+ }
2474
+
2475
+ // Config the localStorage backend, using options set in the config.
2476
+ function _initStorage$2(options) {
2477
+ var self = this;
2478
+ var dbInfo = {};
2479
+ if (options) {
2480
+ for (var i in options) {
2481
+ dbInfo[i] = options[i];
2482
+ }
2483
+ }
2484
+
2485
+ dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);
2486
+
2487
+ if (!_isLocalStorageUsable()) {
2488
+ return Promise$1.reject();
2489
+ }
2490
+
2491
+ self._dbInfo = dbInfo;
2492
+ dbInfo.serializer = localforageSerializer;
2493
+
2494
+ return Promise$1.resolve();
2495
+ }
2496
+
2497
+ // Remove all keys from the datastore, effectively destroying all data in
2498
+ // the app's key/value store!
2499
+ function clear$2(callback) {
2500
+ var self = this;
2501
+ var promise = self.ready().then(function () {
2502
+ var keyPrefix = self._dbInfo.keyPrefix;
2503
+
2504
+ for (var i = localStorage.length - 1; i >= 0; i--) {
2505
+ var key = localStorage.key(i);
2506
+
2507
+ if (key.indexOf(keyPrefix) === 0) {
2508
+ localStorage.removeItem(key);
2509
+ }
2510
+ }
2511
+ });
2512
+
2513
+ executeCallback(promise, callback);
2514
+ return promise;
2515
+ }
2516
+
2517
+ // Retrieve an item from the store. Unlike the original async_storage
2518
+ // library in Gaia, we don't modify return values at all. If a key's value
2519
+ // is `undefined`, we pass that value to the callback function.
2520
+ function getItem$2(key, callback) {
2521
+ var self = this;
2522
+
2523
+ key = normalizeKey(key);
2524
+
2525
+ var promise = self.ready().then(function () {
2526
+ var dbInfo = self._dbInfo;
2527
+ var result = localStorage.getItem(dbInfo.keyPrefix + key);
2528
+
2529
+ // If a result was found, parse it from the serialized
2530
+ // string into a JS object. If result isn't truthy, the key
2531
+ // is likely undefined and we'll pass it straight to the
2532
+ // callback.
2533
+ if (result) {
2534
+ result = dbInfo.serializer.deserialize(result);
2535
+ }
2536
+
2537
+ return result;
2538
+ });
2539
+
2540
+ executeCallback(promise, callback);
2541
+ return promise;
2542
+ }
2543
+
2544
+ // Iterate over all items in the store.
2545
+ function iterate$2(iterator, callback) {
2546
+ var self = this;
2547
+
2548
+ var promise = self.ready().then(function () {
2549
+ var dbInfo = self._dbInfo;
2550
+ var keyPrefix = dbInfo.keyPrefix;
2551
+ var keyPrefixLength = keyPrefix.length;
2552
+ var length = localStorage.length;
2553
+
2554
+ // We use a dedicated iterator instead of the `i` variable below
2555
+ // so other keys we fetch in localStorage aren't counted in
2556
+ // the `iterationNumber` argument passed to the `iterate()`
2557
+ // callback.
2558
+ //
2559
+ // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
2560
+ var iterationNumber = 1;
2561
+
2562
+ for (var i = 0; i < length; i++) {
2563
+ var key = localStorage.key(i);
2564
+ if (key.indexOf(keyPrefix) !== 0) {
2565
+ continue;
2566
+ }
2567
+ var value = localStorage.getItem(key);
2568
+
2569
+ // If a result was found, parse it from the serialized
2570
+ // string into a JS object. If result isn't truthy, the
2571
+ // key is likely undefined and we'll pass it straight
2572
+ // to the iterator.
2573
+ if (value) {
2574
+ value = dbInfo.serializer.deserialize(value);
2575
+ }
2576
+
2577
+ value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
2578
+
2579
+ if (value !== void 0) {
2580
+ return value;
2581
+ }
2582
+ }
2583
+ });
2584
+
2585
+ executeCallback(promise, callback);
2586
+ return promise;
2587
+ }
2588
+
2589
+ // Same as localStorage's key() method, except takes a callback.
2590
+ function key$2(n, callback) {
2591
+ var self = this;
2592
+ var promise = self.ready().then(function () {
2593
+ var dbInfo = self._dbInfo;
2594
+ var result;
2595
+ try {
2596
+ result = localStorage.key(n);
2597
+ } catch (error) {
2598
+ result = null;
2599
+ }
2600
+
2601
+ // Remove the prefix from the key, if a key is found.
2602
+ if (result) {
2603
+ result = result.substring(dbInfo.keyPrefix.length);
2604
+ }
2605
+
2606
+ return result;
2607
+ });
2608
+
2609
+ executeCallback(promise, callback);
2610
+ return promise;
2611
+ }
2612
+
2613
+ function keys$2(callback) {
2614
+ var self = this;
2615
+ var promise = self.ready().then(function () {
2616
+ var dbInfo = self._dbInfo;
2617
+ var length = localStorage.length;
2618
+ var keys = [];
2619
+
2620
+ for (var i = 0; i < length; i++) {
2621
+ var itemKey = localStorage.key(i);
2622
+ if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {
2623
+ keys.push(itemKey.substring(dbInfo.keyPrefix.length));
2624
+ }
2625
+ }
2626
+
2627
+ return keys;
2628
+ });
2629
+
2630
+ executeCallback(promise, callback);
2631
+ return promise;
2632
+ }
2633
+
2634
+ // Supply the number of keys in the datastore to the callback function.
2635
+ function length$2(callback) {
2636
+ var self = this;
2637
+ var promise = self.keys().then(function (keys) {
2638
+ return keys.length;
2639
+ });
2640
+
2641
+ executeCallback(promise, callback);
2642
+ return promise;
2643
+ }
2644
+
2645
+ // Remove an item from the store, nice and simple.
2646
+ function removeItem$2(key, callback) {
2647
+ var self = this;
2648
+
2649
+ key = normalizeKey(key);
2650
+
2651
+ var promise = self.ready().then(function () {
2652
+ var dbInfo = self._dbInfo;
2653
+ localStorage.removeItem(dbInfo.keyPrefix + key);
2654
+ });
2655
+
2656
+ executeCallback(promise, callback);
2657
+ return promise;
2658
+ }
2659
+
2660
+ // Set a key's value and run an optional callback once the value is set.
2661
+ // Unlike Gaia's implementation, the callback function is passed the value,
2662
+ // in case you want to operate on that value only after you're sure it
2663
+ // saved, or something like that.
2664
+ function setItem$2(key, value, callback) {
2665
+ var self = this;
2666
+
2667
+ key = normalizeKey(key);
2668
+
2669
+ var promise = self.ready().then(function () {
2670
+ // Convert undefined values to null.
2671
+ // https://github.com/mozilla/localForage/pull/42
2672
+ if (value === undefined) {
2673
+ value = null;
2674
+ }
2675
+
2676
+ // Save the original value to pass to the callback.
2677
+ var originalValue = value;
2678
+
2679
+ return new Promise$1(function (resolve, reject) {
2680
+ var dbInfo = self._dbInfo;
2681
+ dbInfo.serializer.serialize(value, function (value, error) {
2682
+ if (error) {
2683
+ reject(error);
2684
+ } else {
2685
+ try {
2686
+ localStorage.setItem(dbInfo.keyPrefix + key, value);
2687
+ resolve(originalValue);
2688
+ } catch (e) {
2689
+ // localStorage capacity exceeded.
2690
+ // TODO: Make this a specific error/event.
2691
+ if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
2692
+ reject(e);
2693
+ }
2694
+ reject(e);
2695
+ }
2696
+ }
2697
+ });
2698
+ });
2699
+ });
2700
+
2701
+ executeCallback(promise, callback);
2702
+ return promise;
2703
+ }
2704
+
2705
+ function dropInstance$2(options, callback) {
2706
+ callback = getCallback.apply(this, arguments);
2707
+
2708
+ options = typeof options !== 'function' && options || {};
2709
+ if (!options.name) {
2710
+ var currentConfig = this.config();
2711
+ options.name = options.name || currentConfig.name;
2712
+ options.storeName = options.storeName || currentConfig.storeName;
2713
+ }
2714
+
2715
+ var self = this;
2716
+ var promise;
2717
+ if (!options.name) {
2718
+ promise = Promise$1.reject('Invalid arguments');
2719
+ } else {
2720
+ promise = new Promise$1(function (resolve) {
2721
+ if (!options.storeName) {
2722
+ resolve(options.name + '/');
2723
+ } else {
2724
+ resolve(_getKeyPrefix(options, self._defaultConfig));
2725
+ }
2726
+ }).then(function (keyPrefix) {
2727
+ for (var i = localStorage.length - 1; i >= 0; i--) {
2728
+ var key = localStorage.key(i);
2729
+
2730
+ if (key.indexOf(keyPrefix) === 0) {
2731
+ localStorage.removeItem(key);
2732
+ }
2733
+ }
2734
+ });
2735
+ }
2736
+
2737
+ executeCallback(promise, callback);
2738
+ return promise;
2739
+ }
2740
+
2741
+ var localStorageWrapper = {
2742
+ _driver: 'localStorageWrapper',
2743
+ _initStorage: _initStorage$2,
2744
+ _support: isLocalStorageValid(),
2745
+ iterate: iterate$2,
2746
+ getItem: getItem$2,
2747
+ setItem: setItem$2,
2748
+ removeItem: removeItem$2,
2749
+ clear: clear$2,
2750
+ length: length$2,
2751
+ key: key$2,
2752
+ keys: keys$2,
2753
+ dropInstance: dropInstance$2
2754
+ };
2755
+
2756
+ var sameValue = function sameValue(x, y) {
2757
+ return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
2758
+ };
2759
+
2760
+ var includes = function includes(array, searchElement) {
2761
+ var len = array.length;
2762
+ var i = 0;
2763
+ while (i < len) {
2764
+ if (sameValue(array[i], searchElement)) {
2765
+ return true;
2766
+ }
2767
+ i++;
2768
+ }
2769
+
2770
+ return false;
2771
+ };
2772
+
2773
+ var isArray = Array.isArray || function (arg) {
2774
+ return Object.prototype.toString.call(arg) === '[object Array]';
2775
+ };
2776
+
2777
+ // Drivers are stored here when `defineDriver()` is called.
2778
+ // They are shared across all instances of localForage.
2779
+ var DefinedDrivers = {};
2780
+
2781
+ var DriverSupport = {};
2782
+
2783
+ var DefaultDrivers = {
2784
+ INDEXEDDB: asyncStorage,
2785
+ WEBSQL: webSQLStorage,
2786
+ LOCALSTORAGE: localStorageWrapper
2787
+ };
2788
+
2789
+ var DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];
2790
+
2791
+ var OptionalDriverMethods = ['dropInstance'];
2792
+
2793
+ var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);
2794
+
2795
+ var DefaultConfig = {
2796
+ description: '',
2797
+ driver: DefaultDriverOrder.slice(),
2798
+ name: 'localforage',
2799
+ // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
2800
+ // we can use without a prompt.
2801
+ size: 4980736,
2802
+ storeName: 'keyvaluepairs',
2803
+ version: 1.0
2804
+ };
2805
+
2806
+ function callWhenReady(localForageInstance, libraryMethod) {
2807
+ localForageInstance[libraryMethod] = function () {
2808
+ var _args = arguments;
2809
+ return localForageInstance.ready().then(function () {
2810
+ return localForageInstance[libraryMethod].apply(localForageInstance, _args);
2811
+ });
2812
+ };
2813
+ }
2814
+
2815
+ function extend() {
2816
+ for (var i = 1; i < arguments.length; i++) {
2817
+ var arg = arguments[i];
2818
+
2819
+ if (arg) {
2820
+ for (var _key in arg) {
2821
+ if (arg.hasOwnProperty(_key)) {
2822
+ if (isArray(arg[_key])) {
2823
+ arguments[0][_key] = arg[_key].slice();
2824
+ } else {
2825
+ arguments[0][_key] = arg[_key];
2826
+ }
2827
+ }
2828
+ }
2829
+ }
2830
+ }
2831
+
2832
+ return arguments[0];
2833
+ }
2834
+
2835
+ var LocalForage = function () {
2836
+ function LocalForage(options) {
2837
+ _classCallCheck(this, LocalForage);
2838
+
2839
+ for (var driverTypeKey in DefaultDrivers) {
2840
+ if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {
2841
+ var driver = DefaultDrivers[driverTypeKey];
2842
+ var driverName = driver._driver;
2843
+ this[driverTypeKey] = driverName;
2844
+
2845
+ if (!DefinedDrivers[driverName]) {
2846
+ // we don't need to wait for the promise,
2847
+ // since the default drivers can be defined
2848
+ // in a blocking manner
2849
+ this.defineDriver(driver);
2850
+ }
2851
+ }
2852
+ }
2853
+
2854
+ this._defaultConfig = extend({}, DefaultConfig);
2855
+ this._config = extend({}, this._defaultConfig, options);
2856
+ this._driverSet = null;
2857
+ this._initDriver = null;
2858
+ this._ready = false;
2859
+ this._dbInfo = null;
2860
+
2861
+ this._wrapLibraryMethodsWithReady();
2862
+ this.setDriver(this._config.driver)["catch"](function () {});
2863
+ }
2864
+
2865
+ // Set any config values for localForage; can be called anytime before
2866
+ // the first API call (e.g. `getItem`, `setItem`).
2867
+ // We loop through options so we don't overwrite existing config
2868
+ // values.
2869
+
2870
+
2871
+ LocalForage.prototype.config = function config(options) {
2872
+ // If the options argument is an object, we use it to set values.
2873
+ // Otherwise, we return either a specified config value or all
2874
+ // config values.
2875
+ if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
2876
+ // If localforage is ready and fully initialized, we can't set
2877
+ // any new configuration values. Instead, we return an error.
2878
+ if (this._ready) {
2879
+ return new Error("Can't call config() after localforage " + 'has been used.');
2880
+ }
2881
+
2882
+ for (var i in options) {
2883
+ if (i === 'storeName') {
2884
+ options[i] = options[i].replace(/\W/g, '_');
2885
+ }
2886
+
2887
+ if (i === 'version' && typeof options[i] !== 'number') {
2888
+ return new Error('Database version must be a number.');
2889
+ }
2890
+
2891
+ this._config[i] = options[i];
2892
+ }
2893
+
2894
+ // after all config options are set and
2895
+ // the driver option is used, try setting it
2896
+ if ('driver' in options && options.driver) {
2897
+ return this.setDriver(this._config.driver);
2898
+ }
2899
+
2900
+ return true;
2901
+ } else if (typeof options === 'string') {
2902
+ return this._config[options];
2903
+ } else {
2904
+ return this._config;
2905
+ }
2906
+ };
2907
+
2908
+ // Used to define a custom driver, shared across all instances of
2909
+ // localForage.
2910
+
2911
+
2912
+ LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
2913
+ var promise = new Promise$1(function (resolve, reject) {
2914
+ try {
2915
+ var driverName = driverObject._driver;
2916
+ var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
2917
+
2918
+ // A driver name should be defined and not overlap with the
2919
+ // library-defined, default drivers.
2920
+ if (!driverObject._driver) {
2921
+ reject(complianceError);
2922
+ return;
2923
+ }
2924
+
2925
+ var driverMethods = LibraryMethods.concat('_initStorage');
2926
+ for (var i = 0, len = driverMethods.length; i < len; i++) {
2927
+ var driverMethodName = driverMethods[i];
2928
+
2929
+ // when the property is there,
2930
+ // it should be a method even when optional
2931
+ var isRequired = !includes(OptionalDriverMethods, driverMethodName);
2932
+ if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {
2933
+ reject(complianceError);
2934
+ return;
2935
+ }
2936
+ }
2937
+
2938
+ var configureMissingMethods = function configureMissingMethods() {
2939
+ var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {
2940
+ return function () {
2941
+ var error = new Error('Method ' + methodName + ' is not implemented by the current driver');
2942
+ var promise = Promise$1.reject(error);
2943
+ executeCallback(promise, arguments[arguments.length - 1]);
2944
+ return promise;
2945
+ };
2946
+ };
2947
+
2948
+ for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {
2949
+ var optionalDriverMethod = OptionalDriverMethods[_i];
2950
+ if (!driverObject[optionalDriverMethod]) {
2951
+ driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);
2952
+ }
2953
+ }
2954
+ };
2955
+
2956
+ configureMissingMethods();
2957
+
2958
+ var setDriverSupport = function setDriverSupport(support) {
2959
+ if (DefinedDrivers[driverName]) {
2960
+ console.info('Redefining LocalForage driver: ' + driverName);
2961
+ }
2962
+ DefinedDrivers[driverName] = driverObject;
2963
+ DriverSupport[driverName] = support;
2964
+ // don't use a then, so that we can define
2965
+ // drivers that have simple _support methods
2966
+ // in a blocking manner
2967
+ resolve();
2968
+ };
2969
+
2970
+ if ('_support' in driverObject) {
2971
+ if (driverObject._support && typeof driverObject._support === 'function') {
2972
+ driverObject._support().then(setDriverSupport, reject);
2973
+ } else {
2974
+ setDriverSupport(!!driverObject._support);
2975
+ }
2976
+ } else {
2977
+ setDriverSupport(true);
2978
+ }
2979
+ } catch (e) {
2980
+ reject(e);
2981
+ }
2982
+ });
2983
+
2984
+ executeTwoCallbacks(promise, callback, errorCallback);
2985
+ return promise;
2986
+ };
2987
+
2988
+ LocalForage.prototype.driver = function driver() {
2989
+ return this._driver || null;
2990
+ };
2991
+
2992
+ LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
2993
+ var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));
2994
+
2995
+ executeTwoCallbacks(getDriverPromise, callback, errorCallback);
2996
+ return getDriverPromise;
2997
+ };
2998
+
2999
+ LocalForage.prototype.getSerializer = function getSerializer(callback) {
3000
+ var serializerPromise = Promise$1.resolve(localforageSerializer);
3001
+ executeTwoCallbacks(serializerPromise, callback);
3002
+ return serializerPromise;
3003
+ };
3004
+
3005
+ LocalForage.prototype.ready = function ready(callback) {
3006
+ var self = this;
3007
+
3008
+ var promise = self._driverSet.then(function () {
3009
+ if (self._ready === null) {
3010
+ self._ready = self._initDriver();
3011
+ }
3012
+
3013
+ return self._ready;
3014
+ });
3015
+
3016
+ executeTwoCallbacks(promise, callback, callback);
3017
+ return promise;
3018
+ };
3019
+
3020
+ LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
3021
+ var self = this;
3022
+
3023
+ if (!isArray(drivers)) {
3024
+ drivers = [drivers];
3025
+ }
3026
+
3027
+ var supportedDrivers = this._getSupportedDrivers(drivers);
3028
+
3029
+ function setDriverToConfig() {
3030
+ self._config.driver = self.driver();
3031
+ }
3032
+
3033
+ function extendSelfWithDriver(driver) {
3034
+ self._extend(driver);
3035
+ setDriverToConfig();
3036
+
3037
+ self._ready = self._initStorage(self._config);
3038
+ return self._ready;
3039
+ }
3040
+
3041
+ function initDriver(supportedDrivers) {
3042
+ return function () {
3043
+ var currentDriverIndex = 0;
3044
+
3045
+ function driverPromiseLoop() {
3046
+ while (currentDriverIndex < supportedDrivers.length) {
3047
+ var driverName = supportedDrivers[currentDriverIndex];
3048
+ currentDriverIndex++;
3049
+
3050
+ self._dbInfo = null;
3051
+ self._ready = null;
3052
+
3053
+ return self.getDriver(driverName).then(extendSelfWithDriver)["catch"](driverPromiseLoop);
3054
+ }
3055
+
3056
+ setDriverToConfig();
3057
+ var error = new Error('No available storage method found.');
3058
+ self._driverSet = Promise$1.reject(error);
3059
+ return self._driverSet;
3060
+ }
3061
+
3062
+ return driverPromiseLoop();
3063
+ };
3064
+ }
3065
+
3066
+ // There might be a driver initialization in progress
3067
+ // so wait for it to finish in order to avoid a possible
3068
+ // race condition to set _dbInfo
3069
+ var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
3070
+ return Promise$1.resolve();
3071
+ }) : Promise$1.resolve();
3072
+
3073
+ this._driverSet = oldDriverSetDone.then(function () {
3074
+ var driverName = supportedDrivers[0];
3075
+ self._dbInfo = null;
3076
+ self._ready = null;
3077
+
3078
+ return self.getDriver(driverName).then(function (driver) {
3079
+ self._driver = driver._driver;
3080
+ setDriverToConfig();
3081
+ self._wrapLibraryMethodsWithReady();
3082
+ self._initDriver = initDriver(supportedDrivers);
3083
+ });
3084
+ })["catch"](function () {
3085
+ setDriverToConfig();
3086
+ var error = new Error('No available storage method found.');
3087
+ self._driverSet = Promise$1.reject(error);
3088
+ return self._driverSet;
3089
+ });
3090
+
3091
+ executeTwoCallbacks(this._driverSet, callback, errorCallback);
3092
+ return this._driverSet;
3093
+ };
3094
+
3095
+ LocalForage.prototype.supports = function supports(driverName) {
3096
+ return !!DriverSupport[driverName];
3097
+ };
3098
+
3099
+ LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
3100
+ extend(this, libraryMethodsAndProperties);
3101
+ };
3102
+
3103
+ LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
3104
+ var supportedDrivers = [];
3105
+ for (var i = 0, len = drivers.length; i < len; i++) {
3106
+ var driverName = drivers[i];
3107
+ if (this.supports(driverName)) {
3108
+ supportedDrivers.push(driverName);
3109
+ }
3110
+ }
3111
+ return supportedDrivers;
3112
+ };
3113
+
3114
+ LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
3115
+ // Add a stub for each driver API method that delays the call to the
3116
+ // corresponding driver method until localForage is ready. These stubs
3117
+ // will be replaced by the driver methods as soon as the driver is
3118
+ // loaded, so there is no performance impact.
3119
+ for (var i = 0, len = LibraryMethods.length; i < len; i++) {
3120
+ callWhenReady(this, LibraryMethods[i]);
3121
+ }
3122
+ };
3123
+
3124
+ LocalForage.prototype.createInstance = function createInstance(options) {
3125
+ return new LocalForage(options);
3126
+ };
3127
+
3128
+ return LocalForage;
3129
+ }();
3130
+
3131
+ // The actual localForage object that we expose as a module or via a
3132
+ // global. It's extended by pulling in one of our other libraries.
3133
+
3134
+
3135
+ var localforage_js = new LocalForage();
3136
+
3137
+ module.exports = localforage_js;
3138
+
3139
+ },{"3":3}]},{},[4])(4)
3140
+ });
3141
+ });
3142
+
3143
+ (function (ObjectUtils) {
319
3144
  /**
320
- * @param id
321
- * @param data
322
- * @param duration in seconds until considered expired.
3145
+ * Generates a Bruce compatible UID.
3146
+ * @returns
323
3147
  */
324
- constructor(id, data, duration) {
325
- this.Id = id;
326
- this.Data = data;
327
- this.Duration = duration;
328
- this._created = duration > -1 ? new Date() : null;
329
- }
330
- IsExpired() {
331
- if (this._created == null) {
332
- return false;
3148
+ function UId() {
3149
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
3150
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
3151
+ return v.toString(16);
3152
+ });
3153
+ }
3154
+ ObjectUtils.UId = UId;
3155
+ })(exports.ObjectUtils || (exports.ObjectUtils = {}));
3156
+
3157
+ class CacheDictionary {
3158
+ constructor(id) {
3159
+ this.memory = Object.create(null);
3160
+ if (!id) {
3161
+ id = "BRUCE_UI_MODELS_CACHE_DICT_" + exports.ObjectUtils.UId();
333
3162
  }
334
- return (new Date().getTime() - this._created.getTime()) / 1000 > this.Duration;
3163
+ this.id = id;
3164
+ this.store = localforage.createInstance({
3165
+ name: id
3166
+ });
3167
+ }
3168
+ get Id() {
3169
+ return this.id;
3170
+ }
3171
+ GetItems() {
3172
+ return __awaiter(this, void 0, void 0, function* () {
3173
+ if (this.items == null) {
3174
+ const raw = yield this.store.getItem(this.id);
3175
+ if (raw == null) {
3176
+ this.items = [];
3177
+ }
3178
+ else {
3179
+ // Check if any are expired.
3180
+ // We can clean this every first time we load.
3181
+ const now = new Date().getTime();
3182
+ for (const item of raw) {
3183
+ if (item.duration > -1 && (now - item.created) / 1000 > item.duration) {
3184
+ if (item.inMemory) {
3185
+ this.memory[item.key] = null;
3186
+ delete this.memory[item.key];
3187
+ }
3188
+ else {
3189
+ yield this.store.removeItem(item.key);
3190
+ }
3191
+ }
3192
+ }
3193
+ this.items = raw;
3194
+ }
3195
+ }
3196
+ return this.items;
3197
+ });
3198
+ }
3199
+ GetKeys() {
3200
+ return __awaiter(this, void 0, void 0, function* () {
3201
+ return (yield this.GetItems()).map(x => "" + x.key);
3202
+ });
3203
+ }
3204
+ Set(key, value, duration) {
3205
+ return __awaiter(this, void 0, void 0, function* () {
3206
+ key = "" + key;
3207
+ const items = yield this.GetItems();
3208
+ const itemIndex = items.findIndex(x => x.key == key);
3209
+ if (itemIndex > -1) {
3210
+ const item = items[itemIndex];
3211
+ if (item.inMemory) {
3212
+ this.memory[item.key] = null;
3213
+ delete this.memory[item.key];
3214
+ }
3215
+ else {
3216
+ yield this.store.removeItem(item.key);
3217
+ }
3218
+ items.splice(itemIndex, 1);
3219
+ }
3220
+ const item = {
3221
+ key: key,
3222
+ duration: duration,
3223
+ created: new Date().getTime(),
3224
+ inMemory: false
3225
+ };
3226
+ // Short duration, keep in memory.
3227
+ if (duration < 60) {
3228
+ item.inMemory = true;
3229
+ this.memory[item.key] = value;
3230
+ }
3231
+ // Let's resolve and store the value in local-storage.
3232
+ // If resolution crashes then we'll keep retaining that in memory.
3233
+ else if (value instanceof Promise) {
3234
+ value.then((x) => __awaiter(this, void 0, void 0, function* () {
3235
+ try {
3236
+ const items = yield this.GetItems();
3237
+ const item = items.find(x => x.key == key);
3238
+ if (!item) {
3239
+ console.log("Item was removed from cache before promise resolved.", key, items);
3240
+ return;
3241
+ }
3242
+ try {
3243
+ yield this.store.setItem(item.key, x);
3244
+ item.inMemory = false;
3245
+ this.memory[item.key] = null;
3246
+ delete this.memory[item.key];
3247
+ yield this.store.setItem(this.id, items);
3248
+ }
3249
+ catch (e) {
3250
+ console.warn(e);
3251
+ }
3252
+ }
3253
+ catch (e) {
3254
+ console.warn(e);
3255
+ }
3256
+ }));
3257
+ item.inMemory = true;
3258
+ this.memory[item.key] = value;
3259
+ }
3260
+ if (!item.inMemory) {
3261
+ try {
3262
+ yield this.store.setItem(item.key, value);
3263
+ }
3264
+ catch (e) {
3265
+ item.inMemory = true;
3266
+ this.memory[item.key] = value;
3267
+ console.warn(e);
3268
+ }
3269
+ }
3270
+ items.push(item);
3271
+ yield this.store.setItem(this.id, items);
3272
+ this.items = items;
3273
+ });
3274
+ }
3275
+ Remove(key) {
3276
+ return __awaiter(this, void 0, void 0, function* () {
3277
+ key = "" + key;
3278
+ const items = yield this.GetItems();
3279
+ const index = items.findIndex(x => x.key == key);
3280
+ if (index >= 0) {
3281
+ const item = items[index];
3282
+ if (item.inMemory) {
3283
+ this.memory[item.key] = null;
3284
+ delete this.memory[item.key];
3285
+ }
3286
+ else {
3287
+ this.store.removeItem(item.key);
3288
+ }
3289
+ items.splice(index, 1);
3290
+ this.store.setItem(this.id, items);
3291
+ }
3292
+ this.items = items;
3293
+ });
3294
+ }
3295
+ Clear() {
3296
+ return __awaiter(this, void 0, void 0, function* () {
3297
+ const items = yield this.GetItems();
3298
+ for (const item of items) {
3299
+ if (item.inMemory) {
3300
+ this.store.removeItem(item.key);
3301
+ }
3302
+ }
3303
+ this.store.setItem(this.id, []);
3304
+ this.items = [];
3305
+ this.memory = Object.create(null);
3306
+ });
3307
+ }
3308
+ GetData(key) {
3309
+ return __awaiter(this, void 0, void 0, function* () {
3310
+ key = "" + key;
3311
+ const item = (yield this.GetItems()).find(x => x.key == key);
3312
+ const isExpired = item == null || item.duration > -1 && (new Date().getTime() - item.created) / 1000 > item.duration;
3313
+ if (isExpired) {
3314
+ this.Remove(key);
3315
+ return null;
3316
+ }
3317
+ if (item.inMemory) {
3318
+ return this.memory[item.key];
3319
+ }
3320
+ const raw = yield this.store.getItem(item.key);
3321
+ if (raw == null) {
3322
+ return null;
3323
+ }
3324
+ return raw;
3325
+ });
335
3326
  }
336
3327
  }
337
- // Milliseconds between each data cleaning.
338
- const CLEANER_INTERVAL = 5000;
339
- // Max number of items to clean in each cleaning.
340
- const MAX_CLEAN_BATCH = 100;
341
- // (Default) Max idle time to keep the cleaner alive.
342
- // Set to default API cache duration by default.
343
- const DEFAULT_MAX_CLEAN_IDLE = 60 * 5;
344
- /**
345
- * Simple local cache controller.
346
- */
347
3328
  class CacheControl {
348
- constructor() {
349
- this.data = {};
3329
+ constructor(id) {
350
3330
  this.Disabled = false;
351
- this.cleanerInterval = null;
352
- // Max idle time to keep the cleaner alive.
353
- // This value is increased when a new item is added with a larger cache duration.
354
- this.maxCleanIdle = DEFAULT_MAX_CLEAN_IDLE;
3331
+ this.data = new CacheDictionary(id);
355
3332
  }
356
3333
  /**
357
3334
  * @param id
@@ -359,121 +3336,64 @@
359
3336
  * @param duration seconds to keep the data in cache. -1 for infinite.
360
3337
  */
361
3338
  Set(id, data, duration = -1) {
362
- this.data[id + ""] = new CacheItem(id + "", data, duration);
363
- if (duration > -1) {
364
- this.startCleaning();
365
- if (this.maxCleanIdle < duration) {
366
- // Add 5 seconds to be sure cleaner stays alive to get it.
367
- this.maxCleanIdle = duration + 5;
368
- }
369
- }
3339
+ return __awaiter(this, void 0, void 0, function* () {
3340
+ return this.data.Set(id, data, duration);
3341
+ });
370
3342
  }
371
3343
  Get(id) {
372
- if (this.Disabled) {
373
- return null;
374
- }
375
- const item = this.data[id + ""];
376
- if (item == null) {
377
- return null;
378
- }
379
- if (item.IsExpired()) {
380
- delete this.data[id + ""];
381
- return null;
382
- }
383
- return item.Data;
3344
+ return __awaiter(this, void 0, void 0, function* () {
3345
+ return this.data.GetData(id);
3346
+ });
384
3347
  }
385
3348
  Clear() {
386
- this.data = {};
387
- this.stopCleaning();
3349
+ return __awaiter(this, void 0, void 0, function* () {
3350
+ return this.data.Clear();
3351
+ });
388
3352
  }
389
3353
  Remove(id) {
390
- delete this.data[id + ""];
391
- if (Object.keys(this.data).length <= 0) {
392
- this.stopCleaning();
393
- }
3354
+ return __awaiter(this, void 0, void 0, function* () {
3355
+ return this.data.Remove(id);
3356
+ });
394
3357
  }
395
3358
  RemoveByStartsWith(text) {
396
- for (const key in this.data) {
397
- if (key.startsWith(text)) {
398
- delete this.data[key];
3359
+ return __awaiter(this, void 0, void 0, function* () {
3360
+ const items = [...(yield this.data.GetItems())];
3361
+ for (const item of items) {
3362
+ if (item.key.startsWith(text)) {
3363
+ yield this.data.Remove(item.key);
3364
+ }
399
3365
  }
400
- }
401
- if (Object.keys(this.data).length <= 0) {
402
- this.stopCleaning();
403
- }
3366
+ });
404
3367
  }
405
3368
  RemoveByContains(text) {
406
- for (const key in this.data) {
407
- if (key.includes(text)) {
408
- delete this.data[key];
3369
+ return __awaiter(this, void 0, void 0, function* () {
3370
+ const items = [...(yield this.data.GetItems())];
3371
+ for (const item of items) {
3372
+ if (item.key.includes(text)) {
3373
+ yield this.data.Remove(item.key);
3374
+ }
409
3375
  }
410
- }
411
- if (Object.keys(this.data).length <= 0) {
412
- this.stopCleaning();
413
- }
3376
+ });
414
3377
  }
415
3378
  GetKeys() {
416
- if (this.Disabled) {
417
- return [];
418
- }
419
- return Object.keys(this.data);
3379
+ return __awaiter(this, void 0, void 0, function* () {
3380
+ if (this.Disabled) {
3381
+ return [];
3382
+ }
3383
+ const items = yield this.data.GetItems();
3384
+ return items.map(x => x.key);
3385
+ });
420
3386
  }
421
3387
  GetValues() {
422
- if (this.Disabled) {
423
- return [];
424
- }
425
- const values = [];
426
- for (const key in this.data) {
427
- const data = this.Get(key);
428
- if (data != null) {
429
- values.push(data);
430
- }
431
- }
432
- return values;
433
- }
434
- startCleaning() {
435
- if (this.cleanerInterval == null) {
436
- let cleanIdleStart = null;
437
- this.cleanerInterval = setInterval(() => {
438
- let cleaned = 0;
439
- for (const key in this.data) {
440
- const item = this.data[key];
441
- if (item.IsExpired()) {
442
- delete this.data[key];
443
- cleaned += 1;
444
- }
445
- if (cleaned >= MAX_CLEAN_BATCH) {
446
- break;
447
- }
448
- }
449
- if (cleaned <= 0) {
450
- // Stop cleaner if nothing in cache.
451
- if (Object.keys(this.data).length <= 0) {
452
- this.stopCleaning();
453
- }
454
- // Stop cleaner if idle time is reached.
455
- else {
456
- if (cleanIdleStart == null) {
457
- cleanIdleStart = new Date().getTime();
458
- }
459
- const now = new Date().getTime();
460
- if (now - cleanIdleStart > this.maxCleanIdle * 1000) {
461
- this.stopCleaning();
462
- }
463
- }
464
- }
465
- else {
466
- cleanIdleStart = null;
467
- }
468
- }, CLEANER_INTERVAL);
469
- }
470
- }
471
- stopCleaning() {
472
- if (this.cleanerInterval != null) {
473
- clearInterval(this.cleanerInterval);
474
- this.cleanerInterval = null;
475
- this.maxCleanIdle = DEFAULT_MAX_CLEAN_IDLE;
476
- }
3388
+ return __awaiter(this, void 0, void 0, function* () {
3389
+ if (this.Disabled) {
3390
+ return [];
3391
+ }
3392
+ const items = yield this.data.GetItems();
3393
+ const keys = items.map(x => x.key);
3394
+ const values = yield Promise.all(keys.map(key => this.data.GetData(key)));
3395
+ return values.filter(x => x != null);
3396
+ });
477
3397
  }
478
3398
  }
479
3399
 
@@ -529,8 +3449,8 @@
529
3449
  constructor(params) {
530
3450
  this.ssid = "";
531
3451
  this.baseUrl = "";
532
- this.Cache = new CacheControl();
533
3452
  this.ssidHeader = params === null || params === void 0 ? void 0 : params.ssidHeader;
3453
+ this.Cache = new CacheControl(params === null || params === void 0 ? void 0 : params.cacheId);
534
3454
  }
535
3455
  GetBaseUrl() {
536
3456
  return this.baseUrl;
@@ -542,28 +3462,32 @@
542
3462
  }
543
3463
  }
544
3464
  GetCacheItem(key, reqParams) {
545
- let noCache = reqParams === null || reqParams === void 0 ? void 0 : reqParams.noCache;
546
- if (noCache == null) {
547
- noCache = exports.Api.DEFAULT_NO_CACHE;
548
- }
549
- if (noCache) {
550
- return null;
551
- }
552
- return this.Cache.Get(key);
3465
+ return __awaiter(this, void 0, void 0, function* () {
3466
+ let noCache = reqParams === null || reqParams === void 0 ? void 0 : reqParams.noCache;
3467
+ if (noCache == null) {
3468
+ noCache = exports.Api.DEFAULT_NO_CACHE;
3469
+ }
3470
+ if (noCache) {
3471
+ return null;
3472
+ }
3473
+ return this.Cache.Get(key);
3474
+ });
553
3475
  }
554
3476
  SetCacheItem(params) {
555
- let { key, value, duration, req } = params;
556
- let noCache = req === null || req === void 0 ? void 0 : req.noCache;
557
- if (noCache == null) {
558
- noCache = exports.Api.DEFAULT_NO_CACHE;
559
- }
560
- if (noCache) {
561
- return;
562
- }
563
- if (isNaN(duration)) {
564
- duration = exports.Api.DEFAULT_CACHE_DURATION;
565
- }
566
- this.Cache.Set(key, value, duration);
3477
+ return __awaiter(this, void 0, void 0, function* () {
3478
+ let { key, value, duration, req } = params;
3479
+ let noCache = req === null || req === void 0 ? void 0 : req.noCache;
3480
+ if (noCache == null) {
3481
+ noCache = exports.Api.DEFAULT_NO_CACHE;
3482
+ }
3483
+ if (noCache) {
3484
+ return;
3485
+ }
3486
+ if (isNaN(duration)) {
3487
+ duration = exports.Api.DEFAULT_CACHE_DURATION;
3488
+ }
3489
+ yield this.Cache.Set(key, value, duration);
3490
+ });
567
3491
  }
568
3492
  GetSessionId() {
569
3493
  return this.ssid;
@@ -760,7 +3684,7 @@
760
3684
  function Get(params) {
761
3685
  return __awaiter(this, void 0, void 0, function* () {
762
3686
  const { api, accountId: id, req: reqParams } = params;
763
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
3687
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
764
3688
  if (cacheData) {
765
3689
  return cacheData;
766
3690
  }
@@ -768,7 +3692,7 @@
768
3692
  const resData = {
769
3693
  account: req
770
3694
  };
771
- api.SetCacheItem({
3695
+ yield api.SetCacheItem({
772
3696
  key: GetCacheKey(id),
773
3697
  value: resData,
774
3698
  req: reqParams
@@ -780,7 +3704,7 @@
780
3704
  function GetRelatedList(params) {
781
3705
  return __awaiter(this, void 0, void 0, function* () {
782
3706
  const { api, req: reqParams } = params;
783
- const cacheData = api.GetCacheItem(GetListCacheKey(api.GetSessionId()), reqParams);
3707
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(api.GetSessionId()), reqParams);
784
3708
  if (cacheData) {
785
3709
  return cacheData;
786
3710
  }
@@ -797,7 +3721,7 @@
797
3721
  rej(e);
798
3722
  }
799
3723
  }));
800
- api.SetCacheItem({
3724
+ yield api.SetCacheItem({
801
3725
  key: GetListCacheKey(api.GetSessionId()),
802
3726
  value: prom,
803
3727
  req: reqParams
@@ -809,7 +3733,7 @@
809
3733
  function GetAppSettings(params) {
810
3734
  return __awaiter(this, void 0, void 0, function* () {
811
3735
  const { api, accountId: id, appId, req: reqParams } = params;
812
- const cacheData = api.GetCacheItem(GetCacheKey(id, appId), reqParams);
3736
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id, appId), reqParams);
813
3737
  if (cacheData) {
814
3738
  return cacheData;
815
3739
  }
@@ -827,7 +3751,7 @@
827
3751
  rej(e);
828
3752
  }
829
3753
  }));
830
- api.SetCacheItem({
3754
+ yield api.SetCacheItem({
831
3755
  key: GetCacheKey(id, appId),
832
3756
  value: prom,
833
3757
  req: reqParams
@@ -845,7 +3769,7 @@
845
3769
  return __awaiter(this, void 0, void 0, function* () {
846
3770
  const { api, accountId: id, appId, settings: data, req: reqParams } = params;
847
3771
  const res = yield api.POST(`account/${id}/applicationSettings/${appId}`, data, reqParams);
848
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Account + exports.Api.ECacheKey.Id + id);
3772
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Account + exports.Api.ECacheKey.Id + id);
849
3773
  return {
850
3774
  settings: res
851
3775
  };
@@ -883,7 +3807,7 @@
883
3807
  function GetDbRegions(params) {
884
3808
  return __awaiter(this, void 0, void 0, function* () {
885
3809
  const { api, req: reqParams, key } = params;
886
- const cacheData = api.GetCacheItem(GetDbRegionListCacheKey(), reqParams);
3810
+ const cacheData = yield api.GetCacheItem(GetDbRegionListCacheKey(), reqParams);
887
3811
  if (cacheData) {
888
3812
  return cacheData;
889
3813
  }
@@ -896,7 +3820,7 @@
896
3820
  rej(e);
897
3821
  }
898
3822
  }));
899
- api.SetCacheItem({
3823
+ yield api.SetCacheItem({
900
3824
  key: GetDbRegionListCacheKey(),
901
3825
  value: prom,
902
3826
  req: reqParams
@@ -949,7 +3873,8 @@
949
3873
  class Api$$1 extends AbstractApi {
950
3874
  constructor(params) {
951
3875
  super({
952
- ssidHeader: "x-sessionid"
3876
+ ssidHeader: "x-sessionid",
3877
+ cacheId: `CAM_API_${params === null || params === void 0 ? void 0 : params.env}_`
953
3878
  });
954
3879
  this.env = (params === null || params === void 0 ? void 0 : params.env) ? params.env : exports.Api.EEnv.PROD;
955
3880
  this.setBaseUrl();
@@ -1161,7 +4086,8 @@
1161
4086
  */
1162
4087
  constructor(params) {
1163
4088
  super({
1164
- ssidHeader: "x-sessionid"
4089
+ ssidHeader: "x-sessionid",
4090
+ cacheId: `BRUCE_API_${params === null || params === void 0 ? void 0 : params.env}_${params === null || params === void 0 ? void 0 : params.accountId}_`
1165
4091
  });
1166
4092
  this.loadCancelled = false;
1167
4093
  let { accountId, env, cam, loadRegionalBaseUrl, loadConfig } = params;
@@ -1367,7 +4293,8 @@
1367
4293
  class Api$$1 extends AbstractApi {
1368
4294
  constructor(params) {
1369
4295
  super({
1370
- ssidHeader: "SSID"
4296
+ ssidHeader: "SSID",
4297
+ cacheId: `IDM_API_${params === null || params === void 0 ? void 0 : params.env}_`
1371
4298
  });
1372
4299
  this.env = (params === null || params === void 0 ? void 0 : params.env) ? params.env : exports.Api.EEnv.PROD;
1373
4300
  this.setBaseUrl();
@@ -1438,7 +4365,8 @@
1438
4365
  class Api$$1 extends AbstractApi {
1439
4366
  constructor(params) {
1440
4367
  super({
1441
- ssidHeader: "x-sessionid"
4368
+ ssidHeader: "x-sessionid",
4369
+ cacheId: `GLOBAL_API_${params === null || params === void 0 ? void 0 : params.env}_`
1442
4370
  });
1443
4371
  this.env = (params === null || params === void 0 ? void 0 : params.env) ? params.env : exports.Api.EEnv.PROD;
1444
4372
  this.setBaseUrl();
@@ -1706,20 +4634,6 @@
1706
4634
  Color.ColorFromStr = ColorFromStr;
1707
4635
  })(exports.Color || (exports.Color = {}));
1708
4636
 
1709
- (function (ObjectUtils) {
1710
- /**
1711
- * Generates a Bruce compatible UID.
1712
- * @returns
1713
- */
1714
- function UId() {
1715
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
1716
- const r = Math.random() * 16 | 0, v = c == "x" ? r : (r & 0x3 | 0x8);
1717
- return v.toString(16);
1718
- });
1719
- }
1720
- ObjectUtils.UId = UId;
1721
- })(exports.ObjectUtils || (exports.ObjectUtils = {}));
1722
-
1723
4637
  /**
1724
4638
  * Utility to help with parsing and wrapping Bruce paths.
1725
4639
  */
@@ -1790,7 +4704,7 @@
1790
4704
  throw ("Entity ID is required.");
1791
4705
  }
1792
4706
  const key = GetCacheKey(entityId, expandLocation);
1793
- const cacheData = api.GetCacheItem(key, reqParams);
4707
+ const cacheData = yield api.GetCacheItem(key, reqParams);
1794
4708
  if (cacheData) {
1795
4709
  return cacheData;
1796
4710
  }
@@ -1805,7 +4719,7 @@
1805
4719
  rej(e);
1806
4720
  }
1807
4721
  }));
1808
- api.SetCacheItem({
4722
+ yield api.SetCacheItem({
1809
4723
  key,
1810
4724
  value: prom,
1811
4725
  req: reqParams
@@ -1825,7 +4739,7 @@
1825
4739
  for (let i = 0; i < entityIds.length; i++) {
1826
4740
  const entityId = entityIds[i];
1827
4741
  const key = GetCacheKey(entityId);
1828
- const cacheData = api.GetCacheItem(key, reqParams);
4742
+ const cacheData = yield api.GetCacheItem(key, reqParams);
1829
4743
  if (cacheData) {
1830
4744
  reqs.push(cacheData);
1831
4745
  }
@@ -1859,7 +4773,7 @@
1859
4773
  }
1860
4774
  res(null);
1861
4775
  }));
1862
- api.SetCacheItem({
4776
+ yield api.SetCacheItem({
1863
4777
  key,
1864
4778
  value: prom,
1865
4779
  req: reqParams
@@ -2072,7 +4986,7 @@
2072
4986
  for (let i = 0; i < entities.length; i++) {
2073
4987
  const entity = entities[i];
2074
4988
  const id = entity.Bruce.ID;
2075
- api.SetCacheItem({
4989
+ yield api.SetCacheItem({
2076
4990
  key: GetCacheKey(id),
2077
4991
  value: {
2078
4992
  entity: entity
@@ -2959,6 +5873,28 @@
2959
5873
  UTC.FromDate = FromDate;
2960
5874
  })(exports.UTC || (exports.UTC = {}));
2961
5875
 
5876
+ class LRUCache {
5877
+ constructor(capacity) {
5878
+ this.capacity = capacity;
5879
+ this.cache = new Map();
5880
+ }
5881
+ Get(key) {
5882
+ const value = this.cache.get(key);
5883
+ if (value) {
5884
+ this.cache.delete(key);
5885
+ this.cache.set(key, value);
5886
+ }
5887
+ return value;
5888
+ }
5889
+ Set(key, value) {
5890
+ if (this.cache.size >= this.capacity) {
5891
+ const leastRecentlyUsedKey = this.cache.keys().next().value;
5892
+ this.cache.delete(leastRecentlyUsedKey);
5893
+ }
5894
+ this.cache.set(key, value);
5895
+ }
5896
+ }
5897
+
2962
5898
  (function (EntityAttachmentType) {
2963
5899
  function GetCacheKey(id) {
2964
5900
  return exports.Api.ECacheKey.AttachmentType + exports.Api.ECacheKey.Id + id;
@@ -3003,7 +5939,7 @@
3003
5939
  function GetList(params) {
3004
5940
  return __awaiter(this, void 0, void 0, function* () {
3005
5941
  const { api, reqParams } = params;
3006
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
5942
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
3007
5943
  if (cacheData) {
3008
5944
  return cacheData;
3009
5945
  }
@@ -3018,7 +5954,7 @@
3018
5954
  rej(e);
3019
5955
  }
3020
5956
  }));
3021
- api.SetCacheItem({
5957
+ yield api.SetCacheItem({
3022
5958
  key: GetListCacheKey(),
3023
5959
  value: req,
3024
5960
  req: reqParams
@@ -3075,7 +6011,7 @@
3075
6011
  for (let i = 0; i < attachments.length; i++) {
3076
6012
  api.Cache.Remove(GetCacheKey(attachments[i].ID));
3077
6013
  }
3078
- api.Cache.RemoveByStartsWith(GetListCacheKey(entityId));
6014
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey(entityId));
3079
6015
  });
3080
6016
  }
3081
6017
  EntityAttachment.UpdateOrder = UpdateOrder;
@@ -3096,7 +6032,7 @@
3096
6032
  if (!entityId) {
3097
6033
  throw ("Entity ID is required.");
3098
6034
  }
3099
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId), reqParams);
6035
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId), reqParams);
3100
6036
  if (cacheData) {
3101
6037
  return cacheData;
3102
6038
  }
@@ -3111,7 +6047,7 @@
3111
6047
  rej(e);
3112
6048
  }
3113
6049
  }));
3114
- api.SetCacheItem({
6050
+ yield api.SetCacheItem({
3115
6051
  key: GetListCacheKey(entityId),
3116
6052
  value: req,
3117
6053
  req: reqParams
@@ -3155,7 +6091,7 @@
3155
6091
  const url = `entity/${data["TargetObject.ID"]}/comment` + (data.ID == null ? "" : "/" + data.ID);
3156
6092
  const res = yield api.POST(url, data, exports.Api.PrepReqParams(reqParams));
3157
6093
  api.Cache.Remove(GetCacheKey(data.ID));
3158
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Comment + exports.Api.ECacheKey.Entity);
6094
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Comment + exports.Api.ECacheKey.Entity);
3159
6095
  return {
3160
6096
  comment: res
3161
6097
  };
@@ -3170,7 +6106,7 @@
3170
6106
  }
3171
6107
  yield api.DELETE(`entity/${entityId}/comment/${commentId}`, exports.Api.PrepReqParams(reqParams));
3172
6108
  api.Cache.Remove(GetCacheKey(commentId));
3173
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Comment + exports.Api.ECacheKey.Entity);
6109
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Comment + exports.Api.ECacheKey.Entity);
3174
6110
  });
3175
6111
  }
3176
6112
  EntityComment.Delete = Delete;
@@ -3180,7 +6116,7 @@
3180
6116
  if (!entityId) {
3181
6117
  throw ("Entity ID is required.");
3182
6118
  }
3183
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId), reqParams);
6119
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId), reqParams);
3184
6120
  if (cacheData) {
3185
6121
  return cacheData;
3186
6122
  }
@@ -3195,7 +6131,7 @@
3195
6131
  rej(e);
3196
6132
  }
3197
6133
  }));
3198
- api.SetCacheItem({
6134
+ yield api.SetCacheItem({
3199
6135
  key: GetListCacheKey(entityId),
3200
6136
  value: req,
3201
6137
  req: reqParams
@@ -3224,7 +6160,7 @@
3224
6160
  const url = `entity/${data["Entity.ID"]}/link` + (data.ID == null ? "" : "/" + data.ID);
3225
6161
  const res = yield api.POST(url, data, exports.Api.PrepReqParams(reqParams));
3226
6162
  api.Cache.Remove(GetCacheKey(data.ID));
3227
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Link + exports.Api.ECacheKey.Entity);
6163
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Link + exports.Api.ECacheKey.Entity);
3228
6164
  return {
3229
6165
  link: res
3230
6166
  };
@@ -3239,7 +6175,7 @@
3239
6175
  }
3240
6176
  yield api.DELETE(`entity/${entityId}/link/${linkId}`, exports.Api.PrepReqParams(reqParams));
3241
6177
  api.Cache.Remove(GetCacheKey(linkId));
3242
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Link + exports.Api.ECacheKey.Entity);
6178
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Link + exports.Api.ECacheKey.Entity);
3243
6179
  });
3244
6180
  }
3245
6181
  EntityLink.Delete = Delete;
@@ -3249,7 +6185,7 @@
3249
6185
  if (!entityId) {
3250
6186
  throw ("Entity ID is required.");
3251
6187
  }
3252
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId), reqParams);
6188
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId), reqParams);
3253
6189
  if (cacheData) {
3254
6190
  return cacheData;
3255
6191
  }
@@ -3264,7 +6200,7 @@
3264
6200
  rej(e);
3265
6201
  }
3266
6202
  }));
3267
- api.SetCacheItem({
6203
+ yield api.SetCacheItem({
3268
6204
  key: GetListCacheKey(entityId),
3269
6205
  value: req,
3270
6206
  req: reqParams
@@ -3314,7 +6250,7 @@
3314
6250
  if (!url) {
3315
6251
  throw ("Url is required.");
3316
6252
  }
3317
- const cacheData = api.GetCacheItem(GetCacheKey(url), reqParams);
6253
+ const cacheData = yield api.GetCacheItem(GetCacheKey(url), reqParams);
3318
6254
  if (cacheData) {
3319
6255
  return cacheData;
3320
6256
  }
@@ -3329,7 +6265,7 @@
3329
6265
  rej(e);
3330
6266
  }
3331
6267
  }));
3332
- api.SetCacheItem({
6268
+ yield api.SetCacheItem({
3333
6269
  key: GetCacheKey(url),
3334
6270
  value: req,
3335
6271
  req: reqParams
@@ -3358,7 +6294,7 @@
3358
6294
  if (!entityId) {
3359
6295
  throw ("Entity id is required.");
3360
6296
  }
3361
- const cacheData = api.GetCacheItem(GetEntityListKey(entityId), reqParams);
6297
+ const cacheData = yield api.GetCacheItem(GetEntityListKey(entityId), reqParams);
3362
6298
  if (cacheData) {
3363
6299
  return cacheData;
3364
6300
  }
@@ -3374,7 +6310,7 @@
3374
6310
  rej(e);
3375
6311
  }
3376
6312
  }));
3377
- api.SetCacheItem({
6313
+ yield api.SetCacheItem({
3378
6314
  key: GetEntityListKey(entityId),
3379
6315
  value: prom,
3380
6316
  req: reqParams
@@ -3393,7 +6329,7 @@
3393
6329
  if (!group) {
3394
6330
  group = "DEFAULT";
3395
6331
  }
3396
- const cacheData = api.GetCacheItem(GetTypeListKey(typeId, group), reqParams);
6332
+ const cacheData = yield api.GetCacheItem(GetTypeListKey(typeId, group), reqParams);
3397
6333
  if (cacheData) {
3398
6334
  return cacheData;
3399
6335
  }
@@ -3410,7 +6346,7 @@
3410
6346
  rej(e);
3411
6347
  }
3412
6348
  }));
3413
- api.SetCacheItem({
6349
+ yield api.SetCacheItem({
3414
6350
  key: GetTypeListKey(typeId, group),
3415
6351
  value: prom,
3416
6352
  req: reqParams
@@ -3465,7 +6401,7 @@
3465
6401
  function GetList(params) {
3466
6402
  return __awaiter(this, void 0, void 0, function* () {
3467
6403
  const { api, req: reqParams } = params;
3468
- const cacheKey = api.GetCacheItem(GetListCacheKey(), reqParams);
6404
+ const cacheKey = yield api.GetCacheItem(GetListCacheKey(), reqParams);
3469
6405
  if (cacheKey) {
3470
6406
  return cacheKey;
3471
6407
  }
@@ -3480,7 +6416,7 @@
3480
6416
  rej(e);
3481
6417
  }
3482
6418
  }));
3483
- api.SetCacheItem({
6419
+ yield api.SetCacheItem({
3484
6420
  key: GetListCacheKey(),
3485
6421
  value: req,
3486
6422
  req: reqParams
@@ -3495,7 +6431,7 @@
3495
6431
  if (!id) {
3496
6432
  throw ("Lod category id is required.");
3497
6433
  }
3498
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
6434
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
3499
6435
  if (cacheData) {
3500
6436
  return cacheData;
3501
6437
  }
@@ -3510,7 +6446,7 @@
3510
6446
  rej(e);
3511
6447
  }
3512
6448
  }));
3513
- api.SetCacheItem({
6449
+ yield api.SetCacheItem({
3514
6450
  key: GetCacheKey(id),
3515
6451
  value: req,
3516
6452
  req: reqParams
@@ -3564,7 +6500,7 @@
3564
6500
  throw ("Type ID is required.");
3565
6501
  }
3566
6502
  const key = GetCacheKey(typeId);
3567
- const cacheData = api.GetCacheItem(key, reqParams);
6503
+ const cacheData = yield api.GetCacheItem(key, reqParams);
3568
6504
  if (cacheData) {
3569
6505
  return cacheData;
3570
6506
  }
@@ -3579,7 +6515,7 @@
3579
6515
  rej(e);
3580
6516
  }
3581
6517
  }));
3582
- api.SetCacheItem({
6518
+ yield api.SetCacheItem({
3583
6519
  key,
3584
6520
  value: prom,
3585
6521
  req: reqParams
@@ -3603,7 +6539,7 @@
3603
6539
  function GetList(params) {
3604
6540
  return __awaiter(this, void 0, void 0, function* () {
3605
6541
  const { api, req: reqParams } = params;
3606
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
6542
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
3607
6543
  if (cacheData) {
3608
6544
  return cacheData;
3609
6545
  }
@@ -3618,7 +6554,7 @@
3618
6554
  rej(e);
3619
6555
  }
3620
6556
  }));
3621
- api.SetCacheItem({
6557
+ yield api.SetCacheItem({
3622
6558
  key: GetListCacheKey(),
3623
6559
  value: req,
3624
6560
  req: reqParams
@@ -3675,11 +6611,11 @@
3675
6611
  };
3676
6612
  const url = `entity/${data["Principal.Entity.ID"]}/relation/${data["Relation.Type.ID"]}/add`;
3677
6613
  yield api.POST(url, reqData, exports.Api.PrepReqParams(reqParams));
3678
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Principal.Entity.ID"]);
3679
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Related.Entity.ID"]);
3680
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.RelationType + exports.Api.ECacheKey.Id + data["Relation.Type.ID"]);
6614
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Principal.Entity.ID"]);
6615
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Related.Entity.ID"]);
6616
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.RelationType + exports.Api.ECacheKey.Id + data["Relation.Type.ID"]);
3681
6617
  if (data["Data.Entity.ID"]) {
3682
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Entity + exports.Api.ECacheKey.Id + data["Data.Entity.ID"]);
6618
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Entity + exports.Api.ECacheKey.Id + data["Data.Entity.ID"]);
3683
6619
  }
3684
6620
  });
3685
6621
  }
@@ -3695,9 +6631,9 @@
3695
6631
  "Related.Entity.ID": [relatedEntityId]
3696
6632
  }, exports.Api.PrepReqParams(reqParams));
3697
6633
  // Remove related cache entries
3698
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + principalEntityId);
3699
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + relatedEntityId);
3700
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.RelationType + exports.Api.ECacheKey.Id + relationTypeId);
6634
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + principalEntityId);
6635
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + relatedEntityId);
6636
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.RelationType + exports.Api.ECacheKey.Id + relationTypeId);
3701
6637
  });
3702
6638
  }
3703
6639
  EntityRelation.Delete = Delete;
@@ -3709,11 +6645,11 @@
3709
6645
  }
3710
6646
  const url = `entity/${data["Principal.Entity.ID"]}/otherEntityID/${data["Related.Entity.ID"]}/relation/${data["Relation.Type.ID"]}/update`;
3711
6647
  const res = yield api.POST(url, data, exports.Api.PrepReqParams(reqParams));
3712
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Principal.Entity.ID"]);
3713
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Related.Entity.ID"]);
3714
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.RelationType + exports.Api.ECacheKey.Id + data["Relation.Type.ID"]);
6648
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Principal.Entity.ID"]);
6649
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Id + data["Related.Entity.ID"]);
6650
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.RelationType + exports.Api.ECacheKey.Id + data["Relation.Type.ID"]);
3715
6651
  if (data["Data.Entity.ID"]) {
3716
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Entity + exports.Api.ECacheKey.Id + data["Data.Entity.ID"]);
6652
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Relation + exports.Api.ECacheKey.Entity + exports.Api.ECacheKey.Id + data["Data.Entity.ID"]);
3717
6653
  }
3718
6654
  });
3719
6655
  }
@@ -3725,7 +6661,7 @@
3725
6661
  throw ("Entity ID is required.");
3726
6662
  }
3727
6663
  filter = Object.assign({ relationTypeId: "", oneWayOnly: false, loadEntityData: false }, filter);
3728
- const cacheData = api.GetCacheItem(GetListCacheKey(entityId, filter), reqParams);
6664
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityId, filter), reqParams);
3729
6665
  if (cacheData) {
3730
6666
  return cacheData;
3731
6667
  }
@@ -3745,7 +6681,7 @@
3745
6681
  rej(e);
3746
6682
  }
3747
6683
  }));
3748
- api.SetCacheItem({
6684
+ yield api.SetCacheItem({
3749
6685
  key: GetListCacheKey(entityId, filter),
3750
6686
  value: req,
3751
6687
  req: reqParams
@@ -3760,7 +6696,7 @@
3760
6696
  if (!entityId) {
3761
6697
  throw ("Entity ID is required.");
3762
6698
  }
3763
- const cacheData = api.GetCacheItem(GetEntityCacheKey(entityId), reqParams);
6699
+ const cacheData = yield api.GetCacheItem(GetEntityCacheKey(entityId), reqParams);
3764
6700
  if (cacheData) {
3765
6701
  return cacheData;
3766
6702
  }
@@ -3775,7 +6711,7 @@
3775
6711
  rej(e);
3776
6712
  }
3777
6713
  }));
3778
- api.SetCacheItem({
6714
+ yield api.SetCacheItem({
3779
6715
  key: GetEntityCacheKey(entityId),
3780
6716
  value: prom,
3781
6717
  req: reqParams
@@ -3820,7 +6756,7 @@
3820
6756
  const reqs = [];
3821
6757
  for (let i = 0; i < sourceKeys.length; i++) {
3822
6758
  const sourceKey = sourceKeys[i];
3823
- const cacheData = api.GetCacheItem(GetCacheKey(sourceId, sourceKey), reqParams);
6759
+ const cacheData = yield api.GetCacheItem(GetCacheKey(sourceId, sourceKey), reqParams);
3824
6760
  if (cacheData) {
3825
6761
  reqs.push(cacheData);
3826
6762
  }
@@ -3895,7 +6831,7 @@
3895
6831
  }
3896
6832
  const res = yield params.api.POST("entitysource", source);
3897
6833
  const cacheKey = GetCacheKey(source["Source.ID"], source["SourceRecord.Key"]);
3898
- params.api.Cache.Remove(cacheKey);
6834
+ yield params.api.Cache.Remove(cacheKey);
3899
6835
  return {
3900
6836
  source: res
3901
6837
  };
@@ -3943,7 +6879,7 @@
3943
6879
  const reqs = [];
3944
6880
  for (let i = 0; i < tagIds.length; i++) {
3945
6881
  const tagId = tagIds[i];
3946
- const cacheData = api.GetCacheItem(GetCacheKey(tagId), reqParams);
6882
+ const cacheData = yield api.GetCacheItem(GetCacheKey(tagId), reqParams);
3947
6883
  if (cacheData) {
3948
6884
  reqs.push(cacheData);
3949
6885
  }
@@ -3975,7 +6911,7 @@
3975
6911
  rej(e);
3976
6912
  }
3977
6913
  }));
3978
- api.SetCacheItem({
6914
+ yield api.SetCacheItem({
3979
6915
  key: GetCacheKey(id),
3980
6916
  value: req,
3981
6917
  req: reqParams
@@ -3992,7 +6928,7 @@
3992
6928
  function GetList(params) {
3993
6929
  return __awaiter(this, void 0, void 0, function* () {
3994
6930
  const { api, entityTypeId, req: reqParams } = params;
3995
- const cacheData = api.GetCacheItem(GetListCacheKey(entityTypeId), reqParams);
6931
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(entityTypeId), reqParams);
3996
6932
  if (cacheData) {
3997
6933
  return cacheData;
3998
6934
  }
@@ -4007,7 +6943,7 @@
4007
6943
  rej(e);
4008
6944
  }
4009
6945
  }));
4010
- api.SetCacheItem({
6946
+ yield api.SetCacheItem({
4011
6947
  key: GetListCacheKey(entityTypeId),
4012
6948
  value: req,
4013
6949
  req: reqParams
@@ -4024,7 +6960,7 @@
4024
6960
  }
4025
6961
  yield api.DELETE(`layer/${tagId}`, exports.Api.PrepReqParams(reqParams));
4026
6962
  api.Cache.Remove(GetCacheKey(tagId));
4027
- api.Cache.RemoveByStartsWith(GetListCacheKey());
6963
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey());
4028
6964
  });
4029
6965
  }
4030
6966
  EntityTag.Delete = Delete;
@@ -4034,7 +6970,7 @@
4034
6970
  const url = data.ID ? `layer/${data.ID}` : "layer";
4035
6971
  const res = yield api.POST(url, data, exports.Api.PrepReqParams(reqParams));
4036
6972
  api.Cache.Remove(GetCacheKey(data.ID));
4037
- api.Cache.RemoveByStartsWith(GetListCacheKey());
6973
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey());
4038
6974
  return {
4039
6975
  tag: res
4040
6976
  };
@@ -4059,7 +6995,7 @@
4059
6995
  throw ("Type ID is required.");
4060
6996
  }
4061
6997
  const key = GetCacheKey(typeId);
4062
- const cacheData = api.GetCacheItem(key, reqParams);
6998
+ const cacheData = yield api.GetCacheItem(key, reqParams);
4063
6999
  if (cacheData) {
4064
7000
  return cacheData;
4065
7001
  }
@@ -4074,7 +7010,7 @@
4074
7010
  rej(e);
4075
7011
  }
4076
7012
  }));
4077
- api.SetCacheItem({
7013
+ yield api.SetCacheItem({
4078
7014
  key,
4079
7015
  value: prom,
4080
7016
  req: reqParams
@@ -4098,7 +7034,7 @@
4098
7034
  function GetList(params) {
4099
7035
  return __awaiter(this, void 0, void 0, function* () {
4100
7036
  const { api, req: reqParams } = params;
4101
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
7037
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
4102
7038
  if (cacheData) {
4103
7039
  return cacheData;
4104
7040
  }
@@ -4113,10 +7049,11 @@
4113
7049
  rej(e);
4114
7050
  }
4115
7051
  }));
4116
- api.SetCacheItem({
7052
+ yield api.SetCacheItem({
4117
7053
  key: GetListCacheKey(),
4118
7054
  value: req,
4119
- req: reqParams
7055
+ req: reqParams,
7056
+ duration: 60 * 5 // 5 minutes.
4120
7057
  });
4121
7058
  return req;
4122
7059
  });
@@ -4551,10 +7488,7 @@
4551
7488
  sortOrder: exports.Api.ESortOrder.Asc,
4552
7489
  entityTypeConditions: this.attrFilter
4553
7490
  },
4554
- viaCdn: this.viaCdn,
4555
- req: {
4556
- noCache: true
4557
- }
7491
+ viaCdn: this.viaCdn
4558
7492
  });
4559
7493
  const integrity = this.getIntegrityId();
4560
7494
  if (loopIntegrity == integrity && entities) {
@@ -4735,7 +7669,7 @@
4735
7669
  function GetEntityCoords(params) {
4736
7670
  return __awaiter(this, void 0, void 0, function* () {
4737
7671
  const { api, rootEntityId: entityId, req: reqParams } = params;
4738
- const cacheData = api.GetCacheItem(GetCacheKey(entityId), reqParams);
7672
+ const cacheData = yield api.GetCacheItem(GetCacheKey(entityId), reqParams);
4739
7673
  if (cacheData) {
4740
7674
  return cacheData;
4741
7675
  }
@@ -4750,7 +7684,7 @@
4750
7684
  rej(e);
4751
7685
  }
4752
7686
  }));
4753
- api.SetCacheItem({
7687
+ yield api.SetCacheItem({
4754
7688
  key: GetCacheKey(entityId),
4755
7689
  value: prom,
4756
7690
  req: reqParams
@@ -4985,7 +7919,7 @@
4985
7919
  throw ("File ID is required.");
4986
7920
  }
4987
7921
  const key = GetCacheKey(fileId);
4988
- const cacheData = api.GetCacheItem(key, reqParams);
7922
+ const cacheData = yield api.GetCacheItem(key, reqParams);
4989
7923
  if (cacheData) {
4990
7924
  return cacheData;
4991
7925
  }
@@ -5000,7 +7934,7 @@
5000
7934
  rej(e);
5001
7935
  }
5002
7936
  }));
5003
- api.SetCacheItem({
7937
+ yield api.SetCacheItem({
5004
7938
  key,
5005
7939
  value: prom,
5006
7940
  req: reqParams
@@ -5216,7 +8150,7 @@
5216
8150
  throw ("Program ID is required.");
5217
8151
  }
5218
8152
  const key = GetCacheKey(programId);
5219
- const cacheData = api.GetCacheItem(key, reqParams);
8153
+ const cacheData = yield api.GetCacheItem(key, reqParams);
5220
8154
  if (cacheData) {
5221
8155
  return cacheData;
5222
8156
  }
@@ -5231,7 +8165,7 @@
5231
8165
  rej(e);
5232
8166
  }
5233
8167
  }));
5234
- api.SetCacheItem({
8168
+ yield api.SetCacheItem({
5235
8169
  key,
5236
8170
  value: prom,
5237
8171
  req: reqParams
@@ -5243,7 +8177,7 @@
5243
8177
  function GetList(params) {
5244
8178
  return __awaiter(this, void 0, void 0, function* () {
5245
8179
  const { api, req: reqParams } = params;
5246
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
8180
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
5247
8181
  if (cacheData) {
5248
8182
  return cacheData;
5249
8183
  }
@@ -5258,7 +8192,7 @@
5258
8192
  rej(e);
5259
8193
  }
5260
8194
  }));
5261
- api.SetCacheItem({
8195
+ yield api.SetCacheItem({
5262
8196
  key: GetListCacheKey(),
5263
8197
  value: req,
5264
8198
  req: reqParams
@@ -5346,7 +8280,7 @@
5346
8280
  if (!tilesetId) {
5347
8281
  throw ("Tileset ID is required.");
5348
8282
  }
5349
- const cacheData = api.GetCacheItem(GetCacheKey(tilesetId, loadFiles), reqParams);
8283
+ const cacheData = yield api.GetCacheItem(GetCacheKey(tilesetId, loadFiles), reqParams);
5350
8284
  if (cacheData) {
5351
8285
  return cacheData;
5352
8286
  }
@@ -5361,7 +8295,7 @@
5361
8295
  rej(e);
5362
8296
  }
5363
8297
  }));
5364
- api.SetCacheItem({
8298
+ yield api.SetCacheItem({
5365
8299
  key: GetCacheKey(tilesetId, loadFiles),
5366
8300
  value: prom,
5367
8301
  req: reqParams
@@ -5404,7 +8338,7 @@
5404
8338
  function GetList(params) {
5405
8339
  return __awaiter(this, void 0, void 0, function* () {
5406
8340
  const { api, req: reqParams } = params;
5407
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
8341
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
5408
8342
  if (cacheData) {
5409
8343
  return cacheData;
5410
8344
  }
@@ -5419,7 +8353,7 @@
5419
8353
  rej(e);
5420
8354
  }
5421
8355
  }));
5422
- api.SetCacheItem({
8356
+ yield api.SetCacheItem({
5423
8357
  key: GetListCacheKey(),
5424
8358
  value: req,
5425
8359
  req: reqParams
@@ -5435,8 +8369,8 @@
5435
8369
  throw ("Tileset ID is required.");
5436
8370
  }
5437
8371
  yield api.DELETE(`tileset/delete/${tilesetId}`, reqParams);
5438
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset + exports.Api.ECacheKey.Id + tilesetId);
5439
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset);
8372
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset + exports.Api.ECacheKey.Id + tilesetId);
8373
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset);
5440
8374
  });
5441
8375
  }
5442
8376
  Tileset.Delete = Delete;
@@ -5452,8 +8386,8 @@
5452
8386
  data = Object.assign(Object.assign(Object.assign({}, res), data), { settings: Object.assign(Object.assign({}, res.settings), data.settings), id: res.id });
5453
8387
  }
5454
8388
  yield api.POST(`tileset/update/${data.id}`, data, exports.Api.PrepReqParams(reqParams));
5455
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset + exports.Api.ECacheKey.Id + data.id);
5456
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset);
8389
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset + exports.Api.ECacheKey.Id + data.id);
8390
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.Tileset);
5457
8391
  return {
5458
8392
  tileset: data
5459
8393
  };
@@ -5643,7 +8577,7 @@
5643
8577
  if (!accountId || !tilesetId) {
5644
8578
  throw ("Client account ID and tileset ID are required.");
5645
8579
  }
5646
- const cacheData = api.GetCacheItem(GetCacheKey(accountId, tilesetId), reqParams);
8580
+ const cacheData = yield api.GetCacheItem(GetCacheKey(accountId, tilesetId), reqParams);
5647
8581
  if (cacheData) {
5648
8582
  return cacheData;
5649
8583
  }
@@ -5658,7 +8592,7 @@
5658
8592
  rej(e);
5659
8593
  }
5660
8594
  }));
5661
- api.SetCacheItem({
8595
+ yield api.SetCacheItem({
5662
8596
  key: GetCacheKey(accountId, tilesetId),
5663
8597
  value: prom,
5664
8598
  req: reqParams
@@ -5673,7 +8607,7 @@
5673
8607
  if (!accountId) {
5674
8608
  throw ("Client account ID is required.");
5675
8609
  }
5676
- const cacheData = api.GetCacheItem(GetCacheKey(accountId), reqParams);
8610
+ const cacheData = yield api.GetCacheItem(GetCacheKey(accountId), reqParams);
5677
8611
  if (cacheData) {
5678
8612
  return cacheData;
5679
8613
  }
@@ -5688,7 +8622,7 @@
5688
8622
  rej(e);
5689
8623
  }
5690
8624
  }));
5691
- api.SetCacheItem({
8625
+ yield api.SetCacheItem({
5692
8626
  key: GetCacheKey(accountId),
5693
8627
  value: req,
5694
8628
  req: reqParams
@@ -5853,7 +8787,7 @@
5853
8787
  throw ("View ID and Bookmark ID are required.");
5854
8788
  }
5855
8789
  const key = GetCacheKey(viewId, bookmarkId);
5856
- const cacheData = api.GetCacheItem(key, reqParams);
8790
+ const cacheData = yield api.GetCacheItem(key, reqParams);
5857
8791
  if (cacheData) {
5858
8792
  return cacheData;
5859
8793
  }
@@ -5868,7 +8802,7 @@
5868
8802
  rej(e);
5869
8803
  }
5870
8804
  }));
5871
- api.SetCacheItem({
8805
+ yield api.SetCacheItem({
5872
8806
  key,
5873
8807
  value: prom,
5874
8808
  req: reqParams
@@ -5895,7 +8829,7 @@
5895
8829
  if (!viewId) {
5896
8830
  throw ("View ID is required.");
5897
8831
  }
5898
- const cacheData = api.GetCacheItem(GetListCacheKey(viewId), reqParams);
8832
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(viewId), reqParams);
5899
8833
  if (cacheData) {
5900
8834
  return cacheData;
5901
8835
  }
@@ -5913,7 +8847,7 @@
5913
8847
  bookmark: item
5914
8848
  });
5915
8849
  });
5916
- api.SetCacheItem({
8850
+ yield api.SetCacheItem({
5917
8851
  key: GetCacheKey(viewId, item.ID),
5918
8852
  value: prom,
5919
8853
  req: reqParams
@@ -5927,7 +8861,7 @@
5927
8861
  rej(e);
5928
8862
  }
5929
8863
  }));
5930
- api.SetCacheItem({
8864
+ yield api.SetCacheItem({
5931
8865
  key: GetListCacheKey(viewId),
5932
8866
  value: req,
5933
8867
  req: reqParams
@@ -5959,7 +8893,7 @@
5959
8893
  "DisplayOrder.Start": 0
5960
8894
  };
5961
8895
  yield api.POST(`ui.view/${viewId}/slides/setOrder`, reqData, exports.Api.PrepReqParams(reqParams));
5962
- api.Cache.RemoveByStartsWith(GetListCacheKey(viewId));
8896
+ yield api.Cache.RemoveByStartsWith(GetListCacheKey(viewId));
5963
8897
  });
5964
8898
  }
5965
8899
  ProjectViewBookmark.SetOrder = SetOrder;
@@ -5992,7 +8926,7 @@
5992
8926
  throw ("View ID is required.");
5993
8927
  }
5994
8928
  const key = GetCacheKey(viewId);
5995
- const cacheData = api.GetCacheItem(key, reqParams);
8929
+ const cacheData = yield api.GetCacheItem(key, reqParams);
5996
8930
  if (cacheData) {
5997
8931
  return cacheData;
5998
8932
  }
@@ -6007,7 +8941,7 @@
6007
8941
  rej(e);
6008
8942
  }
6009
8943
  }));
6010
- api.SetCacheItem({
8944
+ yield api.SetCacheItem({
6011
8945
  key,
6012
8946
  value: prom,
6013
8947
  req: reqParams
@@ -6019,7 +8953,7 @@
6019
8953
  function GetList(params) {
6020
8954
  return __awaiter(this, void 0, void 0, function* () {
6021
8955
  const { api, req: reqParams } = params;
6022
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
8956
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
6023
8957
  if (cacheData) {
6024
8958
  return cacheData;
6025
8959
  }
@@ -6034,7 +8968,7 @@
6034
8968
  rej(e);
6035
8969
  }
6036
8970
  }));
6037
- api.SetCacheItem({
8971
+ yield api.SetCacheItem({
6038
8972
  key: GetListCacheKey(),
6039
8973
  value: prom,
6040
8974
  req: reqParams
@@ -6353,56 +9287,60 @@
6353
9287
  EPointType["Cylinder"] = "CYLINDER";
6354
9288
  })(EPointType = Style.EPointType || (Style.EPointType = {}));
6355
9289
  function GetList(params) {
6356
- const { api, req: reqParams } = params;
6357
- const cacheData = api.GetCacheItem(GetListCacheKey(), reqParams);
6358
- if (cacheData) {
6359
- return cacheData;
6360
- }
6361
- const res = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
6362
- try {
6363
- const data = yield api.GET("ui.entityDisplaySettings", exports.Api.PrepReqParams(reqParams));
6364
- res({
6365
- styles: data.Items
6366
- });
6367
- }
6368
- catch (e) {
6369
- rej(e);
9290
+ return __awaiter(this, void 0, void 0, function* () {
9291
+ const { api, req: reqParams } = params;
9292
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), reqParams);
9293
+ if (cacheData) {
9294
+ return cacheData;
6370
9295
  }
6371
- }));
6372
- api.SetCacheItem({
6373
- key: GetListCacheKey(),
6374
- value: res,
6375
- req: reqParams
9296
+ const res = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
9297
+ try {
9298
+ const data = yield api.GET("ui.entityDisplaySettings", exports.Api.PrepReqParams(reqParams));
9299
+ res({
9300
+ styles: data.Items
9301
+ });
9302
+ }
9303
+ catch (e) {
9304
+ rej(e);
9305
+ }
9306
+ }));
9307
+ yield api.SetCacheItem({
9308
+ key: GetListCacheKey(),
9309
+ value: res,
9310
+ req: reqParams
9311
+ });
9312
+ return res;
6376
9313
  });
6377
- return res;
6378
9314
  }
6379
9315
  Style.GetList = GetList;
6380
9316
  function Get(params) {
6381
- const { api, styleId: id, req: reqParams } = params;
6382
- if (!id) {
6383
- throw ("Style ID is required.");
6384
- }
6385
- const cacheData = api.GetCacheItem(GetCacheKey(id), reqParams);
6386
- if (cacheData) {
6387
- return cacheData;
6388
- }
6389
- const prom = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
6390
- try {
6391
- const data = yield api.GET(`ui.entityDisplaySetting/${id}`, exports.Api.PrepReqParams(reqParams));
6392
- res({
6393
- style: data
6394
- });
9317
+ return __awaiter(this, void 0, void 0, function* () {
9318
+ const { api, styleId: id, req: reqParams } = params;
9319
+ if (!id) {
9320
+ throw ("Style ID is required.");
6395
9321
  }
6396
- catch (e) {
6397
- rej(e);
9322
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id), reqParams);
9323
+ if (cacheData) {
9324
+ return cacheData;
6398
9325
  }
6399
- }));
6400
- api.SetCacheItem({
6401
- key: GetCacheKey(id),
6402
- value: prom,
6403
- req: reqParams
9326
+ const prom = new Promise((res, rej) => __awaiter(this, void 0, void 0, function* () {
9327
+ try {
9328
+ const data = yield api.GET(`ui.entityDisplaySetting/${id}`, exports.Api.PrepReqParams(reqParams));
9329
+ res({
9330
+ style: data
9331
+ });
9332
+ }
9333
+ catch (e) {
9334
+ rej(e);
9335
+ }
9336
+ }));
9337
+ yield api.SetCacheItem({
9338
+ key: GetCacheKey(id),
9339
+ value: prom,
9340
+ req: reqParams
9341
+ });
9342
+ return prom;
6404
9343
  });
6405
- return prom;
6406
9344
  }
6407
9345
  Style.Get = Get;
6408
9346
  function Update(params) {
@@ -6465,7 +9403,7 @@
6465
9403
  throw ("Session ID is required.");
6466
9404
  }
6467
9405
  const key = GetCacheKey(sessionId);
6468
- const cacheData = api.GetCacheItem(key, reqParams);
9406
+ const cacheData = yield api.GetCacheItem(key, reqParams);
6469
9407
  if (cacheData) {
6470
9408
  return cacheData;
6471
9409
  }
@@ -6480,7 +9418,7 @@
6480
9418
  rej(e);
6481
9419
  }
6482
9420
  }));
6483
- api.SetCacheItem({
9421
+ yield api.SetCacheItem({
6484
9422
  key,
6485
9423
  value: prom,
6486
9424
  req: reqParams
@@ -6684,7 +9622,7 @@
6684
9622
  if (!id) {
6685
9623
  throw ("ID is required.");
6686
9624
  }
6687
- const cacheData = api.GetCacheItem(GetCacheKey(id, accountId), reqParams);
9625
+ const cacheData = yield api.GetCacheItem(GetCacheKey(id, accountId), reqParams);
6688
9626
  if (cacheData) {
6689
9627
  return cacheData;
6690
9628
  }
@@ -6699,7 +9637,7 @@
6699
9637
  rej(e);
6700
9638
  }
6701
9639
  }));
6702
- api.SetCacheItem({
9640
+ yield api.SetCacheItem({
6703
9641
  key: GetCacheKey(id, accountId),
6704
9642
  value: prom,
6705
9643
  req: reqParams
@@ -6731,10 +9669,10 @@
6731
9669
  const res = yield api.POST(`user/${data.ID}`, data, reqParams);
6732
9670
  api.Cache.RemoveByContains(exports.Api.ECacheKey.User + exports.Api.ECacheKey.Id + data.ID);
6733
9671
  if (data.Type == EType.AccessToken) {
6734
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.AccessToken + exports.Api.ECacheKey.Account);
9672
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.AccessToken + exports.Api.ECacheKey.Account);
6735
9673
  }
6736
9674
  else if (data.Type == EType.User) {
6737
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.User + exports.Api.ECacheKey.Account);
9675
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.User + exports.Api.ECacheKey.Account);
6738
9676
  }
6739
9677
  return {
6740
9678
  user: res
@@ -6753,7 +9691,7 @@
6753
9691
  if (!userId || !appId) {
6754
9692
  throw ("UserId and appId are required.");
6755
9693
  }
6756
- const cacheData = api.GetCacheItem(GetSettingsCacheKey(userId, appId), req);
9694
+ const cacheData = yield api.GetCacheItem(GetSettingsCacheKey(userId, appId), req);
6757
9695
  if (cacheData) {
6758
9696
  return cacheData;
6759
9697
  }
@@ -6779,7 +9717,7 @@
6779
9717
  rej(e);
6780
9718
  }
6781
9719
  }));
6782
- api.SetCacheItem({
9720
+ yield api.SetCacheItem({
6783
9721
  key: GetSettingsCacheKey(userId, appId),
6784
9722
  value: prom,
6785
9723
  req: req
@@ -6845,7 +9783,7 @@
6845
9783
  if (!email) {
6846
9784
  throw ("Email is required.");
6847
9785
  }
6848
- const cacheData = api.GetCacheItem(GetEmailCacheKey(email, accountId), reqParams);
9786
+ const cacheData = yield api.GetCacheItem(GetEmailCacheKey(email, accountId), reqParams);
6849
9787
  if (cacheData) {
6850
9788
  return cacheData;
6851
9789
  }
@@ -6860,7 +9798,7 @@
6860
9798
  rej(e);
6861
9799
  }
6862
9800
  }));
6863
- api.SetCacheItem({
9801
+ yield api.SetCacheItem({
6864
9802
  key: GetEmailCacheKey(email, accountId),
6865
9803
  value: prom,
6866
9804
  req: reqParams
@@ -6878,7 +9816,7 @@
6878
9816
  if (!exclusive) {
6879
9817
  exclusive = false;
6880
9818
  }
6881
- const cacheData = exclusive ? null : api.GetCacheItem(GetListCacheKey(accountId), reqParams);
9819
+ const cacheData = exclusive ? null : yield api.GetCacheItem(GetListCacheKey(accountId), reqParams);
6882
9820
  if (cacheData) {
6883
9821
  return cacheData;
6884
9822
  }
@@ -6893,10 +9831,10 @@
6893
9831
  rej(e);
6894
9832
  }
6895
9833
  }));
6896
- req.then((data) => {
9834
+ req.then((data) => __awaiter(this, void 0, void 0, function* () {
6897
9835
  const users = data.users;
6898
9836
  for (let i = 0; i < users.length; i++) {
6899
- api.SetCacheItem({
9837
+ yield api.SetCacheItem({
6900
9838
  key: GetCacheKey(users[i].ID, accountId),
6901
9839
  value: {
6902
9840
  user: users[i]
@@ -6904,9 +9842,9 @@
6904
9842
  req: reqParams
6905
9843
  });
6906
9844
  }
6907
- });
9845
+ }));
6908
9846
  if (!exclusive) {
6909
- api.SetCacheItem({
9847
+ yield api.SetCacheItem({
6910
9848
  key: GetListCacheKey(accountId),
6911
9849
  value: req,
6912
9850
  req: reqParams
@@ -7040,7 +9978,7 @@
7040
9978
  function GetList(params) {
7041
9979
  return __awaiter(this, void 0, void 0, function* () {
7042
9980
  const { api, accountId, req: reqParams } = params;
7043
- const cacheData = api.GetCacheItem(GetListCacheKey(accountId), reqParams);
9981
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(accountId), reqParams);
7044
9982
  if (cacheData) {
7045
9983
  return cacheData;
7046
9984
  }
@@ -7055,10 +9993,10 @@
7055
9993
  rej(e);
7056
9994
  }
7057
9995
  }));
7058
- req.then((data) => {
9996
+ req.then((data) => __awaiter(this, void 0, void 0, function* () {
7059
9997
  const users = data.tokens;
7060
9998
  for (let i = 0; i < users.length; i++) {
7061
- api.SetCacheItem({
9999
+ yield api.SetCacheItem({
7062
10000
  key: GetCacheKey(users[i].ID, accountId),
7063
10001
  value: {
7064
10002
  user: users[i]
@@ -7066,8 +10004,8 @@
7066
10004
  req: reqParams
7067
10005
  });
7068
10006
  }
7069
- });
7070
- api.SetCacheItem({
10007
+ }));
10008
+ yield api.SetCacheItem({
7071
10009
  key: GetListCacheKey(accountId),
7072
10010
  value: req,
7073
10011
  req: reqParams
@@ -7081,7 +10019,7 @@
7081
10019
  const { api, tokenId: id, req: reqParams } = params;
7082
10020
  yield api.DELETE(`accessToken/${id}`, reqParams);
7083
10021
  api.Cache.RemoveByContains(exports.Api.ECacheKey.User + exports.Api.ECacheKey.Id + id);
7084
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.AccessToken + exports.Api.ECacheKey.Account);
10022
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.AccessToken + exports.Api.ECacheKey.Account);
7085
10023
  });
7086
10024
  }
7087
10025
  AccessToken.Delete = Delete;
@@ -7098,7 +10036,7 @@
7098
10036
  data.Type = EType.AccessToken;
7099
10037
  }
7100
10038
  data = yield api.POST("accessToken", data, reqParams);
7101
- api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.AccessToken + exports.Api.ECacheKey.Account);
10039
+ yield api.Cache.RemoveByStartsWith(exports.Api.ECacheKey.AccessToken + exports.Api.ECacheKey.Account);
7102
10040
  return {
7103
10041
  user: data
7104
10042
  };
@@ -7340,7 +10278,7 @@
7340
10278
  if (!pageIndex) {
7341
10279
  pageIndex = 0;
7342
10280
  }
7343
- const cacheData = api.GetCacheItem(GetListCacheKey(type, pageIndex), reqParams);
10281
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(type, pageIndex), reqParams);
7344
10282
  if (cacheData) {
7345
10283
  return cacheData;
7346
10284
  }
@@ -7365,7 +10303,7 @@
7365
10303
  rej(e);
7366
10304
  }
7367
10305
  }));
7368
- api.SetCacheItem({
10306
+ yield api.SetCacheItem({
7369
10307
  key: GetListCacheKey(type, pageIndex),
7370
10308
  value: prom,
7371
10309
  req: reqParams
@@ -7377,7 +10315,7 @@
7377
10315
  function Get(params) {
7378
10316
  return __awaiter(this, void 0, void 0, function* () {
7379
10317
  const { api, importedFileId: fileId, req: reqParams } = params;
7380
- const cacheData = api.GetCacheItem(GetCacheKey(fileId), reqParams);
10318
+ const cacheData = yield api.GetCacheItem(GetCacheKey(fileId), reqParams);
7381
10319
  if (cacheData) {
7382
10320
  return cacheData;
7383
10321
  }
@@ -7392,7 +10330,7 @@
7392
10330
  rej(e);
7393
10331
  }
7394
10332
  }));
7395
- api.SetCacheItem({
10333
+ yield api.SetCacheItem({
7396
10334
  key: GetCacheKey(fileId),
7397
10335
  value: prom,
7398
10336
  req: reqParams
@@ -7600,7 +10538,7 @@
7600
10538
  if (!pluginId) {
7601
10539
  throw ("Plugin ID is required.");
7602
10540
  }
7603
- const cacheData = api.GetCacheItem(GetCacheKey(pluginId), req);
10541
+ const cacheData = yield api.GetCacheItem(GetCacheKey(pluginId), req);
7604
10542
  if (cacheData) {
7605
10543
  return cacheData;
7606
10544
  }
@@ -7615,7 +10553,7 @@
7615
10553
  rej(e);
7616
10554
  }
7617
10555
  }));
7618
- api.SetCacheItem({
10556
+ yield api.SetCacheItem({
7619
10557
  key: GetCacheKey(pluginId),
7620
10558
  value: prom,
7621
10559
  req: req
@@ -7627,7 +10565,7 @@
7627
10565
  function GetList(params) {
7628
10566
  return __awaiter(this, void 0, void 0, function* () {
7629
10567
  const { api, req } = params;
7630
- const cacheData = api.GetCacheItem(GetListCacheKey(), req);
10568
+ const cacheData = yield api.GetCacheItem(GetListCacheKey(), req);
7631
10569
  if (cacheData) {
7632
10570
  return cacheData;
7633
10571
  }
@@ -7642,7 +10580,7 @@
7642
10580
  rej(e);
7643
10581
  }
7644
10582
  }));
7645
- api.SetCacheItem({
10583
+ yield api.SetCacheItem({
7646
10584
  key: GetListCacheKey(),
7647
10585
  value: prom,
7648
10586
  req: req
@@ -7668,6 +10606,7 @@
7668
10606
  exports.BruceEvent = BruceEvent;
7669
10607
  exports.CacheControl = CacheControl;
7670
10608
  exports.DelayQueue = DelayQueue;
10609
+ exports.LRUCache = LRUCache;
7671
10610
 
7672
10611
  Object.defineProperty(exports, '__esModule', { value: true });
7673
10612