fake-indexeddb 6.1.0 → 6.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,308 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _cmp = _interopRequireDefault(require("./cmp.js"));
8
+ var _FDBKeyRange = _interopRequireDefault(require("../FDBKeyRange.js"));
9
+ var _errors = require("./errors.js");
10
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
11
+ // what fraction of the total number of nodes are allowed to be deleted tombstones?
12
+ const MAX_TOMBSTONE_FACTOR = 2 / 3;
13
+ const EVERYTHING_KEY_RANGE = new _FDBKeyRange.default(undefined, undefined, false, false);
14
+ /**
15
+ * Simple red-black binary tree with some aspects of a scapegoat tree. The main goal here is simplicity of
16
+ * implementation, tailored to the needs of IndexedDB.
17
+ *
18
+ * Basically this implements a [red-black tree][1] for insertions, but uses the much simpler [scapegoat tree][2]
19
+ * strategy for deletions. Deletions are a simple matter of rebuilding the tree from scratch if more than 2/3 of the
20
+ * tree is full of deleted (tombstone) markers.
21
+ *
22
+ * [1]: https://en.wikipedia.org/wiki/Red%E2%80%93black_tree
23
+ * [2]: https://en.wikipedia.org/wiki/Scapegoat_tree
24
+ */
25
+ class BinarySearchTree {
26
+ _numTombstones = 0;
27
+ _numNodes = 0;
28
+
29
+ /**
30
+ *
31
+ * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when
32
+ * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used
33
+ * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting)
34
+ */
35
+ constructor(keysAreUnique) {
36
+ this._keysAreUnique = !!keysAreUnique;
37
+ }
38
+ size() {
39
+ return this._numNodes - this._numTombstones;
40
+ }
41
+ get(record) {
42
+ return this._getByComparator(this._root, otherRecord => this._compare(record, otherRecord));
43
+ }
44
+ contains(record) {
45
+ return !!this.get(record);
46
+ }
47
+ _compare(a, b) {
48
+ const keyComparison = (0, _cmp.default)(a.key, b.key);
49
+ if (keyComparison !== 0) {
50
+ return keyComparison;
51
+ }
52
+ // if keys are unique, then we can (and must) avoid comparing the values, since they may be non-comparable
53
+ // (e.g. in the case of an ObjectStore, they are record objects)
54
+ return this._keysAreUnique ? 0 : (0, _cmp.default)(a.value, b.value);
55
+ }
56
+ _getByComparator(node, comparator) {
57
+ let current = node;
58
+ while (current) {
59
+ const comparison = comparator(current.record);
60
+ if (comparison < 0) {
61
+ current = current.left;
62
+ } else if (comparison > 0) {
63
+ current = current.right;
64
+ } else {
65
+ return current.record;
66
+ }
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Put a new record, and return the overwritten record if an overwrite occurred.
72
+ * @param record
73
+ * @param noOverwrite - throw a ConstraintError in case of overwrite
74
+ */
75
+ put(record, noOverwrite = false) {
76
+ if (!this._root) {
77
+ this._root = {
78
+ record,
79
+ left: undefined,
80
+ right: undefined,
81
+ parent: undefined,
82
+ deleted: false,
83
+ // the root is always black in a red-black tree
84
+ red: false
85
+ };
86
+ this._numNodes++;
87
+ return;
88
+ }
89
+ return this._put(this._root, record, noOverwrite);
90
+ }
91
+ _put(node, record, noOverwrite) {
92
+ const comparison = this._compare(record, node.record);
93
+ if (comparison < 0) {
94
+ if (node.left) {
95
+ return this._put(node.left, record, noOverwrite);
96
+ } else {
97
+ node.left = {
98
+ record,
99
+ left: undefined,
100
+ right: undefined,
101
+ parent: node,
102
+ deleted: false,
103
+ red: true
104
+ };
105
+ this._onNewNodeInserted(node.left);
106
+ }
107
+ } else if (comparison > 0) {
108
+ if (node.right) {
109
+ return this._put(node.right, record, noOverwrite);
110
+ } else {
111
+ node.right = {
112
+ record,
113
+ left: undefined,
114
+ right: undefined,
115
+ parent: node,
116
+ deleted: false,
117
+ red: true
118
+ };
119
+ this._onNewNodeInserted(node.right);
120
+ }
121
+ } else if (node.deleted) {
122
+ // undelete
123
+ node.deleted = false;
124
+ node.record = record;
125
+ this._numTombstones--;
126
+ } else if (noOverwrite) {
127
+ // replace not allowed in case of noOverwrite
128
+ throw new _errors.ConstraintError();
129
+ } else {
130
+ // replace, don't add, so no need to increment. return the overwritten record
131
+ const overwrittenRecord = node.record;
132
+ node.record = record;
133
+ return overwrittenRecord;
134
+ }
135
+ }
136
+ delete(record) {
137
+ if (!this._root) {
138
+ return;
139
+ }
140
+ this._delete(this._root, record);
141
+ if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) {
142
+ // to keep the implementation simple, and because most users of fake-indexeddb are not going to be deleting
143
+ // a lot of nodes, just rebuild the whole tree (defragment) if the tree is too full of tombstones,
144
+ // as inspired by the scapegoat tree: https://en.wikipedia.org/wiki/Scapegoat_tree#Deletion
145
+ const records = [...this.getAllRecords()];
146
+ this._root = this._rebuild(records, undefined, false);
147
+ this._numNodes = records.length;
148
+ this._numTombstones = 0;
149
+ }
150
+ }
151
+ _delete(node, record) {
152
+ if (!node) {
153
+ return;
154
+ }
155
+ const comparison = this._compare(record, node.record);
156
+ if (comparison < 0) {
157
+ this._delete(node.left, record);
158
+ } else if (comparison > 0) {
159
+ this._delete(node.right, record);
160
+ } else if (!node.deleted) {
161
+ this._numTombstones++;
162
+ node.deleted = true;
163
+ }
164
+ }
165
+ *getAllRecords(descending = false) {
166
+ yield* this.getRecords(EVERYTHING_KEY_RANGE, descending);
167
+ }
168
+ *getRecords(keyRange, descending = false) {
169
+ yield* this._getRecordsForNode(this._root, keyRange, descending);
170
+ }
171
+ *_getRecordsForNode(node, keyRange, descending = false) {
172
+ if (!node) {
173
+ return;
174
+ }
175
+ yield* this._findRecords(node, keyRange, descending);
176
+ }
177
+ *_findRecords(node, keyRange, descending = false) {
178
+ const {
179
+ lower,
180
+ upper,
181
+ lowerOpen,
182
+ upperOpen
183
+ } = keyRange;
184
+ const {
185
+ record: {
186
+ key
187
+ }
188
+ } = node;
189
+ const lowerComparison = lower === undefined ? -1 : (0, _cmp.default)(lower, key);
190
+ const upperComparison = upper === undefined ? 1 : (0, _cmp.default)(upper, key);
191
+
192
+ // if keys are non-unique then we need to go left/right even for equality
193
+ // else we can just do LT/GT rather than LTE/GTE as a slight optimization
194
+ const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0;
195
+ const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0;
196
+
197
+ // in descending mode we start with rightmost nodes, else leftmost
198
+ const moreStart = descending ? moreRight : moreLeft;
199
+ const moreEnd = descending ? moreLeft : moreRight;
200
+ const start = descending ? "right" : "left";
201
+ const end = descending ? "left" : "right";
202
+
203
+ // does the current record actually match the key range?
204
+ const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0;
205
+ const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0;
206
+ if (moreStart && node[start]) {
207
+ yield* this._findRecords(node[start], keyRange, descending);
208
+ }
209
+ if (lowerMatches && upperMatches && !node.deleted) {
210
+ yield node.record;
211
+ }
212
+ if (moreEnd && node[end]) {
213
+ yield* this._findRecords(node[end], keyRange, descending);
214
+ }
215
+ }
216
+ _onNewNodeInserted(newNode) {
217
+ this._numNodes++;
218
+ this._rebalanceTree(newNode);
219
+ }
220
+
221
+ // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion
222
+ _rebalanceTree(node) {
223
+ let parent = node.parent;
224
+ do {
225
+ // case 1 - no red/black violation
226
+ if (!parent.red) {
227
+ return;
228
+ }
229
+ const grandparent = parent.parent;
230
+ if (!grandparent) {
231
+ // case #4 - parent is the red root, node is also red, so parent goes black
232
+ parent.red = false;
233
+ return;
234
+ }
235
+ const parentIsRightChild = parent === grandparent.right;
236
+ const uncle = parentIsRightChild ? grandparent.left : grandparent.right;
237
+ if (!uncle || !uncle.red) {
238
+ if (node === (parentIsRightChild ? parent.left : parent.right)) {
239
+ // case #5 - parent is red but uncle is black
240
+ this._rotateSubtree(parent, parentIsRightChild);
241
+ node = parent;
242
+ parent = parentIsRightChild ? grandparent.right : grandparent.left;
243
+ }
244
+
245
+ // case #6 - node is "outer" grandchild of grandparent
246
+ this._rotateSubtree(grandparent, !parentIsRightChild);
247
+ parent.red = false;
248
+ grandparent.red = true;
249
+ return;
250
+ }
251
+
252
+ // case #2 - parent and uncle are both red, so both of them go black and grandparent goes red
253
+ parent.red = false;
254
+ uncle.red = false;
255
+ grandparent.red = true;
256
+ node = grandparent;
257
+ } while (node.parent ? parent = node.parent : false);
258
+
259
+ // case #3 - current node is the root, all constraints satisfied
260
+ }
261
+
262
+ // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation
263
+ _rotateSubtree(node, right) {
264
+ const parent = node.parent;
265
+ const newRoot = right ? node.left : node.right; // opposite direction
266
+ const newChild = right ? newRoot.right : newRoot.left;
267
+ node[right ? "left" : "right"] = newChild;
268
+ if (newChild) {
269
+ newChild.parent = node;
270
+ }
271
+ newRoot[right ? "right" : "left"] = node;
272
+ newRoot.parent = parent;
273
+ node.parent = newRoot;
274
+ if (parent) {
275
+ parent[node === parent.right ? "right" : "left"] = newRoot;
276
+ } else {
277
+ this._root = newRoot;
278
+ }
279
+ return newRoot;
280
+ }
281
+
282
+ // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating
283
+ _rebuild(records, parent, red) {
284
+ const {
285
+ length
286
+ } = records;
287
+ if (!length) {
288
+ return undefined;
289
+ }
290
+ const mid = length >>> 1; // like Math.floor(records.length / 2) but fast
291
+
292
+ const node = {
293
+ record: records[mid],
294
+ left: undefined,
295
+ right: undefined,
296
+ parent,
297
+ deleted: false,
298
+ red
299
+ };
300
+ const left = this._rebuild(records.slice(0, mid), node, !red);
301
+ const right = this._rebuild(records.slice(mid + 1), node, !red);
302
+ node.left = left;
303
+ node.right = right;
304
+ return node;
305
+ }
306
+ }
307
+ exports.default = BinarySearchTree;
308
+ module.exports = exports.default;
@@ -42,7 +42,10 @@ const extractKey = (keyPath, value) => {
42
42
  identifier = remainingKeyPath;
43
43
  remainingKeyPath = null;
44
44
  }
45
- if (object === undefined || object === null || !Object.hasOwn(object, identifier)) {
45
+
46
+ // special cases: https://w3c.github.io/IndexedDB/#evaluate-a-key-path-on-a-value
47
+ const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File;
48
+ if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) {
46
49
  return {
47
50
  type: "notFound"
48
51
  };
@@ -23,6 +23,16 @@ function getSetImmediateFromJsdom() {
23
23
  }
24
24
  }
25
25
 
26
+ // waiting on this PR for typescript types: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1249
27
+
28
+ // 'user-blocking' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping
29
+ const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn, {
30
+ priority: "user-blocking"
31
+ }));
32
+
33
+ // fallback for environments that don't support any of the above
34
+ const doSetTimeout = fn => setTimeout(fn, 0);
35
+
26
36
  // Schedules a task to run later. Use Node.js's setImmediate if available and
27
37
  // setTimeout otherwise. Note that options like process.nextTick or
28
38
  // queueMicrotask will likely not work: IndexedDB semantics require that
@@ -30,7 +40,7 @@ function getSetImmediateFromJsdom() {
30
40
  // tick queue and microtask queue run within the current event loop macrotask,
31
41
  // so they'd process database operations too quickly.
32
42
  const queueTask = fn => {
33
- const setImmediate = globalThis.setImmediate || getSetImmediateFromJsdom() || (fn => setTimeout(fn, 0));
43
+ const setImmediate = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout;
34
44
  setImmediate(fn);
35
45
  };
36
46
  exports.queueTask = queueTask;
@@ -5,6 +5,7 @@ import FakeEventTarget from "./lib/FakeEventTarget.js";
5
5
  import ObjectStore from "./lib/ObjectStore.js";
6
6
  import { queueTask } from "./lib/scheduling.js";
7
7
  import validateKeyPath from "./lib/validateKeyPath.js";
8
+ import FakeEvent from "./lib/FakeEvent.js";
8
9
  const confirmActiveVersionchangeTransaction = database => {
9
10
  if (!database._runningVersionchangeTransaction) {
10
11
  throw new InvalidStateError();
@@ -25,7 +26,7 @@ const confirmActiveVersionchangeTransaction = database => {
25
26
  };
26
27
 
27
28
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#database-closing-steps
28
- const closeConnection = connection => {
29
+ export const closeConnection = (connection, forced = false) => {
29
30
  connection._closePending = true;
30
31
  const transactionsComplete = connection._rawDatabase.transactions.every(transaction => {
31
32
  return transaction._state === "finished";
@@ -35,9 +36,17 @@ const closeConnection = connection => {
35
36
  connection._rawDatabase.connections = connection._rawDatabase.connections.filter(otherConnection => {
36
37
  return connection !== otherConnection;
37
38
  });
39
+ if (forced) {
40
+ const event = new FakeEvent("close", {
41
+ bubbles: false,
42
+ cancelable: false
43
+ });
44
+ event.eventPath = [];
45
+ connection.dispatchEvent(event);
46
+ }
38
47
  } else {
39
48
  queueTask(() => {
40
- closeConnection(connection);
49
+ closeConnection(connection, forced);
41
50
  });
42
51
  }
43
52
  };
@@ -114,7 +123,7 @@ class FDBDatabase extends FakeEventTarget {
114
123
  this._rawDatabase.rawObjectStores.delete(name);
115
124
  transaction._objectStoresCache.delete(name);
116
125
  }
117
- transaction(storeNames, mode) {
126
+ transaction(storeNames, mode, options) {
118
127
  mode = mode !== undefined ? mode : "readonly";
119
128
  if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") {
120
129
  throw new TypeError("Invalid mode: " + mode);
@@ -139,7 +148,16 @@ class FDBDatabase extends FakeEventTarget {
139
148
  throw new NotFoundError("No objectStore named " + storeName + " in this database");
140
149
  }
141
150
  }
142
- const tx = new FDBTransaction(storeNames, mode, this);
151
+
152
+ // the actual algo is more complex but this passes the IDB tests: https://webidl.spec.whatwg.org/#es-dictionary
153
+ const durability = options?.durability ?? "default";
154
+ // invalid enums throw a TypeError: https://webidl.spec.whatwg.org/#es-enumeration
155
+ if (durability !== "default" && durability !== "strict" && durability !== "relaxed") {
156
+ throw new TypeError(
157
+ // based on Firefox's error message
158
+ `'${durability}' (value of 'durability' member of IDBTransactionOptions) ` + `is not a valid value for enumeration IDBTransactionDurability`);
159
+ }
160
+ const tx = new FDBTransaction(storeNames, mode, durability, this);
143
161
  this._rawDatabase.transactions.push(tx);
144
162
  this._rawDatabase.processTransactions(); // See if can start right away (async)
145
163
 
@@ -16,10 +16,11 @@ class FDBTransaction extends FakeEventTarget {
16
16
  oncomplete = null;
17
17
  onerror = null;
18
18
  _requests = [];
19
- constructor(storeNames, mode, db) {
19
+ constructor(storeNames, mode, durability, db) {
20
20
  super();
21
21
  this._scope = new Set(storeNames);
22
22
  this.mode = mode;
23
+ this.durability = durability;
23
24
  this.db = db;
24
25
  this.objectStoreNames = new FakeDOMStringList(...Array.from(this._scope).sort());
25
26
  }
@@ -0,0 +1,22 @@
1
+ import { closeConnection } from "./FDBDatabase.js";
2
+
3
+ /**
4
+ * Forcibly closes a database. This simulates a database being closed due to abnormal reasons, such as
5
+ * using DevTools to clear data while a database is open. Spec-wise, this is equivalent to
6
+ * [closing a database connection](https://www.w3.org/TR/IndexedDB/#closing-connection) with the `forced flag`
7
+ * set to true.
8
+ *
9
+ * Use this API if you want to have more test coverage for unusual IndexedDB events, such as a database firing
10
+ * the "close" event:
11
+ *
12
+ * ```js
13
+ * db.addEventListener("close", () => {
14
+ * console.log("Forcibly closed!");
15
+ * });
16
+ * forceCloseDatabase(db); // invokes the event listener
17
+ * ```
18
+ * @param db
19
+ */
20
+ export default function forceCloseDatabase(db) {
21
+ closeConnection(db, true);
22
+ }
@@ -12,4 +12,5 @@ export { default as IDBOpenDBRequest } from "./FDBOpenDBRequest.js";
12
12
  export { default as IDBRecord } from "./FDBRecord.js";
13
13
  export { default as IDBRequest } from "./FDBRequest.js";
14
14
  export { default as IDBTransaction } from "./FDBTransaction.js";
15
- export { default as IDBVersionChangeEvent } from "./FDBVersionChangeEvent.js";
15
+ export { default as IDBVersionChangeEvent } from "./FDBVersionChangeEvent.js";
16
+ export { default as forceCloseDatabase } from "./forceCloseDatabase.js";
@@ -21,6 +21,7 @@ const invokeEventListeners = (event, obj) => {
21
21
  const typeToProp = {
22
22
  abort: "onabort",
23
23
  blocked: "onblocked",
24
+ close: "onclose",
24
25
  complete: "oncomplete",
25
26
  error: "onerror",
26
27
  success: "onsuccess",
@@ -10,13 +10,13 @@ class Index {
10
10
  // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a
11
11
  // constraint
12
12
  initialized = false;
13
- records = new RecordStore();
14
13
  constructor(rawObjectStore, name, keyPath, multiEntry, unique) {
15
14
  this.rawObjectStore = rawObjectStore;
16
15
  this.name = name;
17
16
  this.keyPath = keyPath;
18
17
  this.multiEntry = multiEntry;
19
18
  this.unique = unique;
19
+ this.records = new RecordStore(unique);
20
20
  }
21
21
 
22
22
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index
@@ -127,13 +127,13 @@ class Index {
127
127
  }
128
128
  }
129
129
  if (!this.multiEntry || !Array.isArray(indexKey)) {
130
- this.records.add({
130
+ this.records.put({
131
131
  key: indexKey,
132
132
  value: newRecord.key
133
133
  });
134
134
  } else {
135
135
  for (const individualIndexKey of indexKey) {
136
- this.records.add({
136
+ this.records.put({
137
137
  key: individualIndexKey,
138
138
  value: newRecord.key
139
139
  });
@@ -1,4 +1,4 @@
1
- import { ConstraintError, DataError } from "./errors.js";
1
+ import { DataError } from "./errors.js";
2
2
  import extractKey from "./extractKey.js";
3
3
  import KeyGenerator from "./KeyGenerator.js";
4
4
  import RecordStore from "./RecordStore.js";
@@ -7,7 +7,7 @@ import FDBRecord from "../FDBRecord.js";
7
7
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-object-store
8
8
  class ObjectStore {
9
9
  deleted = false;
10
- records = new RecordStore();
10
+ records = new RecordStore(true);
11
11
  rawIndexes = new Map();
12
12
  constructor(rawDatabase, name, keyPath, autoIncrement) {
13
13
  this.rawDatabase = rawDatabase;
@@ -124,20 +124,26 @@ class ObjectStore {
124
124
  } else if (this.keyGenerator !== null && typeof newRecord.key === "number") {
125
125
  this.keyGenerator.setIfLarger(newRecord.key);
126
126
  }
127
- const existingRecord = this.records.get(newRecord.key);
128
- if (existingRecord) {
129
- if (noOverwrite) {
130
- throw new ConstraintError();
131
- }
132
- this.deleteRecord(newRecord.key, rollbackLog);
133
- }
134
- this.records.add(newRecord);
127
+ const existingRecord = this.records.put(newRecord, noOverwrite);
135
128
  if (rollbackLog) {
136
129
  rollbackLog.push(() => {
137
- this.deleteRecord(newRecord.key);
130
+ if (existingRecord) {
131
+ // overwrite on rollback
132
+ this.storeRecord(existingRecord, false);
133
+ } else {
134
+ // delete on rollback
135
+ this.deleteRecord(newRecord.key);
136
+ }
138
137
  });
139
138
  }
140
139
 
140
+ // Delete existing indexes
141
+ if (existingRecord) {
142
+ for (const rawIndex of this.rawIndexes.values()) {
143
+ rawIndex.records.deleteByValue(newRecord.key);
144
+ }
145
+ }
146
+
141
147
  // Update indexes
142
148
  for (const rawIndex of this.rawIndexes.values()) {
143
149
  if (rawIndex.initialized) {
@@ -177,6 +183,10 @@ class ObjectStore {
177
183
  }
178
184
  }
179
185
  count(range) {
186
+ // optimization: if there is no range, or if the range is everything, then we can just count the total size
187
+ if (range === undefined || range.lower === undefined && range.upper === undefined) {
188
+ return this.records.size();
189
+ }
180
190
  let count = 0;
181
191
 
182
192
  // eslint-disable-next-line @typescript-eslint/no-unused-vars