forked from dexie/Dexie.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dexie.js
4607 lines (4202 loc) · 195 KB
/
dexie.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Dexie = factory());
}(this, (function () { 'use strict';
/*
* Dexie.js - a minimalistic wrapper for IndexedDB
* ===============================================
*
* By David Fahlander, david.fahlander@gmail.com
*
* Version 1.5.0-rc.5, Thu Oct 13 2016
* www.dexie.com
* Apache License Version 2.0, January 2004, http://www.apache.org/licenses/
*/
var keys = Object.keys;
var isArray = Array.isArray;
var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
function extend(obj, extension) {
if (typeof extension !== 'object') return obj;
keys(extension).forEach(function (key) {
obj[key] = extension[key];
});
return obj;
}
var getProto = Object.getPrototypeOf;
var _hasOwn = {}.hasOwnProperty;
function hasOwn(obj, prop) {
return _hasOwn.call(obj, prop);
}
function props(proto, extension) {
if (typeof extension === 'function') extension = extension(getProto(proto));
keys(extension).forEach(function (key) {
setProp(proto, key, extension[key]);
});
}
function setProp(obj, prop, functionOrGetSet, options) {
Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options));
}
function derive(Child) {
return {
from: function (Parent) {
Child.prototype = Object.create(Parent.prototype);
setProp(Child.prototype, "constructor", Child);
return {
extend: props.bind(null, Child.prototype)
};
}
};
}
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
function getPropertyDescriptor(obj, prop) {
var pd = getOwnPropertyDescriptor(obj, prop),
proto;
return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);
}
var _slice = [].slice;
function slice(args, start, end) {
return _slice.call(args, start, end);
}
function override(origFunc, overridedFactory) {
return overridedFactory(origFunc);
}
function doFakeAutoComplete(fn) {
var to = setTimeout(fn, 1000);
clearTimeout(to);
}
function assert(b) {
if (!b) throw new Error("Assertion Failed");
}
function asap(fn) {
if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0);
}
/** Generate an object (hash map) based on given array.
* @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to
* instert on the resulting object for each item in the array. If this function returns a falsy value, the
* current item wont affect the resulting object.
*/
function arrayToObject(array, extractor) {
return array.reduce(function (result, item, i) {
var nameAndValue = extractor(item, i);
if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];
return result;
}, {});
}
function trycatcher(fn, reject) {
return function () {
try {
fn.apply(this, arguments);
} catch (e) {
reject(e);
}
};
}
function tryCatch(fn, onerror, args) {
try {
fn.apply(null, args);
} catch (ex) {
onerror && onerror(ex);
}
}
function getByKeyPath(obj, keyPath) {
// http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path
if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.
if (!keyPath) return obj;
if (typeof keyPath !== 'string') {
var rv = [];
for (var i = 0, l = keyPath.length; i < l; ++i) {
var val = getByKeyPath(obj, keyPath[i]);
rv.push(val);
}
return rv;
}
var period = keyPath.indexOf('.');
if (period !== -1) {
var innerObj = obj[keyPath.substr(0, period)];
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));
}
return undefined;
}
function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if ('isFrozen' in Object && Object.isFrozen(obj)) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPath.length; i < l; ++i) {
setByKeyPath(obj, keyPath[i], value[i]);
}
} else {
var period = keyPath.indexOf('.');
if (period !== -1) {
var currentKeyPath = keyPath.substr(0, period);
var remainingKeyPath = keyPath.substr(period + 1);
if (remainingKeyPath === "") {
if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value;
} else {
var innerObj = obj[currentKeyPath];
if (!innerObj) innerObj = obj[currentKeyPath] = {};
setByKeyPath(innerObj, remainingKeyPath, value);
}
} else {
if (value === undefined) delete obj[keyPath];else obj[keyPath] = value;
}
}
}
function delByKeyPath(obj, keyPath) {
if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) {
setByKeyPath(obj, kp, undefined);
});
}
function shallowClone(obj) {
var rv = {};
for (var m in obj) {
if (hasOwn(obj, m)) rv[m] = obj[m];
}
return rv;
}
function deepClone(any) {
if (!any || typeof any !== 'object') return any;
var rv;
if (isArray(any)) {
rv = [];
for (var i = 0, l = any.length; i < l; ++i) {
rv.push(deepClone(any[i]));
}
} else if (any instanceof Date) {
rv = new Date();
rv.setTime(any.getTime());
} else {
rv = any.constructor ? Object.create(any.constructor.prototype) : {};
for (var prop in any) {
if (hasOwn(any, prop)) {
rv[prop] = deepClone(any[prop]);
}
}
}
return rv;
}
function getObjectDiff(a, b, rv, prfx) {
// Compares objects a and b and produces a diff object.
rv = rv || {};
prfx = prfx || '';
keys(a).forEach(function (prop) {
if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed
else {
var ap = a[prop],
bp = b[prop];
if (typeof ap === 'object' && typeof bp === 'object' && ap && bp && ap.constructor === bp.constructor)
// Same type of object but its properties may have changed
getObjectDiff(ap, bp, rv, prfx + prop + ".");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed
}
});
keys(b).forEach(function (prop) {
if (!hasOwn(a, prop)) {
rv[prfx + prop] = b[prop]; // Property added
}
});
return rv;
}
// If first argument is iterable or array-like, return it as an array
var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;
var getIteratorOf = iteratorSymbol ? function (x) {
var i;
return x != null && (i = x[iteratorSymbol]) && i.apply(x);
} : function () {
return null;
};
var NO_CHAR_ARRAY = {};
// Takes one or several arguments and returns an array based on the following criteras:
// * If several arguments provided, return arguments converted to an array in a way that
// still allows javascript engine to optimize the code.
// * If single argument is an array, return a clone of it.
// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special
// case to the two bullets below.
// * If single argument is an iterable, convert it to an array and return the resulting array.
// * If single argument is array-like (has length of type number), convert it to an array.
function getArrayOf(arrayLike) {
var i, a, x, it;
if (arguments.length === 1) {
if (isArray(arrayLike)) return arrayLike.slice();
if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];
if (it = getIteratorOf(arrayLike)) {
a = [];
while (x = it.next(), !x.done) {
a.push(x.value);
}return a;
}
if (arrayLike == null) return [arrayLike];
i = arrayLike.length;
if (typeof i === 'number') {
a = new Array(i);
while (i--) {
a[i] = arrayLike[i];
}return a;
}
return [arrayLike];
}
i = arguments.length;
a = new Array(i);
while (i--) {
a[i] = arguments[i];
}return a;
}
var concat = [].concat;
function flatten(a) {
return concat.apply([], a);
}
function nop() {}
function mirror(val) {
return val;
}
function pureFunctionChain(f1, f2) {
// Enables chained events that takes ONE argument and returns it to the next function in chain.
// This pattern is used in the hook("reading") event.
if (f1 == null || f1 === mirror) return f2;
return function (val) {
return f2(f1(val));
};
}
function callBoth(on1, on2) {
return function () {
on1.apply(this, arguments);
on2.apply(this, arguments);
};
}
function hookCreatingChain(f1, f2) {
// Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.
// This pattern is used in the hook("creating") event.
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res !== undefined) arguments[0] = res;
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = null;
this.onerror = null;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res2 !== undefined ? res2 : res;
};
}
function hookDeletingChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
f1.apply(this, arguments);
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = this.onerror = null;
f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
};
}
function hookUpdatingChain(f1, f2) {
if (f1 === nop) return f2;
return function (modifications) {
var res = f1.apply(this, arguments);
extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = null;
this.onerror = null;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2);
};
}
function reverseStoppableEventChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
if (f2.apply(this, arguments) === false) return false;
return f1.apply(this, arguments);
};
}
function promisableChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res && typeof res.then === 'function') {
var thiz = this,
i = arguments.length,
args = new Array(i);
while (i--) {
args[i] = arguments[i];
}return res.then(function () {
return f2.apply(thiz, args);
});
}
return f2.apply(this, arguments);
};
}
// By default, debug will be true only if platform is a web platform and its page is served from localhost.
// When debug = true, error's stacks will contain asyncronic long stacks.
var debug = typeof location !== 'undefined' &&
// By default, use debug mode if served from localhost.
/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);
function setDebug(value, filter) {
debug = value;
libraryFilter = filter;
}
var libraryFilter = function () {
return true;
};
var NEEDS_THROW_FOR_STACK = !new Error("").stack;
function getErrorWithStack() {
"use strict";
if (NEEDS_THROW_FOR_STACK) try {
// Doing something naughty in strict mode here to trigger a specific error
// that can be explicitely ignored in debugger's exception settings.
// If we'd just throw new Error() here, IE's debugger's exception settings
// will just consider it as "exception thrown by javascript code" which is
// something you wouldn't want it to ignore.
getErrorWithStack.arguments;
throw new Error(); // Fallback if above line don't throw.
} catch (e) {
return e;
}
return new Error();
}
function prettyStack(exception, numIgnoredFrames) {
var stack = exception.stack;
if (!stack) return "";
numIgnoredFrames = numIgnoredFrames || 0;
if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length;
return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) {
return "\n" + frame;
}).join('');
}
function deprecated(what, fn) {
return function () {
console.warn(what + " is deprecated. See https://github.com/dfahlander/Dexie.js/wiki/Deprecations. " + prettyStack(getErrorWithStack(), 1));
return fn.apply(this, arguments);
};
}
var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise'];
var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone'];
var errorList = dexieErrorNames.concat(idbDomErrorNames);
var defaultTexts = {
VersionChanged: "Database version changed by other database connection",
DatabaseClosed: "Database has been closed",
Abort: "Transaction aborted",
TransactionInactive: "Transaction has already completed or failed"
};
//
// DexieError - base class of all out exceptions.
//
function DexieError(name, msg) {
// Reason we don't use ES6 classes is because:
// 1. It bloats transpiled code and increases size of minified code.
// 2. It doesn't give us much in this case.
// 3. It would require sub classes to call super(), which
// is not needed when deriving from Error.
this._e = getErrorWithStack();
this.name = name;
this.message = msg;
}
derive(DexieError).from(Error).extend({
stack: {
get: function () {
return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2));
}
},
toString: function () {
return this.name + ": " + this.message;
}
});
function getMultiErrorMessage(msg, failures) {
return msg + ". Errors: " + failures.map(function (f) {
return f.toString();
}).filter(function (v, i, s) {
return s.indexOf(v) === i;
}) // Only unique error strings
.join('\n');
}
//
// ModifyError - thrown in WriteableCollection.modify()
// Specific constructor because it contains members failures and failedKeys.
//
function ModifyError(msg, failures, successCount, failedKeys) {
this._e = getErrorWithStack();
this.failures = failures;
this.failedKeys = failedKeys;
this.successCount = successCount;
}
derive(ModifyError).from(DexieError);
function BulkError(msg, failures) {
this._e = getErrorWithStack();
this.name = "BulkError";
this.failures = failures;
this.message = getMultiErrorMessage(msg, failures);
}
derive(BulkError).from(DexieError);
//
//
// Dynamically generate error names and exception classes based
// on the names in errorList.
//
//
// Map of {ErrorName -> ErrorName + "Error"}
var errnames = errorList.reduce(function (obj, name) {
return obj[name] = name + "Error", obj;
}, {});
// Need an alias for DexieError because we're gonna create subclasses with the same name.
var BaseException = DexieError;
// Map of {ErrorName -> exception constructor}
var exceptions = errorList.reduce(function (obj, name) {
// Let the name be "DexieError" because this name may
// be shown in call stack and when debugging. DexieError is
// the most true name because it derives from DexieError,
// and we cannot change Function.name programatically without
// dynamically create a Function object, which would be considered
// 'eval-evil'.
var fullName = name + "Error";
function DexieError(msgOrInner, inner) {
this._e = getErrorWithStack();
this.name = fullName;
if (!msgOrInner) {
this.message = defaultTexts[name] || fullName;
this.inner = null;
} else if (typeof msgOrInner === 'string') {
this.message = msgOrInner;
this.inner = inner || null;
} else if (typeof msgOrInner === 'object') {
this.message = msgOrInner.name + ' ' + msgOrInner.message;
this.inner = msgOrInner;
}
}
derive(DexieError).from(BaseException);
obj[name] = DexieError;
return obj;
}, {});
// Use ECMASCRIPT standard exceptions where applicable:
exceptions.Syntax = SyntaxError;
exceptions.Type = TypeError;
exceptions.Range = RangeError;
var exceptionMap = idbDomErrorNames.reduce(function (obj, name) {
obj[name + "Error"] = exceptions[name];
return obj;
}, {});
function mapError(domError, message) {
if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError;
var rv = new exceptionMap[domError.name](message || domError.message, domError);
if ("stack" in domError) {
// Derive stack from inner exception if it has a stack
setProp(rv, "stack", { get: function () {
return this.inner.stack;
} });
}
return rv;
}
var fullNameExceptions = errorList.reduce(function (obj, name) {
if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name];
return obj;
}, {});
fullNameExceptions.ModifyError = ModifyError;
fullNameExceptions.DexieError = DexieError;
fullNameExceptions.BulkError = BulkError;
function Events(ctx) {
var evs = {};
var rv = function (eventName, subscriber) {
if (subscriber) {
// Subscribe. If additional arguments than just the subscriber was provided, forward them as well.
var i = arguments.length,
args = new Array(i - 1);
while (--i) {
args[i - 1] = arguments[i];
}evs[eventName].subscribe.apply(null, args);
return ctx;
} else if (typeof eventName === 'string') {
// Return interface allowing to fire or unsubscribe from event
return evs[eventName];
}
};
rv.addEventType = add;
for (var i = 1, l = arguments.length; i < l; ++i) {
add(arguments[i]);
}
return rv;
function add(eventName, chainFunction, defaultFunction) {
if (typeof eventName === 'object') return addConfiguredEvents(eventName);
if (!chainFunction) chainFunction = reverseStoppableEventChain;
if (!defaultFunction) defaultFunction = nop;
var context = {
subscribers: [],
fire: defaultFunction,
subscribe: function (cb) {
if (context.subscribers.indexOf(cb) === -1) {
context.subscribers.push(cb);
context.fire = chainFunction(context.fire, cb);
}
},
unsubscribe: function (cb) {
context.subscribers = context.subscribers.filter(function (fn) {
return fn !== cb;
});
context.fire = context.subscribers.reduce(chainFunction, defaultFunction);
}
};
evs[eventName] = rv[eventName] = context;
return context;
}
function addConfiguredEvents(cfg) {
// events(this, {reading: [functionChain, nop]});
keys(cfg).forEach(function (eventName) {
var args = cfg[eventName];
if (isArray(args)) {
add(eventName, cfg[eventName][0], cfg[eventName][1]);
} else if (args === 'asap') {
// Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack
// enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.
var context = add(eventName, mirror, function fire() {
// Optimazation-safe cloning of arguments into args.
var i = arguments.length,
args = new Array(i);
while (i--) {
args[i] = arguments[i];
} // All each subscriber:
context.subscribers.forEach(function (fn) {
asap(function fireEvent() {
fn.apply(null, args);
});
});
});
} else throw new exceptions.InvalidArgument("Invalid event config");
});
}
}
//
// Promise Class for Dexie library
//
// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by
// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.
//
// Modifications needed to be done to support indexedDB because it wont accept setTimeout()
// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .
// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45
//
// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since
// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise.
//
// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another
// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use
// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick
// engine that is used instead of setImmediate() or setTimeout().
// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.
// Also with inspiration from bluebird, asyncronic stacks in debug mode.
//
// Specific non-standard features of this Promise class:
// * Async static context support (Promise.PSD)
// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame
// and below + all promises that those promises creates or awaits.
// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled).
//
// David Fahlander, https://github.com/dfahlander
//
// Just a pointer that only this module knows about.
// Used in Promise constructor to emulate a private constructor.
var INTERNAL = {};
// Async stacks (long stacks) must not grow infinitely.
var LONG_STACKS_CLIP_LIMIT = 100;
var MAX_LONG_STACKS = 20;
var stack_being_generated = false;
/* The default "nextTick" function used only for the very first promise in a promise chain.
As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks
emulated in this module. For indexedDB compatibility, this means that every method needs to
execute at least one promise before doing an indexedDB operation. Dexie will always call
db.ready().then() for every operation to make sure the indexedDB event is started in an
emulated micro tick.
*/
var schedulePhysicalTick = _global.setImmediate ?
// setImmediate supported. Those modern platforms also supports Function.bind().
setImmediate.bind(null, physicalTick) : _global.MutationObserver ?
// MutationObserver supported
function () {
var hiddenDiv = document.createElement("div");
new MutationObserver(function () {
physicalTick();
hiddenDiv = null;
}).observe(hiddenDiv, { attributes: true });
hiddenDiv.setAttribute('i', '1');
} :
// No support for setImmediate or MutationObserver. No worry, setTimeout is only called
// once time. Every tick that follows will be our emulated micro tick.
// Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug
function () {
setTimeout(physicalTick, 0);
};
// Confifurable through Promise.scheduler.
// Don't export because it would be unsafe to let unknown
// code call it unless they do try..catch within their callback.
// This function can be retrieved through getter of Promise.scheduler though,
// but users must not do Promise.scheduler (myFuncThatThrows exception)!
var asap$1 = function (callback, args) {
microtickQueue.push([callback, args]);
if (needsNewPhysicalTick) {
schedulePhysicalTick();
needsNewPhysicalTick = false;
}
};
var isOutsideMicroTick = true;
var needsNewPhysicalTick = true;
var unhandledErrors = [];
var rejectingErrors = [];
var currentFulfiller = null;
var rejectionMapper = mirror; // Remove in next major when removing error mapping of DOMErrors and DOMExceptions
var globalPSD = {
global: true,
ref: 0,
unhandleds: [],
onunhandled: globalError,
//env: null, // Will be set whenever leaving a scope using wrappers.snapshot()
finalize: function () {
this.unhandleds.forEach(function (uh) {
try {
globalError(uh[0], uh[1]);
} catch (e) {}
});
}
};
var PSD = globalPSD;
var microtickQueue = []; // Callbacks to call in this or next physical tick.
var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.
var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.
// Wrappers are not being used yet. Their framework is functioning and can be used
// to replace environment during a PSD scope (a.k.a. 'zone').
/* **KEEP** export var wrappers = (() => {
var wrappers = [];
return {
snapshot: () => {
var i = wrappers.length,
result = new Array(i);
while (i--) result[i] = wrappers[i].snapshot();
return result;
},
restore: values => {
var i = wrappers.length;
while (i--) wrappers[i].restore(values[i]);
},
wrap: () => wrappers.map(w => w.wrap()),
add: wrapper => {
wrappers.push(wrapper);
}
};
})();
*/
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
this._listeners = [];
this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.
// A library may set `promise._lib = true;` after promise is created to make resolve() or reject()
// execute the microtask engine implicitely within the call to resolve() or reject().
// To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack
// only contains library code when calling resolve() or reject().
// RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from
// global scope (event handler, timer etc)!
this._lib = false;
// Current async scope
var psd = this._PSD = PSD;
if (debug) {
this._stackHolder = getErrorWithStack();
this._prev = null;
this._numPrev = 0; // Number of previous promises (for long stacks)
linkToPreviousPromise(this, currentFulfiller);
}
if (typeof fn !== 'function') {
if (fn !== INTERNAL) throw new TypeError('Not a function');
// Private constructor (INTERNAL, state, value).
// Used internally by Promise.resolve() and Promise.reject().
this._state = arguments[1];
this._value = arguments[2];
if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().
return;
}
this._state = null; // null (=pending), false (=rejected) or true (=resolved)
this._value = null; // error or result
++psd.ref; // Refcounting current scope
executePromiseTask(this, fn);
}
props(Promise.prototype, {
then: function (onFulfilled, onRejected) {
var _this = this;
var rv = new Promise(function (resolve, reject) {
propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject));
});
debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this);
return rv;
},
_then: function (onFulfilled, onRejected) {
// A little tinier version of then() that don't have to create a resulting promise.
propagateToListener(this, new Listener(null, null, onFulfilled, onRejected));
},
catch: function (onRejected) {
if (arguments.length === 1) return this.then(null, onRejected);
// First argument is the Error type to catch
var type = arguments[0],
handler = arguments[1];
return typeof type === 'function' ? this.then(null, function (err) {
return (
// Catching errors by its constructor type (similar to java / c++ / c#)
// Sample: promise.catch(TypeError, function (e) { ... });
err instanceof type ? handler(err) : PromiseReject(err)
);
}) : this.then(null, function (err) {
return (
// Catching errors by the error.name property. Makes sense for indexedDB where error type
// is always DOMError but where e.name tells the actual error type.
// Sample: promise.catch('ConstraintError', function (e) { ... });
err && err.name === type ? handler(err) : PromiseReject(err)
);
});
},
finally: function (onFinally) {
return this.then(function (value) {
onFinally();
return value;
}, function (err) {
onFinally();
return PromiseReject(err);
});
},
// Deprecate in next major. Needed only for db.on.error.
uncaught: function (uncaughtHandler) {
var _this2 = this;
// Be backward compatible and use "onuncatched" as the event name on this.
// Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops.
this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler);
// In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not
// a previous promise. Reason: the prevous promise may lack onuncatched handler.
if (this._state === false && unhandledErrors.indexOf(this) === -1) {
// Replace unhandled error's destinaion promise with this one!
unhandledErrors.some(function (p, i, l) {
return p._value === _this2._value && (l[i] = _this2);
});
// Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could
// take away this piece of code as well as the onuncatched and uncaught() method.
}
return this;
},
stack: {
get: function () {
if (this._stack) return this._stack;
try {
stack_being_generated = true;
var stacks = getStack(this, [], MAX_LONG_STACKS);
var stack = stacks.join("\nFrom previous: ");
if (this._state !== null) this._stack = stack; // Stack may be updated on reject.
return stack;
} finally {
stack_being_generated = false;
}
}
}
});
function Listener(onFulfilled, onRejected, resolve, reject) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.resolve = resolve;
this.reject = reject;
this.psd = PSD;
}
// Promise Static Properties
props(Promise, {
all: function () {
var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like.
return new Promise(function (resolve, reject) {
if (values.length === 0) resolve([]);
var remaining = values.length;
values.forEach(function (a, i) {
return Promise.resolve(a).then(function (x) {
values[i] = x;
if (! --remaining) resolve(values);
}, reject);
});
});
},
resolve: function (value) {
if (value instanceof Promise) return value;
if (value && typeof value.then === 'function') return new Promise(function (resolve, reject) {
value.then(resolve, reject);
});
return new Promise(INTERNAL, true, value);
},
reject: PromiseReject,
race: function () {
var values = getArrayOf.apply(null, arguments);
return new Promise(function (resolve, reject) {
values.map(function (value) {
return Promise.resolve(value).then(resolve, reject);
});
});
},
PSD: {
get: function () {
return PSD;
},
set: function (value) {
return PSD = value;
}
},
newPSD: newScope,
usePSD: usePSD,
scheduler: {
get: function () {
return asap$1;
},
set: function (value) {
asap$1 = value;
}
},
rejectionMapper: {
get: function () {
return rejectionMapper;
},
set: function (value) {
rejectionMapper = value;
} // Map reject failures
},
follow: function (fn) {
return new Promise(function (resolve, reject) {
return newScope(function (resolve, reject) {
var psd = PSD;
psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()
psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.
psd.finalize = callBoth(function () {
var _this3 = this;
// Unhandled standard or 3rd part promises are put in PSD.unhandleds and
// examined upon scope completion while unhandled rejections in this Promise
// will trigger directly through psd.onunhandled
run_at_end_of_this_or_next_physical_tick(function () {
_this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]);
});
}, psd.finalize);
fn();
}, resolve, reject);
});
},
on: Events(null, { "error": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler
})
});
var PromiseOnError = Promise.on.error;
PromiseOnError.subscribe = deprecated("Promise.on('error')", PromiseOnError.subscribe);
PromiseOnError.unsubscribe = deprecated("Promise.on('error').unsubscribe", PromiseOnError.unsubscribe);
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.