fake-indexeddb 6.2.3 → 6.2.5

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/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # fake-indexeddb
2
2
 
3
- ![Build Status](https://github.com/dumbmatter/fakeIndexedDB/actions/workflows/test.yml/badge.svg)
4
- ![GitHub Repo stars](https://img.shields.io/github/stars/dumbmatter/fakeIndexedDB)
5
- ![GitHub](https://img.shields.io/github/license/dumbmatter/fakeIndexedDB)
6
- ![npm](https://img.shields.io/npm/v/fake-indexeddb)
7
- ![npm](https://img.shields.io/npm/dm/fake-indexeddb)
3
+ [![Build Status](https://github.com/dumbmatter/fakeIndexedDB/actions/workflows/test.yml/badge.svg)](https://github.com/dumbmatter/fakeIndexedDB/actions/workflows/test.yml)
4
+ [![GitHub Repo stars](https://img.shields.io/github/stars/dumbmatter/fakeIndexedDB)](https://github.com/dumbmatter/fakeIndexedDB)
5
+ [![GitHub](https://img.shields.io/github/license/dumbmatter/fakeIndexedDB)](https://github.com/dumbmatter/fakeIndexedDB)
6
+ [![npm](https://img.shields.io/npm/v/fake-indexeddb)](https://www.npmjs.com/package/fake-indexeddb)
7
+ [![npm](https://img.shields.io/npm/dm/fake-indexeddb)](https://www.npmjs.com/package/fake-indexeddb)
8
8
 
9
9
  A pure JS in-memory implementation of [the IndexedDB API](https://w3c.github.io/IndexedDB/). Its main use is testing IndexedDB-dependent code in Node.js.
10
10
 
@@ -204,19 +204,27 @@ import "fake-indexeddb/auto";
204
204
 
205
205
  ## Quality
206
206
 
207
- Here's a comparison of fake-indexeddb and real browser IndexedDB implementations on [the W3C IndexedDB test suite](https://github.com/w3c/web-platform-tests/tree/master/IndexedDB) as of March 18, 2019:
207
+ Here's a comparison of fake-indexeddb and real browser IndexedDB implementations on [the Web Platform Tests IndexedDB suite](https://wpt.fyi/results/IndexedDB) as of <!-- last_updated_date_start -->November 7, 2025<!-- last_updated_date_end -->:
208
208
 
209
- | Implementation | Percentage of files that pass completely |
210
- | -------------------- | ---------------------------------------- |
211
- | Chrome 73 | 99% |
212
- | Firefox 65 | 97% |
213
- | Safari 12 | 92% |
214
- | fake-indexeddb 3.0.0 | 87% |
215
- | Edge 18 | 61% |
209
+ <!-- DO NOT MANUALLY OVERWRITE THE TABLE BELOW! -->
210
+ <!-- To update the results, run `pnpm run update-wpt-results` -->
211
+ <!-- wpt_results_start -->
212
+ <!-- wpt_results_total=1653 -->
213
+ | Implementation | Version | Passed | % |
214
+ | --- | --- | --- | --- |
215
+ | Chrome | 144.0.7514.0 | 1651 | 99.9% |
216
+ | Firefox | 146.0a1 | 1498 | 90.6% |
217
+ | Safari | 231 preview | 1497 | 90.6% |
218
+ | Ladybird | 1.0-cde3941d9f | 1426 | 86.3% |
219
+ | fake-indexeddb | 6.2.5 | 1369 | 82.8% |
220
+ <!-- wpt_results_end -->
216
221
 
217
- For browsers, I ran http://w3c-test.org/tools/runner/index.html and counted the passes. For fake-indexeddb, I ran `npm run test-w3c`.
222
+ Keep in mind that these tests include a lot of edge cases (such as rare error conditions), so even hitting ~40% likely means that the core IndexedDB functionality is covered. Your app will probably work fine.
218
223
 
219
- 87% is pretty good, right? Especially considering that fake-indexeddb runs in Node.js where failure is guaranteed for tests involving browser APIs like Web Workers. There are definitley still some weak points of fake-indexeddb, most of which are described in `src/test/web-platform-tests/run-all.js`. Your app will probably run fine, though.
224
+ Also note that, for a fair comparison with browsers, these results omit some tests that aren't relevant to Node.js such as web workers and cross-origin isolation. When testing fake-indexeddb, some polyfills are used to simulate a browser environment, such as `File` and `location`.
225
+
226
+ > [!NOTE]
227
+ > To see how these test results are generated, see [`update-browser-wpt-results.js`](./bin/update-browser-wpt-results.js) and [`run-all.js`](./src/test/web-platform-tests/run-all.js).
220
228
 
221
229
  ## Potential applications:
222
230
 
package/auto/index.js CHANGED
@@ -29,7 +29,7 @@ var globalVar =
29
29
  const createPropertyDescriptor = (value) => {
30
30
  return {
31
31
  value,
32
- enumerable: true,
32
+ enumerable: false,
33
33
  configurable: true,
34
34
  writable: true,
35
35
  };
package/auto/index.mjs CHANGED
@@ -29,7 +29,7 @@ var globalVar =
29
29
  const createPropertyDescriptor = (value) => {
30
30
  return {
31
31
  value,
32
- enumerable: true,
32
+ enumerable: false,
33
33
  configurable: true,
34
34
  writable: true,
35
35
  };
@@ -10,6 +10,7 @@ var _cmp = _interopRequireDefault(require("./lib/cmp.js"));
10
10
  var _errors = require("./lib/errors.js");
11
11
  var _extractKey = _interopRequireDefault(require("./lib/extractKey.js"));
12
12
  var _valueToKey = _interopRequireDefault(require("./lib/valueToKey.js"));
13
+ var _cloneValueForInsertion = require("./lib/cloneValueForInsertion.js");
13
14
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
14
15
  const getEffectiveObjectStore = cursor => {
15
16
  if (cursor.source instanceof _FDBObjectStore.default) {
@@ -305,7 +306,7 @@ class FDBCursor {
305
306
  if (!this._gotValue || !Object.hasOwn(this, "value")) {
306
307
  throw new _errors.InvalidStateError();
307
308
  }
308
- const clone = structuredClone(value);
309
+ const clone = (0, _cloneValueForInsertion.cloneValueForInsertion)(value, transaction);
309
310
  if (effectiveObjectStore.keyPath !== null) {
310
311
  let tempKey;
311
312
  try {
@@ -12,19 +12,21 @@ var _ObjectStore = _interopRequireDefault(require("./lib/ObjectStore.js"));
12
12
  var _validateKeyPath = _interopRequireDefault(require("./lib/validateKeyPath.js"));
13
13
  var _closeConnection = _interopRequireDefault(require("./lib/closeConnection.js"));
14
14
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
+ // Common first 3 steps of https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-createobjectstore and https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore
15
16
  const confirmActiveVersionchangeTransaction = database => {
16
- if (!database._runningVersionchangeTransaction) {
17
- throw new _errors.InvalidStateError();
17
+ // Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise.
18
+ let transaction;
19
+ if (database._runningVersionchangeTransaction) {
20
+ // Find the latest versionchange transaction
21
+ transaction = database._rawDatabase.transactions.findLast(tx => {
22
+ return tx.mode === "versionchange";
23
+ });
18
24
  }
19
-
20
- // Find the latest versionchange transaction
21
- const transactions = database._rawDatabase.transactions.filter(tx => {
22
- return tx.mode === "versionchange";
23
- });
24
- const transaction = transactions[transactions.length - 1];
25
- if (!transaction || transaction._state === "finished") {
25
+ if (!transaction) {
26
26
  throw new _errors.InvalidStateError();
27
27
  }
28
+
29
+ // If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
28
30
  if (transaction._state !== "active") {
29
31
  throw new _errors.TransactionInactiveError();
30
32
  }
@@ -62,43 +64,66 @@ class FDBDatabase extends _FakeEventTarget.default {
62
64
  if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) {
63
65
  throw new _errors.InvalidAccessError();
64
66
  }
67
+
68
+ // Save for rollbackLog
65
69
  const objectStoreNames = [...this.objectStoreNames];
66
- transaction._rollbackLog.push(() => {
67
- const objectStore = this._rawDatabase.rawObjectStores.get(name);
68
- if (objectStore) {
69
- objectStore.deleted = true;
70
- }
71
- this.objectStoreNames = new _FakeDOMStringList.default(...objectStoreNames);
72
- transaction._scope.delete(name);
73
- this._rawDatabase.rawObjectStores.delete(name);
74
- });
70
+ const transactionObjectStoreNames = [...transaction.objectStoreNames];
75
71
  const rawObjectStore = new _ObjectStore.default(this._rawDatabase, name, keyPath, autoIncrement);
76
72
  this.objectStoreNames._push(name);
77
73
  this.objectStoreNames._sort();
78
74
  transaction._scope.add(name);
75
+ transaction._createdObjectStores.add(rawObjectStore);
79
76
  this._rawDatabase.rawObjectStores.set(name, rawObjectStore);
80
77
  transaction.objectStoreNames = new _FakeDOMStringList.default(...this.objectStoreNames);
78
+ transaction._rollbackLog.push(() => {
79
+ rawObjectStore.deleted = true;
80
+ this.objectStoreNames = new _FakeDOMStringList.default(...objectStoreNames);
81
+ transaction.objectStoreNames = new _FakeDOMStringList.default(...transactionObjectStoreNames);
82
+ transaction._scope.delete(rawObjectStore.name);
83
+ this._rawDatabase.rawObjectStores.delete(rawObjectStore.name);
84
+ });
81
85
  return transaction.objectStore(name);
82
86
  }
87
+
88
+ // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore
83
89
  deleteObjectStore(name) {
84
90
  if (name === undefined) {
85
91
  throw new TypeError();
86
92
  }
87
93
  const transaction = confirmActiveVersionchangeTransaction(this);
94
+
95
+ // Let store be the object store named name in database, or throw a "NotFoundError" DOMException if none.
88
96
  const store = this._rawDatabase.rawObjectStores.get(name);
89
97
  if (store === undefined) {
90
98
  throw new _errors.NotFoundError();
91
99
  }
100
+
101
+ // Remove store from this’s object store set.
102
+ // This method synchronously modifies the objectStoreNames property on the IDBDatabase instance on which it was called.
92
103
  this.objectStoreNames = new _FakeDOMStringList.default(...Array.from(this.objectStoreNames).filter(objectStoreName => {
93
104
  return objectStoreName !== name;
94
105
  }));
95
106
  transaction.objectStoreNames = new _FakeDOMStringList.default(...this.objectStoreNames);
107
+
108
+ // If there is an object store handle associated with store and transaction, remove all entries from its index set.
109
+ const objectStore = transaction._objectStoresCache.get(name);
110
+ let prevIndexNames;
111
+ if (objectStore) {
112
+ prevIndexNames = [...objectStore.indexNames];
113
+ objectStore.indexNames = new _FakeDOMStringList.default();
114
+ }
96
115
  transaction._rollbackLog.push(() => {
97
116
  store.deleted = false;
98
- this._rawDatabase.rawObjectStores.set(name, store);
99
- this.objectStoreNames._push(name);
117
+ this._rawDatabase.rawObjectStores.set(store.name, store);
118
+ this.objectStoreNames._push(store.name);
119
+ transaction.objectStoreNames._push(store.name);
100
120
  this.objectStoreNames._sort();
121
+ if (objectStore && prevIndexNames) {
122
+ objectStore.indexNames = new _FakeDOMStringList.default(...prevIndexNames);
123
+ }
101
124
  });
125
+
126
+ // Destroy store.
102
127
  store.deleted = true;
103
128
  this._rawDatabase.rawObjectStores.delete(name);
104
129
  transaction._objectStoresCache.delete(name);
@@ -13,6 +13,7 @@ var _enforceRange = _interopRequireDefault(require("./lib/enforceRange.js"));
13
13
  var _errors = require("./lib/errors.js");
14
14
  var _FakeEvent = _interopRequireDefault(require("./lib/FakeEvent.js"));
15
15
  var _scheduling = require("./lib/scheduling.js");
16
+ var _validateRequiredArguments = require("./lib/validateRequiredArguments.js");
16
17
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
17
18
  // https://w3c.github.io/IndexedDB/#connection-queue
18
19
  const runTaskInConnectionQueue = (connectionQueues, name, task) => {
@@ -220,26 +221,28 @@ const runVersionchangeTransaction = (connection, version, request, cb) => {
220
221
  } else {
221
222
  (0, _scheduling.queueTask)(concludeUpgrade);
222
223
  }
223
- transaction.addEventListener("error", () => {
224
+ transaction._prioritizedListeners.set("error", () => {
224
225
  connection._runningVersionchangeTransaction = false;
225
226
  connection._oldVersion = undefined;
226
227
  // throw arguments[0].target.error;
227
228
  // console.log("error in versionchange transaction - not sure if anything needs to be done here", e.target.error.name);
228
229
  });
229
- transaction.addEventListener("abort", () => {
230
+ transaction._prioritizedListeners.set("abort", () => {
230
231
  connection._runningVersionchangeTransaction = false;
231
232
  connection._oldVersion = undefined;
232
- request.transaction = null;
233
233
  (0, _scheduling.queueTask)(() => {
234
+ // Reset transaction in a tick after onabort (upgrade-transaction-lifecycle-user-aborted.any)
235
+ request.transaction = null;
234
236
  cb(new _errors.AbortError());
235
237
  });
236
238
  });
237
- transaction.addEventListener("complete", () => {
239
+ transaction._prioritizedListeners.set("complete", () => {
238
240
  connection._runningVersionchangeTransaction = false;
239
241
  connection._oldVersion = undefined;
240
- request.transaction = null;
241
242
  // Let other complete event handlers run before continuing
242
243
  (0, _scheduling.queueTask)(() => {
244
+ // Reset transaction in a tick after oncomplete (upgrade-transaction-lifecycle-committed.any.js)
245
+ request.transaction = null;
243
246
  if (connection._closePending) {
244
247
  cb(new _errors.AbortError());
245
248
  } else {
@@ -305,13 +308,19 @@ const openDatabase = (databases, connectionQueues, name, version, request, cb) =
305
308
  runTaskInConnectionQueue(connectionQueues, name, openDBTask);
306
309
  };
307
310
  class FDBFactory {
308
- cmp = _cmp.default;
309
311
  _databases = new Map();
310
312
  // https://w3c.github.io/IndexedDB/#connection-queue
311
313
  _connectionQueues = new Map(); // promise chain as lightweight FIFO task queue
312
314
 
315
+ // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp
316
+ cmp(first, second) {
317
+ (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 2, "IDBFactory.cmp");
318
+ return (0, _cmp.default)(first, second);
319
+ }
320
+
313
321
  // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase
314
322
  deleteDatabase(name) {
323
+ (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 1, "IDBFactory.deleteDatabase");
315
324
  const request = new _FDBOpenDBRequest.default();
316
325
  request.source = null;
317
326
  (0, _scheduling.queueTask)(() => {
@@ -341,6 +350,7 @@ class FDBFactory {
341
350
 
342
351
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version
343
352
  open(name, version) {
353
+ (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 1, "IDBFactory.open");
344
354
  if (arguments.length > 1 && version !== undefined) {
345
355
  // Based on spec, not sure why "MAX_SAFE_INTEGER" instead of "unsigned long long", but it's needed to pass
346
356
  // tests
@@ -70,15 +70,19 @@ class FDBIndex {
70
70
  const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName);
71
71
  return index && !index.deleted;
72
72
  }).sort());
73
- transaction._rollbackLog.push(() => {
74
- this._name = oldName;
75
- this._rawIndex.name = oldName;
76
- this.objectStore._indexesCache.delete(name);
77
- this.objectStore._indexesCache.set(oldName, this);
78
- this.objectStore._rawObjectStore.rawIndexes.delete(name);
79
- this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex);
80
- this.objectStore.indexNames = new _FakeDOMStringList.default(...oldIndexNames);
81
- });
73
+
74
+ // https://www.w3.org/TR/IndexedDB/#abort-an-upgrade-transaction - "If handle’s index was not newly created during transaction, set handle’s name to its index’s name."
75
+ if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) {
76
+ transaction._rollbackLog.push(() => {
77
+ this._name = oldName;
78
+ this._rawIndex.name = oldName;
79
+ this.objectStore._indexesCache.delete(name);
80
+ this.objectStore._indexesCache.set(oldName, this);
81
+ this.objectStore._rawObjectStore.rawIndexes.delete(name);
82
+ this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex);
83
+ this.objectStore.indexNames = new _FakeDOMStringList.default(...oldIndexNames);
84
+ });
85
+ }
82
86
  }
83
87
 
84
88
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction
@@ -20,6 +20,7 @@ var _valueToKeyRange = _interopRequireDefault(require("./lib/valueToKeyRange.js"
20
20
  var _getKeyPath = require("./lib/getKeyPath.js");
21
21
  var _extractGetAllOptions = _interopRequireDefault(require("./lib/extractGetAllOptions.js"));
22
22
  var _enforceRange = _interopRequireDefault(require("./lib/enforceRange.js"));
23
+ var _cloneValueForInsertion = require("./lib/cloneValueForInsertion.js");
23
24
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
24
25
  const confirmActiveTransaction = objectStore => {
25
26
  if (objectStore._rawObjectStore.deleted) {
@@ -39,7 +40,7 @@ const buildRecordAddPut = (objectStore, value, key) => {
39
40
  throw new _errors.DataError();
40
41
  }
41
42
  }
42
- const clone = structuredClone(value);
43
+ const clone = (0, _cloneValueForInsertion.cloneValueForInsertion)(value, objectStore.transaction);
43
44
  if (objectStore.keyPath !== null) {
44
45
  const tempKey = (0, _extractKey.default)(objectStore.keyPath, clone);
45
46
  if (tempKey.type === "found") {
@@ -110,17 +111,21 @@ class FDBObjectStore {
110
111
  this.transaction._scope.delete(oldName);
111
112
  transaction._scope.add(name);
112
113
  transaction.objectStoreNames = new _FakeDOMStringList.default(...Array.from(transaction._scope).sort());
113
- transaction._rollbackLog.push(() => {
114
- this._name = oldName;
115
- this._rawObjectStore.name = oldName;
116
- this.transaction._objectStoresCache.delete(name);
117
- this.transaction._objectStoresCache.set(oldName, this);
118
- this._rawObjectStore.rawDatabase.rawObjectStores.delete(name);
119
- this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore);
120
- transaction.db.objectStoreNames = new _FakeDOMStringList.default(...oldObjectStoreNames);
121
- transaction._scope = oldScope;
122
- transaction.objectStoreNames = new _FakeDOMStringList.default(...oldTransactionObjectStoreNames);
123
- });
114
+
115
+ // https://www.w3.org/TR/IndexedDB/#abort-an-upgrade-transaction - "If handle’s object store was not newly created during transaction, set handle’s name to its object store’s name."
116
+ if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) {
117
+ transaction._rollbackLog.push(() => {
118
+ this._name = oldName;
119
+ this._rawObjectStore.name = oldName;
120
+ this.transaction._objectStoresCache.delete(name);
121
+ this.transaction._objectStoresCache.set(oldName, this);
122
+ this._rawObjectStore.rawDatabase.rawObjectStores.delete(name);
123
+ this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore);
124
+ transaction.db.objectStoreNames = new _FakeDOMStringList.default(...oldObjectStoreNames);
125
+ transaction._scope = oldScope;
126
+ transaction.objectStoreNames = new _FakeDOMStringList.default(...oldTransactionObjectStoreNames);
127
+ });
128
+ }
124
129
  }
125
130
  put(value, key) {
126
131
  if (arguments.length === 0) {
@@ -306,21 +311,20 @@ class FDBObjectStore {
306
311
  // create and return an IDBIndex object. Instead the implementation must queue up an operation to abort the
307
312
  // "versionchange" transaction which was used for the createIndex call.
308
313
 
314
+ // Save for rollbackLog
309
315
  const indexNames = [...this.indexNames];
310
- this.transaction._rollbackLog.push(() => {
311
- const index2 = this._rawObjectStore.rawIndexes.get(name);
312
- if (index2) {
313
- index2.deleted = true;
314
- }
315
- this.indexNames = new _FakeDOMStringList.default(...indexNames);
316
- this._rawObjectStore.rawIndexes.delete(name);
317
- });
318
316
  const index = new _Index.default(this._rawObjectStore, name, keyPath, multiEntry, unique);
319
317
  this.indexNames._push(name);
320
318
  this.indexNames._sort();
319
+ this.transaction._createdIndexes.add(index);
321
320
  this._rawObjectStore.rawIndexes.set(name, index);
322
321
  index.initialize(this.transaction); // This is async by design
323
322
 
323
+ this.transaction._rollbackLog.push(() => {
324
+ index.deleted = true;
325
+ this.indexNames = new _FakeDOMStringList.default(...indexNames);
326
+ this._rawObjectStore.rawIndexes.delete(index.name);
327
+ });
324
328
  return new _FDBIndex.default(this, index);
325
329
  }
326
330
 
@@ -358,8 +362,8 @@ class FDBObjectStore {
358
362
  }
359
363
  this.transaction._rollbackLog.push(() => {
360
364
  rawIndex.deleted = false;
361
- this._rawObjectStore.rawIndexes.set(name, rawIndex);
362
- this.indexNames._push(name);
365
+ this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex);
366
+ this.indexNames._push(rawIndex.name);
363
367
  this.indexNames._sort();
364
368
  });
365
369
  this.indexNames = new _FakeDOMStringList.default(...Array.from(this.indexNames).filter(indexName => {
@@ -12,6 +12,7 @@ var _FakeEvent = _interopRequireDefault(require("./lib/FakeEvent.js"));
12
12
  var _FakeEventTarget = _interopRequireDefault(require("./lib/FakeEventTarget.js"));
13
13
  var _scheduling = require("./lib/scheduling.js");
14
14
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
+ const prioritizedListenerTypes = ["error", "abort", "complete"];
15
16
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#transaction
16
17
  class FDBTransaction extends _FakeEventTarget.default {
17
18
  _state = "active";
@@ -23,7 +24,10 @@ class FDBTransaction extends _FakeEventTarget.default {
23
24
  onabort = null;
24
25
  oncomplete = null;
25
26
  onerror = null;
27
+ _prioritizedListeners = new Map();
26
28
  _requests = [];
29
+ _createdIndexes = new Set();
30
+ _createdObjectStores = new Set();
27
31
  constructor(storeNames, mode, durability, db) {
28
32
  super();
29
33
  this._scope = new Set(storeNames);
@@ -31,6 +35,14 @@ class FDBTransaction extends _FakeEventTarget.default {
31
35
  this.durability = durability;
32
36
  this.db = db;
33
37
  this.objectStoreNames = new _FakeDOMStringList.default(...Array.from(this._scope).sort());
38
+ for (const type of prioritizedListenerTypes) {
39
+ // Attach prioritized (internal) listeners before any external listeners are attached.
40
+ // This ensures that these listeners run with the same timing regardless of whether
41
+ // the user uses `on*` or `addEventListener` for event listeners.
42
+ this.addEventListener(type, () => {
43
+ this._prioritizedListeners.get(type)?.();
44
+ });
45
+ }
34
46
  }
35
47
 
36
48
  // https://w3c.github.io/IndexedDB/#abort-transaction
@@ -23,8 +23,10 @@ class Database {
23
23
 
24
24
  // The next transaction to run is the first waiting one that doesn't overlap with either a running one or a
25
25
  // preceding waiting one. This allows non-overlapping transactions to run in parallel.
26
+ // The exception is readonly transactions, which are allowed to run in parallel with other readonly
27
+ // transactions, even with overlapping scopes, since no data is being modified.
26
28
  const next = waiting.find((transaction, i) => {
27
- const anyRunning = running.some(other => (0, _intersection.intersection)(other._scope, transaction._scope).size > 0);
29
+ const anyRunning = running.some(other => !(transaction.mode === "readonly" && other.mode === "readonly") && (0, _intersection.intersection)(other._scope, transaction._scope).size > 0);
28
30
  if (anyRunning) {
29
31
  return false;
30
32
  }
@@ -32,6 +34,8 @@ class Database {
32
34
  // If any _preceding_ waiting transactions are blocked, then that's also blocking.
33
35
  // E.g. if you have 3 transactions: [a], [a,b], and [b,c], then [a] blocks [a,b] which blocks [b,c]
34
36
  // until [a] is complete, even though [a] and [b,c] share no overlap.
37
+ // Note that readonly transactions do not have to be handled as a special case here,
38
+ // because if any transactions with overlapping scopes are blocked, then we can assume they are
35
39
  const anyWaiting = waiting.slice(0, i).some(other => (0, _intersection.intersection)(other._scope, transaction._scope).size > 0);
36
40
  return !anyWaiting;
37
41
  });
@@ -13,8 +13,9 @@ const stopped = (event, listener) => {
13
13
  const invokeEventListeners = (event, obj) => {
14
14
  event.currentTarget = obj;
15
15
  const errors = [];
16
- const invoke = callback => {
16
+ const invoke = callbackOrObject => {
17
17
  try {
18
+ const callback = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent;
18
19
  // @ts-expect-error EventCallback's types are not quite right here
19
20
  callback.call(event.currentTarget, event);
20
21
  } catch (err) {
@@ -68,14 +69,16 @@ class FakeEventTarget {
68
69
 
69
70
  // These will be overridden in individual subclasses and made not readonly
70
71
 
71
- addEventListener(type, callback, capture = false) {
72
+ addEventListener(type, callback, options) {
73
+ const capture = !!(typeof options === "object" && options ? options.capture : options);
72
74
  this.listeners.push({
73
75
  callback,
74
76
  capture,
75
77
  type
76
78
  });
77
79
  }
78
- removeEventListener(type, callback, capture = false) {
80
+ removeEventListener(type, callback, options) {
81
+ const capture = !!(typeof options === "object" && options ? options.capture : options);
79
82
  const i = this.listeners.findIndex(listener => {
80
83
  return listener.type === type && listener.callback === callback && listener.capture === capture;
81
84
  });
@@ -89,14 +89,22 @@ class ObjectStore {
89
89
  newRecord.key = key;
90
90
  }
91
91
  }
92
+ const rollbackLogForThisOperation = [];
92
93
  if (this.keyGenerator !== null && newRecord.key === undefined) {
94
+ let rolledBack = false;
95
+ const keyGeneratorBefore = this.keyGenerator.num;
96
+ const rollbackKeyGenerator = () => {
97
+ if (rolledBack) {
98
+ return;
99
+ }
100
+ rolledBack = true;
101
+ if (this.keyGenerator) {
102
+ this.keyGenerator.num = keyGeneratorBefore;
103
+ }
104
+ };
105
+ rollbackLogForThisOperation.push(rollbackKeyGenerator);
93
106
  if (rollbackLog) {
94
- const keyGeneratorBefore = this.keyGenerator.num;
95
- rollbackLog.push(() => {
96
- if (this.keyGenerator) {
97
- this.keyGenerator.num = keyGeneratorBefore;
98
- }
99
- });
107
+ rollbackLog.push(rollbackKeyGenerator);
100
108
  }
101
109
  newRecord.key = this.keyGenerator.next();
102
110
 
@@ -119,28 +127,50 @@ class ObjectStore {
119
127
  identifier = remainingKeyPath.slice(0, i);
120
128
  remainingKeyPath = remainingKeyPath.slice(i + 1);
121
129
  if (!Object.hasOwn(object, identifier)) {
122
- object[identifier] = {};
130
+ // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`)
131
+ // Equivalent to `object[identifier] = ...` without using `Object.prototype`
132
+ Object.defineProperty(object, identifier, {
133
+ configurable: true,
134
+ enumerable: true,
135
+ writable: true,
136
+ value: {}
137
+ });
123
138
  }
124
139
  object = object[identifier];
125
140
  }
126
141
  }
127
142
  identifier = remainingKeyPath;
128
- object[identifier] = newRecord.key;
143
+
144
+ // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`)
145
+ // Equivalent to `object[identifier] = ...` without using `Object.prototype`
146
+ Object.defineProperty(object, identifier, {
147
+ configurable: true,
148
+ enumerable: true,
149
+ writable: true,
150
+ value: newRecord.key
151
+ });
129
152
  }
130
153
  } else if (this.keyGenerator !== null && typeof newRecord.key === "number") {
131
154
  this.keyGenerator.setIfLarger(newRecord.key);
132
155
  }
133
156
  const existingRecord = this.records.put(newRecord, noOverwrite);
157
+ let rolledBack = false;
158
+ const rollbackStoreRecord = () => {
159
+ if (rolledBack) {
160
+ return;
161
+ }
162
+ rolledBack = true;
163
+ if (existingRecord) {
164
+ // overwrite on rollback
165
+ this.storeRecord(existingRecord, false);
166
+ } else {
167
+ // delete on rollback
168
+ this.deleteRecord(newRecord.key);
169
+ }
170
+ };
171
+ rollbackLogForThisOperation.push(rollbackStoreRecord);
134
172
  if (rollbackLog) {
135
- rollbackLog.push(() => {
136
- if (existingRecord) {
137
- // overwrite on rollback
138
- this.storeRecord(existingRecord, false);
139
- } else {
140
- // delete on rollback
141
- this.deleteRecord(newRecord.key);
142
- }
143
- });
173
+ rollbackLog.push(rollbackStoreRecord);
144
174
  }
145
175
 
146
176
  // Delete existing indexes
@@ -151,10 +181,20 @@ class ObjectStore {
151
181
  }
152
182
 
153
183
  // Update indexes
154
- for (const rawIndex of this.rawIndexes.values()) {
155
- if (rawIndex.initialized) {
156
- rawIndex.storeRecord(newRecord);
184
+ try {
185
+ for (const rawIndex of this.rawIndexes.values()) {
186
+ if (rawIndex.initialized) {
187
+ rawIndex.storeRecord(newRecord);
188
+ }
189
+ }
190
+ } catch (err) {
191
+ // If this request fails here and preventDefault is used to stop the transaction from aborting, we need to roll back the addition of this record to the store, otherwise it will be present in subsequent requests on this transaction. Same for key generator.
192
+ if (err.name === "ConstraintError") {
193
+ for (const rollback of rollbackLogForThisOperation) {
194
+ rollback();
195
+ }
157
196
  }
197
+ throw err;
158
198
  }
159
199
  return newRecord.key;
160
200
  }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.cloneValueForInsertion = cloneValueForInsertion;
7
+ // https://w3c.github.io/IndexedDB/#clone-value
8
+ // Note that we only need to call this during insertions because the spec does not expect any cloning during retrieval,
9
+ // only `StructuredDeserialize()` (e.g. see [1]). This is also only required for values, not keys, since keys do not
10
+ // require cloning during insertion (e.g. see [2]).
11
+ // [1]: https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store
12
+ // [2]: https://w3c.github.io/IndexedDB/#add-or-put
13
+ function cloneValueForInsertion(value, transaction) {
14
+ // Assert: transaction’s state is active.
15
+ if (transaction._state !== "active") {
16
+ throw new Error("Assert: transaction state is active");
17
+ }
18
+
19
+ // Set transaction’s state to inactive.
20
+ transaction._state = "inactive";
21
+ try {
22
+ // Let serialized be StructuredSerializeForStorage(value).
23
+ // Let clone be ? StructuredDeserialize(serialized, targetRealm).
24
+ // Return clone.
25
+ return structuredClone(value);
26
+ } finally {
27
+ // Set transaction’s state to active.
28
+ transaction._state = "active";
29
+ }
30
+ }
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.validateRequiredArguments = validateRequiredArguments;
7
+ // WebIDL requires passing the right number of non-optional arguments, e.g. IDBFactory.open() must have at least 1 arg
8
+ function validateRequiredArguments(numArguments, expectedNumArguments, methodName) {
9
+ if (numArguments < expectedNumArguments) {
10
+ // imitate Firefox's error message
11
+ throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} ` + `required, but only ${arguments.length} passed`);
12
+ }
13
+ }