dexie 4.0.8 → 4.1.0-alpha.2

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.
package/dist/dexie.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * By David Fahlander, david.fahlander@gmail.com
6
6
  *
7
- * Version 4.0.8, Wed Jul 10 2024
7
+ * Version 4.1.0-alpha.2, Fri Oct 04 2024
8
8
  *
9
9
  * https://dexie.org
10
10
  *
@@ -52,6 +52,33 @@
52
52
  };
53
53
  return __assign.apply(this, arguments);
54
54
  };
55
+ function __values(o) {
56
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
57
+ if (m) return m.call(o);
58
+ if (o && typeof o.length === "number") return {
59
+ next: function () {
60
+ if (o && i >= o.length) o = void 0;
61
+ return { value: o && o[i++], done: !o };
62
+ }
63
+ };
64
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
65
+ }
66
+ function __read(o, n) {
67
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
68
+ if (!m) return o;
69
+ var i = m.call(o), r, ar = [], e;
70
+ try {
71
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
72
+ }
73
+ catch (error) { e = { error: error }; }
74
+ finally {
75
+ try {
76
+ if (r && !r.done && (m = i["return"])) m.call(i);
77
+ }
78
+ finally { if (e) throw e.error; }
79
+ }
80
+ return ar;
81
+ }
55
82
  function __spreadArray(to, from, pack) {
56
83
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
57
84
  if (ar || !(i in from)) {
@@ -1150,7 +1177,7 @@
1150
1177
  }
1151
1178
  }
1152
1179
 
1153
- var DEXIE_VERSION = '4.0.8';
1180
+ var DEXIE_VERSION = '4.1.0-alpha.2';
1154
1181
  var maxString = String.fromCharCode(65535);
1155
1182
  var minKey = -Infinity;
1156
1183
  var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.";
@@ -1268,6 +1295,95 @@
1268
1295
  return new Uint8Array(a);
1269
1296
  }
1270
1297
 
1298
+ function getDocCache(db) {
1299
+ var _a;
1300
+ var _b;
1301
+ return (_a = (_b = db._novip)['_docCache']) !== null && _a !== void 0 ? _a : (_b['_docCache'] = {
1302
+ cache: {},
1303
+ get size() {
1304
+ return Object.keys(this.cache).length;
1305
+ },
1306
+ find: function (table, primaryKey, ydocProp) {
1307
+ var cacheKey = getYDocCacheKey(table, primaryKey, ydocProp);
1308
+ var docRef = this.cache[cacheKey];
1309
+ return docRef ? docRef.deref() : undefined;
1310
+ },
1311
+ add: function (doc) {
1312
+ var _a = doc.meta, parentTable = _a.parentTable, parentId = _a.parentId, parentProp = _a.parentProp;
1313
+ if (!parentTable || !parentProp || parentId == null)
1314
+ throw new Error("Missing Dexie-related metadata in Y.Doc");
1315
+ var cacheKey = getYDocCacheKey(parentTable, parentId, parentProp);
1316
+ this.cache[cacheKey] = new WeakRef(doc);
1317
+ docRegistry.register(doc, { cache: this.cache, key: cacheKey });
1318
+ },
1319
+ delete: function (doc) {
1320
+ docRegistry.unregister(doc);
1321
+ delete this.cache[getYDocCacheKey(doc.meta.parentTable, doc.meta.parentId, doc.meta.parentProp)];
1322
+ },
1323
+ });
1324
+ }
1325
+ var docRegistry = new FinalizationRegistry(function (_a) {
1326
+ var cache = _a.cache, key = _a.key;
1327
+ delete cache[key];
1328
+ });
1329
+ var destroyedDocs = new WeakSet();
1330
+ function throwIfDestroyed(doc) {
1331
+ if (destroyedDocs.has(doc))
1332
+ throw new Error('Y.Doc has been destroyed');
1333
+ }
1334
+ function getYDocCacheKey(table, primaryKey, ydocProp) {
1335
+ return "".concat(table, "[").concat(primaryKey, "].").concat(ydocProp);
1336
+ }
1337
+
1338
+ function createYDocProperty(db, Y, table, prop, updatesTable) {
1339
+ var pkKeyPath = table.schema.primKey.keyPath;
1340
+ var docCache = getDocCache(db);
1341
+ return {
1342
+ get: function () {
1343
+ var id = getByKeyPath(this, pkKeyPath);
1344
+ var doc = docCache.find(table.name, id, prop);
1345
+ if (doc)
1346
+ return doc;
1347
+ doc = new Y.Doc({
1348
+ meta: {
1349
+ db: db,
1350
+ updatesTable: updatesTable,
1351
+ parentProp: prop,
1352
+ parentTable: table.name,
1353
+ parentId: id
1354
+ },
1355
+ });
1356
+ docCache.add(doc);
1357
+ doc.on('destroy', function () {
1358
+ destroyedDocs.add(doc);
1359
+ docCache.delete(doc);
1360
+ });
1361
+ return doc;
1362
+ },
1363
+ };
1364
+ }
1365
+
1366
+ function builtInDeletionTrigger(table, keys, res) {
1367
+ var yProps = table.schema.yProps;
1368
+ if (!yProps)
1369
+ return res;
1370
+ if (keys && res.numFailures > 0)
1371
+ keys = keys.filter(function (_, i) { return !res.failures[i]; });
1372
+ return Promise.all(yProps.map(function (_a) {
1373
+ var updatesTable = _a.updatesTable;
1374
+ return keys
1375
+ ? table.db.table(updatesTable).where('k').anyOf(keys).delete()
1376
+ : table.db.table(updatesTable).clear();
1377
+ })).then(function () { return res; });
1378
+ }
1379
+
1380
+ function getYLibrary(db) {
1381
+ var Y = db._options.Y;
1382
+ if (!Y)
1383
+ throw new exceptions.MissingAPI('Y library not supplied to Dexie constructor');
1384
+ return Y;
1385
+ }
1386
+
1271
1387
  var Table = (function () {
1272
1388
  function Table() {
1273
1389
  }
@@ -1347,8 +1463,8 @@
1347
1463
  function equals(a, b) {
1348
1464
  return idb.cmp(a, b) === 0;
1349
1465
  }
1350
- var _a = keyPaths.reduce(function (_a, keyPath) {
1351
- var prevIndex = _a[0], prevFilterFn = _a[1];
1466
+ var _a = __read(keyPaths.reduce(function (_a, keyPath) {
1467
+ var _b = __read(_a, 2), prevIndex = _b[0], prevFilterFn = _b[1];
1352
1468
  var index = idxByName[keyPath];
1353
1469
  var value = indexOrCrit[keyPath];
1354
1470
  return [
@@ -1361,7 +1477,7 @@
1361
1477
  } : function (x) { return equals(value, getByKeyPath(x, keyPath)); })
1362
1478
  : prevFilterFn
1363
1479
  ];
1364
- }, [null, null]), idx = _a[0], filterFunction = _a[1];
1480
+ }, [null, null]), 2), idx = _a[0], filterFunction = _a[1];
1365
1481
  return idx ?
1366
1482
  this.where(idx.name).equals(indexOrCrit[idx.keyPath])
1367
1483
  .filter(filterFunction) :
@@ -1399,6 +1515,7 @@
1399
1515
  return this.toCollection().reverse();
1400
1516
  };
1401
1517
  Table.prototype.mapToClass = function (constructor) {
1518
+ var _this = this;
1402
1519
  var _a = this, db = _a.db, tableName = _a.name;
1403
1520
  this.schema.mappedClass = constructor;
1404
1521
  if (constructor.prototype instanceof Entity) {
@@ -1416,6 +1533,20 @@
1416
1533
  return class_1;
1417
1534
  }(constructor));
1418
1535
  }
1536
+ if (this.schema.yProps) {
1537
+ var Y_1 = getYLibrary(db);
1538
+ constructor = (function (_super) {
1539
+ __extends(class_2, _super);
1540
+ function class_2() {
1541
+ return _super !== null && _super.apply(this, arguments) || this;
1542
+ }
1543
+ return class_2;
1544
+ }(constructor));
1545
+ this.schema.yProps.forEach(function (_a) {
1546
+ var prop = _a.prop, updatesTable = _a.updatesTable;
1547
+ Object.defineProperty(constructor.prototype, prop, createYDocProperty(db, Y_1, _this, prop, updatesTable));
1548
+ });
1549
+ }
1419
1550
  var inheritedProps = new Set();
1420
1551
  for (var proto = constructor.prototype; proto; proto = getProto(proto)) {
1421
1552
  Object.getOwnPropertyNames(proto).forEach(function (propName) { return inheritedProps.add(propName); });
@@ -1497,12 +1628,14 @@
1497
1628
  };
1498
1629
  Table.prototype.delete = function (key) {
1499
1630
  var _this = this;
1500
- return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] }); })
1501
- .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });
1631
+ return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'delete', keys: [key] })
1632
+ .then(function (res) { return builtInDeletionTrigger(_this, [key], res); })
1633
+ .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; }); });
1502
1634
  };
1503
1635
  Table.prototype.clear = function () {
1504
1636
  var _this = this;
1505
- return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange }); })
1637
+ return this._trans('readwrite', function (trans) { return _this.core.mutate({ trans: trans, type: 'deleteRange', range: AnyRange })
1638
+ .then(function (res) { return builtInDeletionTrigger(_this, null, res); }); })
1506
1639
  .then(function (res) { return res.numFailures ? DexiePromise.reject(res.failures[0]) : undefined; });
1507
1640
  };
1508
1641
  Table.prototype.bulkGet = function (keys) {
@@ -1575,20 +1708,30 @@
1575
1708
  var resultKeys = [];
1576
1709
  var resultObjs = [];
1577
1710
  keysAndChanges.forEach(function (_a, idx) {
1711
+ var e_1, _b;
1578
1712
  var key = _a.key, changes = _a.changes;
1579
1713
  var obj = objs[idx];
1580
1714
  if (obj) {
1581
- for (var _i = 0, _b = Object.keys(changes); _i < _b.length; _i++) {
1582
- var keyPath = _b[_i];
1583
- var value = changes[keyPath];
1584
- if (keyPath === _this.schema.primKey.keyPath) {
1585
- if (cmp(value, key) !== 0) {
1586
- throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()");
1715
+ try {
1716
+ for (var _c = __values(Object.keys(changes)), _d = _c.next(); !_d.done; _d = _c.next()) {
1717
+ var keyPath = _d.value;
1718
+ var value = changes[keyPath];
1719
+ if (keyPath === _this.schema.primKey.keyPath) {
1720
+ if (cmp(value, key) !== 0) {
1721
+ throw new exceptions.Constraint("Cannot update primary key in bulkUpdate()");
1722
+ }
1723
+ }
1724
+ else {
1725
+ setByKeyPath(obj, keyPath, value);
1587
1726
  }
1588
1727
  }
1589
- else {
1590
- setByKeyPath(obj, keyPath, value);
1728
+ }
1729
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1730
+ finally {
1731
+ try {
1732
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1591
1733
  }
1734
+ finally { if (e_1) throw e_1.error; }
1592
1735
  }
1593
1736
  offsetMap.push(idx);
1594
1737
  resultKeys.push(key);
@@ -1608,17 +1751,27 @@
1608
1751
  }
1609
1752
  })
1610
1753
  .then(function (_a) {
1754
+ var e_2, _b;
1611
1755
  var numFailures = _a.numFailures, failures = _a.failures;
1612
1756
  if (numFailures === 0)
1613
1757
  return numEntries;
1614
- for (var _i = 0, _b = Object.keys(failures); _i < _b.length; _i++) {
1615
- var offset = _b[_i];
1616
- var mappedOffset = offsetMap[Number(offset)];
1617
- if (mappedOffset != null) {
1618
- var failure = failures[offset];
1619
- delete failures[offset];
1620
- failures[mappedOffset] = failure;
1758
+ try {
1759
+ for (var _c = __values(Object.keys(failures)), _d = _c.next(); !_d.done; _d = _c.next()) {
1760
+ var offset = _d.value;
1761
+ var mappedOffset = offsetMap[Number(offset)];
1762
+ if (mappedOffset != null) {
1763
+ var failure = failures[offset];
1764
+ delete failures[offset];
1765
+ failures[mappedOffset] = failure;
1766
+ }
1767
+ }
1768
+ }
1769
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
1770
+ finally {
1771
+ try {
1772
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1621
1773
  }
1774
+ finally { if (e_2) throw e_2.error; }
1622
1775
  }
1623
1776
  throw new BulkError("".concat(_this.name, ".bulkUpdate(): ").concat(numFailures, " of ").concat(numEntries, " operations failed"), failures);
1624
1777
  });
@@ -1629,7 +1782,8 @@
1629
1782
  var _this = this;
1630
1783
  var numKeys = keys.length;
1631
1784
  return this._trans('readwrite', function (trans) {
1632
- return _this.core.mutate({ trans: trans, type: 'delete', keys: keys });
1785
+ return _this.core.mutate({ trans: trans, type: 'delete', keys: keys })
1786
+ .then(function (res) { return builtInDeletionTrigger(_this, keys, res); });
1633
1787
  }).then(function (_a) {
1634
1788
  var numFailures = _a.numFailures, lastResult = _a.lastResult, failures = _a.failures;
1635
1789
  if (numFailures === 0)
@@ -1813,7 +1967,7 @@
1813
1967
  if (this.add !== undefined) {
1814
1968
  var term = this.add;
1815
1969
  if (isArray(term)) {
1816
- return __spreadArray(__spreadArray([], (isArray(value) ? value : []), true), term, true).sort();
1970
+ return __spreadArray(__spreadArray([], __read((isArray(value) ? value : [])), false), __read(term), false).sort();
1817
1971
  }
1818
1972
  if (typeof term === 'number')
1819
1973
  return (Number(value) || 0) + term;
@@ -2146,52 +2300,65 @@
2146
2300
  var successCount = 0;
2147
2301
  var failedKeys = [];
2148
2302
  var applyMutateResult = function (expectedCount, res) {
2303
+ var e_1, _a;
2149
2304
  var failures = res.failures, numFailures = res.numFailures;
2150
2305
  successCount += expectedCount - numFailures;
2151
- for (var _i = 0, _a = keys(failures); _i < _a.length; _i++) {
2152
- var pos = _a[_i];
2153
- totalFailures.push(failures[pos]);
2306
+ try {
2307
+ for (var _b = __values(keys(failures)), _c = _b.next(); !_c.done; _c = _b.next()) {
2308
+ var pos = _c.value;
2309
+ totalFailures.push(failures[pos]);
2310
+ }
2311
+ }
2312
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2313
+ finally {
2314
+ try {
2315
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2316
+ }
2317
+ finally { if (e_1) throw e_1.error; }
2154
2318
  }
2155
2319
  };
2320
+ var isUnconditionalDelete = changes === deleteCallback;
2156
2321
  return _this.clone().primaryKeys().then(function (keys) {
2157
2322
  var criteria = isPlainKeyRange(ctx) &&
2158
2323
  ctx.limit === Infinity &&
2159
- (typeof changes !== 'function' || changes === deleteCallback) && {
2324
+ (typeof changes !== 'function' || isUnconditionalDelete) && {
2160
2325
  index: ctx.index,
2161
2326
  range: ctx.range
2162
2327
  };
2163
2328
  var nextChunk = function (offset) {
2164
2329
  var count = Math.min(limit, keys.length - offset);
2165
- return coreTable.getMany({
2330
+ var keysInChunk = keys.slice(offset, offset + count);
2331
+ return (isUnconditionalDelete ? Promise.resolve([]) : coreTable.getMany({
2166
2332
  trans: trans,
2167
- keys: keys.slice(offset, offset + count),
2333
+ keys: keysInChunk,
2168
2334
  cache: "immutable"
2169
- }).then(function (values) {
2335
+ })).then(function (values) {
2170
2336
  var addValues = [];
2171
2337
  var putValues = [];
2172
2338
  var putKeys = outbound ? [] : null;
2173
- var deleteKeys = [];
2174
- for (var i = 0; i < count; ++i) {
2175
- var origValue = values[i];
2176
- var ctx_1 = {
2177
- value: deepClone(origValue),
2178
- primKey: keys[offset + i]
2179
- };
2180
- if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {
2181
- if (ctx_1.value == null) {
2182
- deleteKeys.push(keys[offset + i]);
2183
- }
2184
- else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {
2185
- deleteKeys.push(keys[offset + i]);
2186
- addValues.push(ctx_1.value);
2187
- }
2188
- else {
2189
- putValues.push(ctx_1.value);
2190
- if (outbound)
2191
- putKeys.push(keys[offset + i]);
2339
+ var deleteKeys = isUnconditionalDelete ? keysInChunk : [];
2340
+ if (!isUnconditionalDelete)
2341
+ for (var i = 0; i < count; ++i) {
2342
+ var origValue = values[i];
2343
+ var ctx_1 = {
2344
+ value: deepClone(origValue),
2345
+ primKey: keys[offset + i]
2346
+ };
2347
+ if (modifyer.call(ctx_1, ctx_1.value, ctx_1) !== false) {
2348
+ if (ctx_1.value == null) {
2349
+ deleteKeys.push(keys[offset + i]);
2350
+ }
2351
+ else if (!outbound && cmp(extractKey(origValue), extractKey(ctx_1.value)) !== 0) {
2352
+ deleteKeys.push(keys[offset + i]);
2353
+ addValues.push(ctx_1.value);
2354
+ }
2355
+ else {
2356
+ putValues.push(ctx_1.value);
2357
+ if (outbound)
2358
+ putKeys.push(keys[offset + i]);
2359
+ }
2192
2360
  }
2193
2361
  }
2194
- }
2195
2362
  return Promise.resolve(addValues.length > 0 &&
2196
2363
  coreTable.mutate({ trans: trans, type: 'add', values: addValues })
2197
2364
  .then(function (res) {
@@ -2209,14 +2376,15 @@
2209
2376
  changeSpec: typeof changes !== 'function'
2210
2377
  && changes,
2211
2378
  isAdditionalChunk: offset > 0
2212
- }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && changes === deleteCallback)) &&
2379
+ }).then(function (res) { return applyMutateResult(putValues.length, res); }); }).then(function () { return (deleteKeys.length > 0 || (criteria && isUnconditionalDelete)) &&
2213
2380
  coreTable.mutate({
2214
2381
  trans: trans,
2215
2382
  type: 'delete',
2216
2383
  keys: deleteKeys,
2217
2384
  criteria: criteria,
2218
2385
  isAdditionalChunk: offset > 0
2219
- }).then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {
2386
+ }).then(function (res) { return builtInDeletionTrigger(ctx.table, deleteKeys, res); })
2387
+ .then(function (res) { return applyMutateResult(deleteKeys.length, res); }); }).then(function () {
2220
2388
  return keys.length > offset + count && nextChunk(offset + limit);
2221
2389
  });
2222
2390
  });
@@ -2232,6 +2400,7 @@
2232
2400
  Collection.prototype.delete = function () {
2233
2401
  var ctx = this._ctx, range = ctx.range;
2234
2402
  if (isPlainKeyRange(ctx) &&
2403
+ !ctx.table.schema.yProps &&
2235
2404
  (ctx.isPrimKey || range.type === 3 ))
2236
2405
  {
2237
2406
  return this._write(function (trans) {
@@ -2240,7 +2409,7 @@
2240
2409
  return ctx.table.core.count({ trans: trans, query: { index: primaryKey, range: coreRange } }).then(function (count) {
2241
2410
  return ctx.table.core.mutate({ trans: trans, type: 'deleteRange', range: coreRange })
2242
2411
  .then(function (_a) {
2243
- var failures = _a.failures; _a.lastResult; _a.results; var numFailures = _a.numFailures;
2412
+ var failures = _a.failures, numFailures = _a.numFailures;
2244
2413
  if (numFailures)
2245
2414
  throw new ModifyError("Could not delete some values", Object.keys(failures).map(function (pos) { return failures[pos]; }), count - numFailures);
2246
2415
  return count - numFailures;
@@ -2842,6 +3011,13 @@
2842
3011
  function createTransactionConstructor(db) {
2843
3012
  return makeClassConstructor(Transaction.prototype, function Transaction(mode, storeNames, dbschema, chromeTransactionDurability, parent) {
2844
3013
  var _this = this;
3014
+ if (mode !== 'readonly')
3015
+ storeNames.forEach(function (storeName) {
3016
+ var _a;
3017
+ var yProps = (_a = dbschema[storeName]) === null || _a === void 0 ? void 0 : _a.yProps;
3018
+ if (yProps)
3019
+ storeNames = storeNames.concat(yProps.map(function (p) { return p.updatesTable; }));
3020
+ });
2845
3021
  this.db = db;
2846
3022
  this.mode = mode;
2847
3023
  this.storeNames = storeNames;
@@ -2877,7 +3053,7 @@
2877
3053
  });
2878
3054
  }
2879
3055
 
2880
- function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey) {
3056
+ function createIndexSpec(name, keyPath, unique, multi, auto, compound, isPrimKey, type) {
2881
3057
  return {
2882
3058
  name: name,
2883
3059
  keyPath: keyPath,
@@ -2885,7 +3061,8 @@
2885
3061
  multi: multi,
2886
3062
  auto: auto,
2887
3063
  compound: compound,
2888
- src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath)
3064
+ src: (unique && !isPrimKey ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + nameFromKeyPath(keyPath),
3065
+ type: type
2889
3066
  };
2890
3067
  }
2891
3068
  function nameFromKeyPath(keyPath) {
@@ -2894,13 +3071,17 @@
2894
3071
  keyPath ? ('[' + [].join.call(keyPath, '+') + ']') : "";
2895
3072
  }
2896
3073
 
2897
- function createTableSchema(name, primKey, indexes) {
3074
+ function createTableSchema(name, primKey, indexes, yProps) {
2898
3075
  return {
2899
3076
  name: name,
2900
3077
  primKey: primKey,
2901
3078
  indexes: indexes,
2902
3079
  mappedClass: null,
2903
- idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; })
3080
+ yProps: yProps === null || yProps === void 0 ? void 0 : yProps.map(function (prop) { return ({
3081
+ prop: prop,
3082
+ updatesTable: "$".concat(name, ".").concat(prop, "_updates"),
3083
+ }); }),
3084
+ idxByName: arrayToObject(indexes, function (index) { return [index.name, index]; }),
2904
3085
  };
2905
3086
  }
2906
3087
 
@@ -3053,11 +3234,11 @@
3053
3234
  reqs.push(req = store.delete(makeIDBKeyRange(range)));
3054
3235
  }
3055
3236
  else {
3056
- var _a = isAddOrPut ?
3237
+ var _a = __read(isAddOrPut ?
3057
3238
  outbound ?
3058
3239
  [values, keys] :
3059
3240
  [values, null] :
3060
- [keys, null], args1 = _a[0], args2 = _a[1];
3241
+ [keys, null], 2), args1 = _a[0], args2 = _a[1];
3061
3242
  if (isAddOrPut) {
3062
3243
  for (var i = 0; i < length; ++i) {
3063
3244
  reqs.push(req = (args2 && args2[i] !== undefined ?
@@ -3382,6 +3563,7 @@
3382
3563
  });
3383
3564
  }
3384
3565
  function patchCurrentVersion(db, idbUpgradeTrans) {
3566
+ var e_1, _a;
3385
3567
  createMissingTables(db._dbSchema, idbUpgradeTrans);
3386
3568
  if (idbUpgradeTrans.db.version % 10 === 0 && !idbUpgradeTrans.objectStoreNames.contains('$meta')) {
3387
3569
  idbUpgradeTrans.db.createObjectStore('$meta').add(Math.ceil((idbUpgradeTrans.db.version / 10) - 1), 'version');
@@ -3401,11 +3583,20 @@
3401
3583
  addIndex(store, idx);
3402
3584
  });
3403
3585
  };
3404
- for (var _i = 0, _a = diff.change; _i < _a.length; _i++) {
3405
- var tableChange = _a[_i];
3406
- var state_1 = _loop_1(tableChange);
3407
- if (typeof state_1 === "object")
3408
- return state_1.value;
3586
+ try {
3587
+ for (var _b = __values(diff.change), _c = _b.next(); !_c.done; _c = _b.next()) {
3588
+ var tableChange = _c.value;
3589
+ var state_1 = _loop_1(tableChange);
3590
+ if (typeof state_1 === "object")
3591
+ return state_1.value;
3592
+ }
3593
+ }
3594
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3595
+ finally {
3596
+ try {
3597
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
3598
+ }
3599
+ finally { if (e_1) throw e_1.error; }
3409
3600
  }
3410
3601
  }
3411
3602
  function getExistingVersion(db, trans, oldVersion) {
@@ -3644,10 +3835,15 @@
3644
3835
  }
3645
3836
  function parseIndexSyntax(primKeyAndIndexes) {
3646
3837
  return primKeyAndIndexes.split(',').map(function (index, indexNum) {
3647
- index = index.trim();
3838
+ var _a;
3839
+ var typeSplit = index.split(':');
3840
+ var type = (_a = typeSplit[1]) === null || _a === void 0 ? void 0 : _a.trim();
3841
+ index = typeSplit[0].trim();
3842
+ if (type && type !== 'Y')
3843
+ throw new exceptions.Schema("Unsupported type '".concat(type, "'"));
3648
3844
  var name = index.replace(/([&*]|\+\+)/g, "");
3649
3845
  var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name;
3650
- return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0);
3846
+ return createIndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), indexNum === 0, type);
3651
3847
  });
3652
3848
  }
3653
3849
 
@@ -3655,40 +3851,66 @@
3655
3851
  function Version() {
3656
3852
  }
3657
3853
  Version.prototype._parseStoresSpec = function (stores, outSchema) {
3854
+ var _this = this;
3658
3855
  keys(stores).forEach(function (tableName) {
3856
+ var e_1, _a, _b;
3659
3857
  if (stores[tableName] !== null) {
3660
3858
  var indexes = parseIndexSyntax(stores[tableName]);
3859
+ var yProps = indexes.filter(function (idx) { return idx.type === 'Y'; }).map(function (idx) { return idx.name; });
3860
+ indexes = indexes.filter(function (idx) { return idx.type !== 'Y'; });
3661
3861
  var primKey = indexes.shift();
3862
+ if (!primKey) {
3863
+ throw new exceptions.Schema('Invalid schema for table ' + tableName + ': ' + stores[tableName]);
3864
+ }
3662
3865
  primKey.unique = true;
3663
3866
  if (primKey.multi)
3664
- throw new exceptions.Schema("Primary key cannot be multi-valued");
3867
+ throw new exceptions.Schema('Primary key cannot be multiEntry*');
3665
3868
  indexes.forEach(function (idx) {
3666
3869
  if (idx.auto)
3667
- throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)");
3870
+ throw new exceptions.Schema('Only primary key can be marked as autoIncrement (++)');
3668
3871
  if (!idx.keyPath)
3669
- throw new exceptions.Schema("Index must have a name and cannot be an empty string");
3872
+ throw new exceptions.Schema('Index must have a name and cannot be an empty string');
3670
3873
  });
3671
- outSchema[tableName] = createTableSchema(tableName, primKey, indexes);
3874
+ var tblSchema = createTableSchema(tableName, primKey, indexes, yProps.length ? yProps : undefined);
3875
+ outSchema[tableName] = tblSchema;
3876
+ try {
3877
+ for (var _c = __values(tblSchema.yProps || []), _d = _c.next(); !_d.done; _d = _c.next()) {
3878
+ var yProp = _d.value;
3879
+ _this._parseStoresSpec((_b = {}, _b[yProp.updatesTable] = '++i,k', _b), outSchema);
3880
+ }
3881
+ }
3882
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3883
+ finally {
3884
+ try {
3885
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
3886
+ }
3887
+ finally { if (e_1) throw e_1.error; }
3888
+ }
3672
3889
  }
3673
3890
  });
3674
3891
  };
3675
3892
  Version.prototype.stores = function (stores) {
3676
3893
  var db = this.db;
3677
- this._cfg.storesSource = this._cfg.storesSource ?
3678
- extend(this._cfg.storesSource, stores) :
3679
- stores;
3894
+ this._cfg.storesSource = this._cfg.storesSource
3895
+ ? extend(this._cfg.storesSource, stores)
3896
+ : stores;
3680
3897
  var versions = db._versions;
3681
3898
  var storesSpec = {};
3682
3899
  var dbschema = {};
3683
3900
  versions.forEach(function (version) {
3684
3901
  extend(storesSpec, version._cfg.storesSource);
3685
- dbschema = (version._cfg.dbschema = {});
3902
+ dbschema = version._cfg.dbschema = {};
3686
3903
  version._parseStoresSpec(storesSpec, dbschema);
3687
3904
  });
3688
3905
  db._dbSchema = dbschema;
3689
3906
  removeTablesApi(db, [db._allTables, db, db.Transaction.prototype]);
3690
3907
  setApiOnPlace(db, [db._allTables, db, db.Transaction.prototype, this._cfg.tables], keys(dbschema), dbschema);
3691
3908
  db._storeNames = keys(dbschema);
3909
+ db._storeNames.forEach(function (tableName) {
3910
+ if (dbschema[tableName].yProps) {
3911
+ db.table(tableName).mapToClass(dbschema[tableName].mappedClass || Object);
3912
+ }
3913
+ });
3692
3914
  return this;
3693
3915
  };
3694
3916
  Version.prototype.upgrade = function (upgradeFunction) {
@@ -3967,19 +4189,29 @@
3967
4189
  }
3968
4190
  }
3969
4191
  function signalSubscribersNow(updatedParts, deleteAffectedCacheEntries) {
4192
+ var e_1, _a;
3970
4193
  if (deleteAffectedCacheEntries === void 0) { deleteAffectedCacheEntries = false; }
3971
4194
  var queriesToSignal = new Set();
3972
4195
  if (updatedParts.all) {
3973
- for (var _i = 0, _a = Object.values(cache); _i < _a.length; _i++) {
3974
- var tblCache = _a[_i];
3975
- collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
4196
+ try {
4197
+ for (var _b = __values(Object.values(cache)), _c = _b.next(); !_c.done; _c = _b.next()) {
4198
+ var tblCache = _c.value;
4199
+ collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
4200
+ }
4201
+ }
4202
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4203
+ finally {
4204
+ try {
4205
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4206
+ }
4207
+ finally { if (e_1) throw e_1.error; }
3976
4208
  }
3977
4209
  }
3978
4210
  else {
3979
4211
  for (var key in updatedParts) {
3980
4212
  var parts = /^idb\:\/\/(.*)\/(.*)\//.exec(key);
3981
4213
  if (parts) {
3982
- var dbName = parts[1], tableName = parts[2];
4214
+ var _d = __read(parts, 3), dbName = _d[1], tableName = _d[2];
3983
4215
  var tblCache = cache["idb://".concat(dbName, "/").concat(tableName)];
3984
4216
  if (tblCache)
3985
4217
  collectTableSubscribers(tblCache, updatedParts, queriesToSignal, deleteAffectedCacheEntries);
@@ -3989,26 +4221,54 @@
3989
4221
  queriesToSignal.forEach(function (requery) { return requery(); });
3990
4222
  }
3991
4223
  function collectTableSubscribers(tblCache, updatedParts, outQueriesToSignal, deleteAffectedCacheEntries) {
4224
+ var e_2, _a, e_3, _b, e_4, _c;
3992
4225
  var updatedEntryLists = [];
3993
- for (var _i = 0, _a = Object.entries(tblCache.queries.query); _i < _a.length; _i++) {
3994
- var _b = _a[_i], indexName = _b[0], entries = _b[1];
3995
- var filteredEntries = [];
3996
- for (var _c = 0, entries_1 = entries; _c < entries_1.length; _c++) {
3997
- var entry = entries_1[_c];
3998
- if (obsSetsOverlap(updatedParts, entry.obsSet)) {
3999
- entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });
4226
+ try {
4227
+ for (var _d = __values(Object.entries(tblCache.queries.query)), _e = _d.next(); !_e.done; _e = _d.next()) {
4228
+ var _f = __read(_e.value, 2), indexName = _f[0], entries = _f[1];
4229
+ var filteredEntries = [];
4230
+ try {
4231
+ for (var entries_1 = (e_3 = void 0, __values(entries)), entries_1_1 = entries_1.next(); !entries_1_1.done; entries_1_1 = entries_1.next()) {
4232
+ var entry = entries_1_1.value;
4233
+ if (obsSetsOverlap(updatedParts, entry.obsSet)) {
4234
+ entry.subscribers.forEach(function (requery) { return outQueriesToSignal.add(requery); });
4235
+ }
4236
+ else if (deleteAffectedCacheEntries) {
4237
+ filteredEntries.push(entry);
4238
+ }
4239
+ }
4000
4240
  }
4001
- else if (deleteAffectedCacheEntries) {
4002
- filteredEntries.push(entry);
4241
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
4242
+ finally {
4243
+ try {
4244
+ if (entries_1_1 && !entries_1_1.done && (_b = entries_1.return)) _b.call(entries_1);
4245
+ }
4246
+ finally { if (e_3) throw e_3.error; }
4003
4247
  }
4248
+ if (deleteAffectedCacheEntries)
4249
+ updatedEntryLists.push([indexName, filteredEntries]);
4250
+ }
4251
+ }
4252
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
4253
+ finally {
4254
+ try {
4255
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
4004
4256
  }
4005
- if (deleteAffectedCacheEntries)
4006
- updatedEntryLists.push([indexName, filteredEntries]);
4257
+ finally { if (e_2) throw e_2.error; }
4007
4258
  }
4008
4259
  if (deleteAffectedCacheEntries) {
4009
- for (var _d = 0, updatedEntryLists_1 = updatedEntryLists; _d < updatedEntryLists_1.length; _d++) {
4010
- var _e = updatedEntryLists_1[_d], indexName = _e[0], filteredEntries = _e[1];
4011
- tblCache.queries.query[indexName] = filteredEntries;
4260
+ try {
4261
+ for (var updatedEntryLists_1 = __values(updatedEntryLists), updatedEntryLists_1_1 = updatedEntryLists_1.next(); !updatedEntryLists_1_1.done; updatedEntryLists_1_1 = updatedEntryLists_1.next()) {
4262
+ var _g = __read(updatedEntryLists_1_1.value, 2), indexName = _g[0], filteredEntries = _g[1];
4263
+ tblCache.queries.query[indexName] = filteredEntries;
4264
+ }
4265
+ }
4266
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
4267
+ finally {
4268
+ try {
4269
+ if (updatedEntryLists_1_1 && !updatedEntryLists_1_1.done && (_c = updatedEntryLists_1.return)) _c.call(updatedEntryLists_1);
4270
+ }
4271
+ finally { if (e_4) throw e_4.error; }
4012
4272
  }
4013
4273
  }
4014
4274
  }
@@ -4259,6 +4519,7 @@
4259
4519
  }
4260
4520
  function createVirtualIndexMiddleware(down) {
4261
4521
  return __assign(__assign({}, down), { table: function (tableName) {
4522
+ var e_1, _a;
4262
4523
  var table = down.table(tableName);
4263
4524
  var schema = table.schema;
4264
4525
  var indexLookup = {};
@@ -4286,9 +4547,18 @@
4286
4547
  }
4287
4548
  var primaryKey = addVirtualIndexes(schema.primaryKey.keyPath, 0, schema.primaryKey);
4288
4549
  indexLookup[":id"] = [primaryKey];
4289
- for (var _i = 0, _a = schema.indexes; _i < _a.length; _i++) {
4290
- var index = _a[_i];
4291
- addVirtualIndexes(index.keyPath, 0, index);
4550
+ try {
4551
+ for (var _b = __values(schema.indexes), _c = _b.next(); !_c.done; _c = _b.next()) {
4552
+ var index = _c.value;
4553
+ addVirtualIndexes(index.keyPath, 0, index);
4554
+ }
4555
+ }
4556
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
4557
+ finally {
4558
+ try {
4559
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
4560
+ }
4561
+ finally { if (e_1) throw e_1.error; }
4292
4562
  }
4293
4563
  function findBestIndex(keyPath) {
4294
4564
  var result = indexLookup[getKeyPathAlias(keyPath)];
@@ -4448,9 +4718,9 @@
4448
4718
  throw new Error("Keys missing");
4449
4719
  req = req.type === 'add' || req.type === 'put' ? __assign(__assign({}, req), { keys: keys }) : __assign({}, req);
4450
4720
  if (req.type !== 'delete')
4451
- req.values = __spreadArray([], req.values, true);
4721
+ req.values = __spreadArray([], __read(req.values), false);
4452
4722
  if (req.keys)
4453
- req.keys = __spreadArray([], req.keys, true);
4723
+ req.keys = __spreadArray([], __read(req.keys), false);
4454
4724
  return getExistingValues(downTable, req, keys).then(function (existingValues) {
4455
4725
  var contexts = keys.map(function (key, i) {
4456
4726
  var existingValue = existingValues[i];
@@ -4639,13 +4909,13 @@
4639
4909
  var pkRangeSet = getRangeSet("");
4640
4910
  var delsRangeSet = getRangeSet(":dels");
4641
4911
  var type = req.type;
4642
- var _a = req.type === "deleteRange"
4912
+ var _a = __read(req.type === "deleteRange"
4643
4913
  ? [req.range]
4644
4914
  : req.type === "delete"
4645
4915
  ? [req.keys]
4646
4916
  : req.values.length < 50
4647
4917
  ? [getEffectiveKeys(primaryKey, req).filter(function (id) { return id; }), req.values]
4648
- : [], keys = _a[0], newObjs = _a[1];
4918
+ : [], 2), keys = _a[0], newObjs = _a[1];
4649
4919
  var oldCache = req.trans["_cache"];
4650
4920
  if (isArray(keys)) {
4651
4921
  pkRangeSet.addKeys(keys);
@@ -4714,7 +4984,7 @@
4714
4984
  };
4715
4985
  var pkRangeSet_1 = getRangeSet("");
4716
4986
  var delsRangeSet_1 = getRangeSet(":dels");
4717
- var _a = readSubscribers[method](req), queriedIndex = _a[0], queriedRanges = _a[1];
4987
+ var _a = __read(readSubscribers[method](req), 2), queriedIndex = _a[0], queriedRanges = _a[1];
4718
4988
  if (method === 'query' && queriedIndex.isPrimaryKey && !req.values) {
4719
4989
  delsRangeSet_1.add(queriedRanges);
4720
4990
  }
@@ -5038,60 +5308,106 @@
5038
5308
  var ac_1 = new AbortController();
5039
5309
  var signal = ac_1.signal;
5040
5310
  var endTransaction = function (wasCommitted) { return function () {
5311
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e;
5041
5312
  ac_1.abort();
5042
5313
  if (mode === 'readwrite') {
5043
5314
  var affectedSubscribers_1 = new Set();
5044
- for (var _i = 0, stores_1 = stores; _i < stores_1.length; _i++) {
5045
- var storeName = stores_1[_i];
5046
- var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)];
5047
- if (tblCache) {
5048
- var table = core.table(storeName);
5049
- var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });
5050
- if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {
5051
- for (var _a = 0, _b = Object.values(tblCache.queries.query); _a < _b.length; _a++) {
5052
- var entries = _b[_a];
5053
- for (var _c = 0, _d = entries.slice(); _c < _d.length; _c++) {
5054
- var entry = _d[_c];
5055
- if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {
5056
- delArrayItem(entries, entry);
5057
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5315
+ try {
5316
+ for (var stores_1 = __values(stores), stores_1_1 = stores_1.next(); !stores_1_1.done; stores_1_1 = stores_1.next()) {
5317
+ var storeName = stores_1_1.value;
5318
+ var tblCache = cache["idb://".concat(dbName, "/").concat(storeName)];
5319
+ if (tblCache) {
5320
+ var table = core.table(storeName);
5321
+ var ops = tblCache.optimisticOps.filter(function (op) { return op.trans === idbtrans; });
5322
+ if (idbtrans._explicit && wasCommitted && idbtrans.mutatedParts) {
5323
+ try {
5324
+ for (var _f = (e_2 = void 0, __values(Object.values(tblCache.queries.query))), _g = _f.next(); !_g.done; _g = _f.next()) {
5325
+ var entries = _g.value;
5326
+ try {
5327
+ for (var _h = (e_3 = void 0, __values(entries.slice())), _j = _h.next(); !_j.done; _j = _h.next()) {
5328
+ var entry = _j.value;
5329
+ if (obsSetsOverlap(entry.obsSet, idbtrans.mutatedParts)) {
5330
+ delArrayItem(entries, entry);
5331
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5332
+ }
5333
+ }
5334
+ }
5335
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
5336
+ finally {
5337
+ try {
5338
+ if (_j && !_j.done && (_c = _h.return)) _c.call(_h);
5339
+ }
5340
+ finally { if (e_3) throw e_3.error; }
5341
+ }
5058
5342
  }
5059
5343
  }
5344
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5345
+ finally {
5346
+ try {
5347
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
5348
+ }
5349
+ finally { if (e_2) throw e_2.error; }
5350
+ }
5060
5351
  }
5061
- }
5062
- else if (ops.length > 0) {
5063
- tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });
5064
- for (var _e = 0, _f = Object.values(tblCache.queries.query); _e < _f.length; _e++) {
5065
- var entries = _f[_e];
5066
- for (var _g = 0, _h = entries.slice(); _g < _h.length; _g++) {
5067
- var entry = _h[_g];
5068
- if (entry.res != null &&
5069
- idbtrans.mutatedParts
5352
+ else if (ops.length > 0) {
5353
+ tblCache.optimisticOps = tblCache.optimisticOps.filter(function (op) { return op.trans !== idbtrans; });
5354
+ try {
5355
+ for (var _k = (e_4 = void 0, __values(Object.values(tblCache.queries.query))), _l = _k.next(); !_l.done; _l = _k.next()) {
5356
+ var entries = _l.value;
5357
+ try {
5358
+ for (var _m = (e_5 = void 0, __values(entries.slice())), _o = _m.next(); !_o.done; _o = _m.next()) {
5359
+ var entry = _o.value;
5360
+ if (entry.res != null &&
5361
+ idbtrans.mutatedParts
5070
5362
  ) {
5071
- if (wasCommitted && !entry.dirty) {
5072
- var freezeResults = Object.isFrozen(entry.res);
5073
- var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);
5074
- if (entry.dirty) {
5075
- delArrayItem(entries, entry);
5076
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5077
- }
5078
- else if (modRes !== entry.res) {
5079
- entry.res = modRes;
5080
- entry.promise = DexiePromise.resolve({ result: modRes });
5363
+ if (wasCommitted && !entry.dirty) {
5364
+ var freezeResults = Object.isFrozen(entry.res);
5365
+ var modRes = applyOptimisticOps(entry.res, entry.req, ops, table, entry, freezeResults);
5366
+ if (entry.dirty) {
5367
+ delArrayItem(entries, entry);
5368
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5369
+ }
5370
+ else if (modRes !== entry.res) {
5371
+ entry.res = modRes;
5372
+ entry.promise = DexiePromise.resolve({ result: modRes });
5373
+ }
5374
+ }
5375
+ else {
5376
+ if (entry.dirty) {
5377
+ delArrayItem(entries, entry);
5378
+ }
5379
+ entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5380
+ }
5381
+ }
5081
5382
  }
5082
5383
  }
5083
- else {
5084
- if (entry.dirty) {
5085
- delArrayItem(entries, entry);
5384
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
5385
+ finally {
5386
+ try {
5387
+ if (_o && !_o.done && (_e = _m.return)) _e.call(_m);
5086
5388
  }
5087
- entry.subscribers.forEach(function (requery) { return affectedSubscribers_1.add(requery); });
5389
+ finally { if (e_5) throw e_5.error; }
5088
5390
  }
5089
5391
  }
5090
5392
  }
5393
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
5394
+ finally {
5395
+ try {
5396
+ if (_l && !_l.done && (_d = _k.return)) _d.call(_k);
5397
+ }
5398
+ finally { if (e_4) throw e_4.error; }
5399
+ }
5091
5400
  }
5092
5401
  }
5093
5402
  }
5094
5403
  }
5404
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5405
+ finally {
5406
+ try {
5407
+ if (stores_1_1 && !stores_1_1.done && (_a = stores_1.return)) _a.call(stores_1);
5408
+ }
5409
+ finally { if (e_1) throw e_1.error; }
5410
+ }
5095
5411
  affectedSubscribers_1.forEach(function (requery) { return requery(); });
5096
5412
  }
5097
5413
  }; };
@@ -5161,7 +5477,7 @@
5161
5477
  return downTable.query(req);
5162
5478
  var freezeResults = ((_a = PSD.trans) === null || _a === void 0 ? void 0 : _a.db._options.cache) === 'immutable';
5163
5479
  var _b = PSD, requery = _b.requery, signal = _b.signal;
5164
- var _c = findCompatibleQuery(dbName, tableName, 'query', req), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];
5480
+ var _c = __read(findCompatibleQuery(dbName, tableName, 'query', req), 4), cacheEntry = _c[0], exactMatch = _c[1], tblCache = _c[2], container = _c[3];
5165
5481
  if (cacheEntry && exactMatch) {
5166
5482
  cacheEntry.obsSet = req.obsSet;
5167
5483
  }
@@ -5235,6 +5551,169 @@
5235
5551
  });
5236
5552
  }
5237
5553
 
5554
+ function compressYDocs(db, interval) {
5555
+ var e_1, _a, e_2, _b;
5556
+ var p = Promise.resolve();
5557
+ try {
5558
+ for (var _c = __values(db.tables), _d = _c.next(); !_d.done; _d = _c.next()) {
5559
+ var table = _d.value;
5560
+ var _loop_1 = function (yProp) {
5561
+ p = p.then(function () { return compressYDocsTable(db, yProp, interval); });
5562
+ };
5563
+ try {
5564
+ for (var _e = (e_2 = void 0, __values(table.schema.yProps || [])), _f = _e.next(); !_f.done; _f = _e.next()) {
5565
+ var yProp = _f.value;
5566
+ _loop_1(yProp);
5567
+ }
5568
+ }
5569
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
5570
+ finally {
5571
+ try {
5572
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
5573
+ }
5574
+ finally { if (e_2) throw e_2.error; }
5575
+ }
5576
+ }
5577
+ }
5578
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
5579
+ finally {
5580
+ try {
5581
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
5582
+ }
5583
+ finally { if (e_1) throw e_1.error; }
5584
+ }
5585
+ return p;
5586
+ }
5587
+ function compressYDocsTable(db, _a, skipIfRunnedSince
5588
+ ) {
5589
+ var updatesTable = _a.updatesTable;
5590
+ var updTbl = db.table(updatesTable);
5591
+ return Promise.all([
5592
+ updTbl
5593
+ .where('i')
5594
+ .startsWith('')
5595
+ .toArray(),
5596
+ db.transaction('rw', updatesTable, function () {
5597
+ return updTbl.get(0).then(function (lastCompressed) {
5598
+ if (lastCompressed &&
5599
+ skipIfRunnedSince &&
5600
+ lastCompressed.lastRun.getTime() > Date.now() - skipIfRunnedSince) {
5601
+ return null;
5602
+ }
5603
+ lastCompressed = lastCompressed || { i: 0, lastCompressed: 0 };
5604
+ return updTbl
5605
+ .put(__assign(__assign({}, lastCompressed), { lastRun: new Date() }))
5606
+ .then(function () { return lastCompressed; });
5607
+ });
5608
+ }),
5609
+ ]).then(function (_a) {
5610
+ var _b = __read(_a, 2), syncers = _b[0], stamp = _b[1];
5611
+ if (!stamp)
5612
+ return;
5613
+ var lastCompressedUpdate = stamp.lastCompressed;
5614
+ var unsyncedFrom = Math.min.apply(Math, __spreadArray([], __read(syncers.map(function (s) { return Math.min(s.unsentFrom || Infinity, s.receivedUntil != null ? s.receivedUntil + 1 : Infinity); })), false));
5615
+ return updTbl
5616
+ .where('i')
5617
+ .between(lastCompressedUpdate, Infinity, false)
5618
+ .toArray(function (addedUpdates) {
5619
+ var e_3, _a;
5620
+ if (addedUpdates.length <= 1)
5621
+ return;
5622
+ var docsToCompress = [];
5623
+ var lastUpdateToCompress = lastCompressedUpdate + 1;
5624
+ var _loop_2 = function (j) {
5625
+ var updateRow = addedUpdates[j];
5626
+ var i = updateRow.i, f = updateRow.f, k = updateRow.k;
5627
+ if (i >= unsyncedFrom && (f & 0x01))
5628
+ return "break";
5629
+ var entry = docsToCompress.find(function (entry) { return cmp(entry.docId, k) === 0; });
5630
+ if (entry)
5631
+ entry.updates.push(updateRow);
5632
+ else
5633
+ docsToCompress.push({ docId: k, updates: [updateRow] });
5634
+ lastUpdateToCompress = i;
5635
+ };
5636
+ for (var j = 0; j < addedUpdates.length; ++j) {
5637
+ var state_1 = _loop_2(j);
5638
+ if (state_1 === "break")
5639
+ break;
5640
+ }
5641
+ var p = Promise.resolve();
5642
+ var _loop_3 = function (docId, updates) {
5643
+ p = p.then(function () { return compressUpdatesForDoc(db, updatesTable, docId, updates); });
5644
+ };
5645
+ try {
5646
+ for (var docsToCompress_1 = __values(docsToCompress), docsToCompress_1_1 = docsToCompress_1.next(); !docsToCompress_1_1.done; docsToCompress_1_1 = docsToCompress_1.next()) {
5647
+ var _b = docsToCompress_1_1.value, docId = _b.docId, updates = _b.updates;
5648
+ _loop_3(docId, updates);
5649
+ }
5650
+ }
5651
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
5652
+ finally {
5653
+ try {
5654
+ if (docsToCompress_1_1 && !docsToCompress_1_1.done && (_a = docsToCompress_1.return)) _a.call(docsToCompress_1);
5655
+ }
5656
+ finally { if (e_3) throw e_3.error; }
5657
+ }
5658
+ return p.then(function () {
5659
+ return db.transaction('rw', updTbl, function () {
5660
+ return updTbl.get(0).then(function (current) {
5661
+ return updTbl.put(__assign(__assign({}, current), { lastCompressed: Math.max(lastUpdateToCompress, (current === null || current === void 0 ? void 0 : current.lastCompressed) || 0) }));
5662
+ });
5663
+ });
5664
+ });
5665
+ });
5666
+ });
5667
+ }
5668
+ function compressUpdatesForDoc(db, updatesTable, parentId, addedUpdatesToCompress) {
5669
+ if (addedUpdatesToCompress.length < 1)
5670
+ throw new Error('Invalid input');
5671
+ return db.transaction('rw', updatesTable, function (tx) {
5672
+ var updTbl = tx.table(updatesTable);
5673
+ return updTbl.where({ k: parentId }).first(function (mainUpdate) {
5674
+ var updates = [mainUpdate].concat(addedUpdatesToCompress);
5675
+ var Y = getYLibrary(db);
5676
+ var doc = new Y.Doc({ gc: true });
5677
+ updates.forEach(function (update) {
5678
+ Y.applyUpdateV2(doc, update.u);
5679
+ });
5680
+ var compressedUpdate = Y.encodeStateAsUpdateV2(doc);
5681
+ var lastUpdate = updates.pop();
5682
+ return updTbl
5683
+ .put({
5684
+ i: lastUpdate.i,
5685
+ k: parentId,
5686
+ u: compressedUpdate,
5687
+ })
5688
+ .then(function () { return updTbl.bulkDelete(updates.map(function (update) { return update.i; })); });
5689
+ });
5690
+ });
5691
+ }
5692
+
5693
+ var INTERVAL = 10000;
5694
+ function periodicGC(db) {
5695
+ var timer = null;
5696
+ db.on('ready', function (db) {
5697
+ if (db.tables.some(function (tbl) { return tbl.schema.yProps; })) {
5698
+ var gc_1 = function () {
5699
+ if (!db.isOpen())
5700
+ return;
5701
+ compressYDocs(db, INTERVAL).catch(function (err) {
5702
+ console.debug('Error during periodic GC', err);
5703
+ }).then(function () {
5704
+ timer = setTimeout(gc_1, INTERVAL);
5705
+ });
5706
+ };
5707
+ timer = setTimeout(gc_1, INTERVAL);
5708
+ }
5709
+ }, true);
5710
+ db.on('close', function () {
5711
+ if (timer)
5712
+ clearTimeout(timer);
5713
+ timer = null;
5714
+ });
5715
+ }
5716
+
5238
5717
  var Dexie$1 = (function () {
5239
5718
  function Dexie(name, options) {
5240
5719
  var _this = this;
@@ -5276,7 +5755,18 @@
5276
5755
  });
5277
5756
  this._state = state;
5278
5757
  this.name = name;
5279
- this.on = Events(this, "populate", "blocked", "versionchange", "close", { ready: [promisableChain, nop] });
5758
+ this.on = Events(this, "populate", "blocked", "versionchange", "close", "y", { ready: [promisableChain, nop] });
5759
+ this.once = function (event, callback) {
5760
+ var fn = function () {
5761
+ var args = [];
5762
+ for (var _i = 0; _i < arguments.length; _i++) {
5763
+ args[_i] = arguments[_i];
5764
+ }
5765
+ _this.on(event).unsubscribe(fn);
5766
+ callback.apply(_this, args);
5767
+ };
5768
+ return _this.on(event, fn);
5769
+ };
5280
5770
  this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {
5281
5771
  return function (subscriber, bSticky) {
5282
5772
  Dexie.vip(function () {
@@ -5355,6 +5845,8 @@
5355
5845
  }
5356
5846
  });
5357
5847
  this.vip = vipDB;
5848
+ if (options === null || options === void 0 ? void 0 : options.Y)
5849
+ periodicGC(this);
5358
5850
  addons.forEach(function (addon) { return addon(_this); });
5359
5851
  }
5360
5852
  Dexie.prototype.version = function (versionNumber) {
@@ -5417,6 +5909,7 @@
5417
5909
  function () { return dexieOpen(_this); });
5418
5910
  };
5419
5911
  Dexie.prototype._close = function () {
5912
+ this.on.close.fire(new CustomEvent('close'));
5420
5913
  var state = this._state;
5421
5914
  var idx = connections.indexOf(this);
5422
5915
  if (idx >= 0)
@@ -5574,6 +6067,9 @@
5574
6067
  }
5575
6068
  return this._allTables[tableName];
5576
6069
  };
6070
+ Dexie.prototype.gc = function () {
6071
+ return compressYDocs(this);
6072
+ };
5577
6073
  return Dexie;
5578
6074
  }());
5579
6075
 
@@ -5874,6 +6370,174 @@
5874
6370
  return new PropModification({ replacePrefix: [a, b] });
5875
6371
  }
5876
6372
 
6373
+ function observeYDocUpdates(provider, doc, db, parentTableName, updatesTableName, parentId, Y) {
6374
+ var lastUpdateId = 0;
6375
+ var initial = true;
6376
+ var subscription = liveQuery(function () {
6377
+ throwIfDestroyed(doc);
6378
+ var updatesTable = db.table(updatesTableName);
6379
+ return Promise.all([
6380
+ (lastUpdateId > 0
6381
+ ? updatesTable
6382
+ .where('i')
6383
+ .between(lastUpdateId, Infinity, false)
6384
+ .toArray()
6385
+ .then(function (updates) {
6386
+ return updates.filter(function (update) { return cmp(update.k, parentId) === 0; });
6387
+ })
6388
+ : updatesTable.where({ k: parentId }).toArray()).then(function (updates) {
6389
+ if (updates.length > 0)
6390
+ lastUpdateId = updates[updates.length - 1].i;
6391
+ return updates;
6392
+ }),
6393
+ db.table(parentTableName).where(':id').equals(parentId).toArray(),
6394
+ ]);
6395
+ }).subscribe(function (_a) {
6396
+ var _b = __read(_a, 2), updates = _b[0], parentRow = _b[1];
6397
+ if (parentRow.length === 0) {
6398
+ doc.destroy();
6399
+ return;
6400
+ }
6401
+ throwIfDestroyed(doc);
6402
+ if (updates.length > 0) {
6403
+ Y.transact(doc, function () {
6404
+ updates.forEach(function (update) {
6405
+ try {
6406
+ DexieYProvider.currentUpdateRow = update;
6407
+ Y.applyUpdateV2(doc, update.u);
6408
+ }
6409
+ finally {
6410
+ DexieYProvider.currentUpdateRow = null;
6411
+ }
6412
+ });
6413
+ }, provider, false);
6414
+ }
6415
+ if (initial) {
6416
+ initial = false;
6417
+ doc.emit('load', [doc]);
6418
+ }
6419
+ }, function (error) {
6420
+ provider.on('error').fire(error);
6421
+ });
6422
+ var onUpdate = function (update, origin) {
6423
+ if (origin === provider)
6424
+ return;
6425
+ db.table(updatesTableName)
6426
+ .add({
6427
+ k: parentId,
6428
+ u: update,
6429
+ f: 1,
6430
+ })
6431
+ .then(function (i) {
6432
+ if (i === lastUpdateId - 1)
6433
+ ++lastUpdateId;
6434
+ })
6435
+ .catch(function (error) {
6436
+ provider.on('error').fire(error);
6437
+ });
6438
+ };
6439
+ var stopObserving = function () {
6440
+ subscription.unsubscribe();
6441
+ doc.off('updateV2', onUpdate);
6442
+ doc.off('destroy', stopObserving);
6443
+ };
6444
+ doc.on('updateV2', onUpdate);
6445
+ doc.on('destroy', stopObserving);
6446
+ return stopObserving;
6447
+ }
6448
+
6449
+ var wm = new WeakMap();
6450
+ function createEvents() {
6451
+ return Events(null, 'load', 'sync', 'error');
6452
+ }
6453
+ var DexieYProvider = (function () {
6454
+ function DexieYProvider(doc) {
6455
+ var _this = this;
6456
+ this.refCount = 1;
6457
+ this.cleanupHandlers = [];
6458
+ this.destroyed = false;
6459
+ var _a = (doc || {}).meta, db = _a.db, parentTable = _a.parentTable, parentId = _a.parentId, updatesTable = _a.updatesTable;
6460
+ if (!db || !parentTable || !updatesTable)
6461
+ throw new Error('Y.Doc not generated by Dexie');
6462
+ if (!db.table(parentTable) || !db.table(updatesTable)) {
6463
+ throw new Error("Table ".concat(parentTable, " or ").concat(updatesTable, " not found in db"));
6464
+ }
6465
+ throwIfDestroyed(doc);
6466
+ var Y = getYLibrary(db);
6467
+ this.on = createEvents();
6468
+ this.doc = doc;
6469
+ this.off = function (name, f) { var _a; return (_a = _this.on[name]) === null || _a === void 0 ? void 0 : _a.unsubscribe(f); };
6470
+ this.whenLoaded = new Promise(function (resolve, reject) {
6471
+ _this.on('load', resolve);
6472
+ _this.on('error', reject);
6473
+ });
6474
+ this.whenSynced = new Promise(function (resolve, reject) {
6475
+ _this.on('sync', resolve);
6476
+ _this.on('error', reject);
6477
+ });
6478
+ if ('dispose' in Symbol) {
6479
+ this[Symbol.dispose] = this.dispose;
6480
+ }
6481
+ this.stopObserving = observeYDocUpdates(this, doc, db, parentTable, updatesTable, parentId, Y);
6482
+ doc.on('load', function () { return _this.on('load').fire(); });
6483
+ doc.on('sync', function (sync) { return sync !== false && _this.on('sync').fire(); });
6484
+ doc.on('destroy', this.destroy.bind(this));
6485
+ db.on.y.fire(this, Y);
6486
+ }
6487
+ DexieYProvider.load = function (doc) {
6488
+ var p = wm.get(doc);
6489
+ if (p) {
6490
+ ++p.refCount;
6491
+ }
6492
+ else {
6493
+ p = new DexieYProvider(doc);
6494
+ wm.set(doc, p);
6495
+ }
6496
+ return p;
6497
+ };
6498
+ DexieYProvider.release = function (doc, options) {
6499
+ if (destroyedDocs.has(doc))
6500
+ return;
6501
+ var p = wm.get(doc);
6502
+ if (!p) {
6503
+ if (--p.refCount === 0) {
6504
+ if (isNaN(options === null || options === void 0 ? void 0 : options.gracePeriod)) {
6505
+ doc.destroy();
6506
+ }
6507
+ else {
6508
+ setTimeout(function () { return p.refCount || doc.destroy(); },
6509
+ options.gracePeriod
6510
+ );
6511
+ }
6512
+ }
6513
+ }
6514
+ else {
6515
+ doc.destroy();
6516
+ }
6517
+ };
6518
+ DexieYProvider.for = function (doc) {
6519
+ return wm.get(doc);
6520
+ };
6521
+ DexieYProvider.prototype.destroy = function () {
6522
+ var _a;
6523
+ wm.delete(this.doc);
6524
+ this.doc = null;
6525
+ this.destroyed = true;
6526
+ this.refCount = 0;
6527
+ (_a = this.stopObserving) === null || _a === void 0 ? void 0 : _a.call(this);
6528
+ this.on = createEvents();
6529
+ this.cleanupHandlers.forEach(function (cleanup) { return cleanup(); });
6530
+ };
6531
+ DexieYProvider.prototype.addCleanupHandler = function (cleanupHandler) {
6532
+ this.cleanupHandlers.push(typeof cleanupHandler === 'function'
6533
+ ? cleanupHandler
6534
+ : function () { return cleanupHandler.unsubscribe(); });
6535
+ };
6536
+ DexieYProvider.getDocCache = getDocCache;
6537
+ DexieYProvider.currentUpdateRow = null;
6538
+ return DexieYProvider;
6539
+ }());
6540
+
5877
6541
  DexiePromise.rejectionMapper = mapError;
5878
6542
  setDebug(debug);
5879
6543
 
@@ -5891,7 +6555,8 @@
5891
6555
  'default': Dexie$1,
5892
6556
  RangeSet: RangeSet,
5893
6557
  mergeRanges: mergeRanges,
5894
- rangesOverlap: rangesOverlap
6558
+ rangesOverlap: rangesOverlap,
6559
+ DexieYProvider: DexieYProvider
5895
6560
  });
5896
6561
 
5897
6562
  __assign(Dexie$1, namedExports, { default: Dexie$1 });