fake-indexeddb 6.2.3 → 6.2.4

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 -->October 16, 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=1651 -->
213
+ | Implementation | Version | Passed | % |
214
+ | --- | --- | --- | --- |
215
+ | Chrome | 143.0.7476.0 | 1651 | 100% |
216
+ | Firefox | 146.0a1 | 1498 | 90.7% |
217
+ | Safari | 230 preview | 1498 | 90.7% |
218
+ | Ladybird | 1.0-62c00712fa | 772 | 46.8% |
219
+ | fake-indexeddb | 6.2.4 | 1368 | 82.9% |
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) => {
@@ -305,13 +306,19 @@ const openDatabase = (databases, connectionQueues, name, version, request, cb) =
305
306
  runTaskInConnectionQueue(connectionQueues, name, openDBTask);
306
307
  };
307
308
  class FDBFactory {
308
- cmp = _cmp.default;
309
309
  _databases = new Map();
310
310
  // https://w3c.github.io/IndexedDB/#connection-queue
311
311
  _connectionQueues = new Map(); // promise chain as lightweight FIFO task queue
312
312
 
313
+ // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp
314
+ cmp(first, second) {
315
+ (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 2, "IDBFactory.cmp");
316
+ return (0, _cmp.default)(first, second);
317
+ }
318
+
313
319
  // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase
314
320
  deleteDatabase(name) {
321
+ (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 1, "IDBFactory.deleteDatabase");
315
322
  const request = new _FDBOpenDBRequest.default();
316
323
  request.source = null;
317
324
  (0, _scheduling.queueTask)(() => {
@@ -341,6 +348,7 @@ class FDBFactory {
341
348
 
342
349
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version
343
350
  open(name, version) {
351
+ (0, _validateRequiredArguments.validateRequiredArguments)(arguments.length, 1, "IDBFactory.open");
344
352
  if (arguments.length > 1 && version !== undefined) {
345
353
  // Based on spec, not sure why "MAX_SAFE_INTEGER" instead of "unsigned long long", but it's needed to pass
346
354
  // 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 => {
@@ -24,6 +24,8 @@ class FDBTransaction extends _FakeEventTarget.default {
24
24
  oncomplete = null;
25
25
  onerror = null;
26
26
  _requests = [];
27
+ _createdIndexes = new Set();
28
+ _createdObjectStores = new Set();
27
29
  constructor(storeNames, mode, durability, db) {
28
30
  super();
29
31
  this._scope = new Set(storeNames);
@@ -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
  });
@@ -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
+ }
@@ -58,20 +58,40 @@ const valueToKeyWithoutThrowing = (input, seen) => {
58
58
  return INVALID_VALUE;
59
59
  }
60
60
  seen.add(input);
61
- const keys = [];
62
- for (let i = 0; i < input.length; i++) {
61
+
62
+ // This algorithm is tricky to account for `bindings-inject-keys-bypass.any.js`. We _should_ return early when
63
+ // encountering an invalid key/type, but we also need to avoid triggering `Object.prototype['10']` if it's been
64
+ // overridden. One simple way to do this (and which doesn't rely on sparse arrays or other exotic solutions that
65
+ // could cause de-opts) is to use `Array.from()` with a mapper function, which does not trigger the prototype
66
+ // setter [1]. It does prevent an early return, but we can at least short-circuit inside the mapper function
67
+ // (which isn't strictly necessary to pass the WPTs, but is closer to the spec).
68
+ // [1]: See https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from, specifically
69
+ // the chain CreateDataPropertyOrThrow -> CreateDataProperty -> DefineOwnProperty which defines
70
+ // the array element as an "own" property.
71
+ let hasInvalid = false;
72
+ const keys = Array.from({
73
+ length: input.length
74
+ }, (_, i) => {
75
+ if (hasInvalid) {
76
+ return;
77
+ }
63
78
  const hop = Object.hasOwn(input, i);
64
79
  if (!hop) {
65
80
  // If hop is false, return "invalid value".
66
- return INVALID_VALUE;
81
+ hasInvalid = true;
82
+ return;
67
83
  }
68
84
  const entry = input[i];
69
85
  const key = valueToKeyWithoutThrowing(entry, seen);
70
86
  // If key is "invalid value" or "invalid type" abort these steps and return "invalid value".
71
87
  if (key === INVALID_VALUE || key === INVALID_TYPE) {
72
- return INVALID_VALUE;
88
+ hasInvalid = true;
89
+ return;
73
90
  }
74
- keys.push(key);
91
+ return key;
92
+ });
93
+ if (hasInvalid) {
94
+ return INVALID_VALUE;
75
95
  }
76
96
  return keys;
77
97
  } else {
@@ -4,6 +4,7 @@ import cmp from "./lib/cmp.js";
4
4
  import { DataError, InvalidAccessError, InvalidStateError, ReadOnlyError, TransactionInactiveError } from "./lib/errors.js";
5
5
  import extractKey from "./lib/extractKey.js";
6
6
  import valueToKey from "./lib/valueToKey.js";
7
+ import { cloneValueForInsertion } from "./lib/cloneValueForInsertion.js";
7
8
  const getEffectiveObjectStore = cursor => {
8
9
  if (cursor.source instanceof FDBObjectStore) {
9
10
  return cursor.source;
@@ -298,7 +299,7 @@ class FDBCursor {
298
299
  if (!this._gotValue || !Object.hasOwn(this, "value")) {
299
300
  throw new InvalidStateError();
300
301
  }
301
- const clone = structuredClone(value);
302
+ const clone = cloneValueForInsertion(value, transaction);
302
303
  if (effectiveObjectStore.keyPath !== null) {
303
304
  let tempKey;
304
305
  try {
@@ -5,19 +5,21 @@ import FakeEventTarget from "./lib/FakeEventTarget.js";
5
5
  import ObjectStore from "./lib/ObjectStore.js";
6
6
  import validateKeyPath from "./lib/validateKeyPath.js";
7
7
  import closeConnection from "./lib/closeConnection.js";
8
+ // Common first 3 steps of https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-createobjectstore and https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore
8
9
  const confirmActiveVersionchangeTransaction = database => {
9
- if (!database._runningVersionchangeTransaction) {
10
- throw new InvalidStateError();
10
+ // Let transaction be database’s upgrade transaction if it is not null, or throw an "InvalidStateError" DOMException otherwise.
11
+ let transaction;
12
+ if (database._runningVersionchangeTransaction) {
13
+ // Find the latest versionchange transaction
14
+ transaction = database._rawDatabase.transactions.findLast(tx => {
15
+ return tx.mode === "versionchange";
16
+ });
11
17
  }
12
-
13
- // Find the latest versionchange transaction
14
- const transactions = database._rawDatabase.transactions.filter(tx => {
15
- return tx.mode === "versionchange";
16
- });
17
- const transaction = transactions[transactions.length - 1];
18
- if (!transaction || transaction._state === "finished") {
18
+ if (!transaction) {
19
19
  throw new InvalidStateError();
20
20
  }
21
+
22
+ // If transaction’s state is not active, then throw a "TransactionInactiveError" DOMException.
21
23
  if (transaction._state !== "active") {
22
24
  throw new TransactionInactiveError();
23
25
  }
@@ -55,43 +57,66 @@ class FDBDatabase extends FakeEventTarget {
55
57
  if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) {
56
58
  throw new InvalidAccessError();
57
59
  }
60
+
61
+ // Save for rollbackLog
58
62
  const objectStoreNames = [...this.objectStoreNames];
59
- transaction._rollbackLog.push(() => {
60
- const objectStore = this._rawDatabase.rawObjectStores.get(name);
61
- if (objectStore) {
62
- objectStore.deleted = true;
63
- }
64
- this.objectStoreNames = new FakeDOMStringList(...objectStoreNames);
65
- transaction._scope.delete(name);
66
- this._rawDatabase.rawObjectStores.delete(name);
67
- });
63
+ const transactionObjectStoreNames = [...transaction.objectStoreNames];
68
64
  const rawObjectStore = new ObjectStore(this._rawDatabase, name, keyPath, autoIncrement);
69
65
  this.objectStoreNames._push(name);
70
66
  this.objectStoreNames._sort();
71
67
  transaction._scope.add(name);
68
+ transaction._createdObjectStores.add(rawObjectStore);
72
69
  this._rawDatabase.rawObjectStores.set(name, rawObjectStore);
73
70
  transaction.objectStoreNames = new FakeDOMStringList(...this.objectStoreNames);
71
+ transaction._rollbackLog.push(() => {
72
+ rawObjectStore.deleted = true;
73
+ this.objectStoreNames = new FakeDOMStringList(...objectStoreNames);
74
+ transaction.objectStoreNames = new FakeDOMStringList(...transactionObjectStoreNames);
75
+ transaction._scope.delete(rawObjectStore.name);
76
+ this._rawDatabase.rawObjectStores.delete(rawObjectStore.name);
77
+ });
74
78
  return transaction.objectStore(name);
75
79
  }
80
+
81
+ // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore
76
82
  deleteObjectStore(name) {
77
83
  if (name === undefined) {
78
84
  throw new TypeError();
79
85
  }
80
86
  const transaction = confirmActiveVersionchangeTransaction(this);
87
+
88
+ // Let store be the object store named name in database, or throw a "NotFoundError" DOMException if none.
81
89
  const store = this._rawDatabase.rawObjectStores.get(name);
82
90
  if (store === undefined) {
83
91
  throw new NotFoundError();
84
92
  }
93
+
94
+ // Remove store from this’s object store set.
95
+ // This method synchronously modifies the objectStoreNames property on the IDBDatabase instance on which it was called.
85
96
  this.objectStoreNames = new FakeDOMStringList(...Array.from(this.objectStoreNames).filter(objectStoreName => {
86
97
  return objectStoreName !== name;
87
98
  }));
88
99
  transaction.objectStoreNames = new FakeDOMStringList(...this.objectStoreNames);
100
+
101
+ // If there is an object store handle associated with store and transaction, remove all entries from its index set.
102
+ const objectStore = transaction._objectStoresCache.get(name);
103
+ let prevIndexNames;
104
+ if (objectStore) {
105
+ prevIndexNames = [...objectStore.indexNames];
106
+ objectStore.indexNames = new FakeDOMStringList();
107
+ }
89
108
  transaction._rollbackLog.push(() => {
90
109
  store.deleted = false;
91
- this._rawDatabase.rawObjectStores.set(name, store);
92
- this.objectStoreNames._push(name);
110
+ this._rawDatabase.rawObjectStores.set(store.name, store);
111
+ this.objectStoreNames._push(store.name);
112
+ transaction.objectStoreNames._push(store.name);
93
113
  this.objectStoreNames._sort();
114
+ if (objectStore && prevIndexNames) {
115
+ objectStore.indexNames = new FakeDOMStringList(...prevIndexNames);
116
+ }
94
117
  });
118
+
119
+ // Destroy store.
95
120
  store.deleted = true;
96
121
  this._rawDatabase.rawObjectStores.delete(name);
97
122
  transaction._objectStoresCache.delete(name);
@@ -7,6 +7,7 @@ import enforceRange from "./lib/enforceRange.js";
7
7
  import { AbortError, VersionError } from "./lib/errors.js";
8
8
  import FakeEvent from "./lib/FakeEvent.js";
9
9
  import { queueTask } from "./lib/scheduling.js";
10
+ import { validateRequiredArguments } from "./lib/validateRequiredArguments.js";
10
11
  // https://w3c.github.io/IndexedDB/#connection-queue
11
12
  const runTaskInConnectionQueue = (connectionQueues, name, task) => {
12
13
  // Let queue be the connection queue for storageKey and name.
@@ -298,13 +299,19 @@ const openDatabase = (databases, connectionQueues, name, version, request, cb) =
298
299
  runTaskInConnectionQueue(connectionQueues, name, openDBTask);
299
300
  };
300
301
  class FDBFactory {
301
- cmp = cmp;
302
302
  _databases = new Map();
303
303
  // https://w3c.github.io/IndexedDB/#connection-queue
304
304
  _connectionQueues = new Map(); // promise chain as lightweight FIFO task queue
305
305
 
306
+ // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp
307
+ cmp(first, second) {
308
+ validateRequiredArguments(arguments.length, 2, "IDBFactory.cmp");
309
+ return cmp(first, second);
310
+ }
311
+
306
312
  // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase
307
313
  deleteDatabase(name) {
314
+ validateRequiredArguments(arguments.length, 1, "IDBFactory.deleteDatabase");
308
315
  const request = new FDBOpenDBRequest();
309
316
  request.source = null;
310
317
  queueTask(() => {
@@ -334,6 +341,7 @@ class FDBFactory {
334
341
 
335
342
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version
336
343
  open(name, version) {
344
+ validateRequiredArguments(arguments.length, 1, "IDBFactory.open");
337
345
  if (arguments.length > 1 && version !== undefined) {
338
346
  // Based on spec, not sure why "MAX_SAFE_INTEGER" instead of "unsigned long long", but it's needed to pass
339
347
  // tests
@@ -63,15 +63,19 @@ class FDBIndex {
63
63
  const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName);
64
64
  return index && !index.deleted;
65
65
  }).sort());
66
- transaction._rollbackLog.push(() => {
67
- this._name = oldName;
68
- this._rawIndex.name = oldName;
69
- this.objectStore._indexesCache.delete(name);
70
- this.objectStore._indexesCache.set(oldName, this);
71
- this.objectStore._rawObjectStore.rawIndexes.delete(name);
72
- this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex);
73
- this.objectStore.indexNames = new FakeDOMStringList(...oldIndexNames);
74
- });
66
+
67
+ // 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."
68
+ if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) {
69
+ transaction._rollbackLog.push(() => {
70
+ this._name = oldName;
71
+ this._rawIndex.name = oldName;
72
+ this.objectStore._indexesCache.delete(name);
73
+ this.objectStore._indexesCache.set(oldName, this);
74
+ this.objectStore._rawObjectStore.rawIndexes.delete(name);
75
+ this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex);
76
+ this.objectStore.indexNames = new FakeDOMStringList(...oldIndexNames);
77
+ });
78
+ }
75
79
  }
76
80
 
77
81
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction
@@ -14,6 +14,7 @@ import valueToKeyRange from "./lib/valueToKeyRange.js";
14
14
  import { getKeyPath } from "./lib/getKeyPath.js";
15
15
  import extractGetAllOptions from "./lib/extractGetAllOptions.js";
16
16
  import enforceRange from "./lib/enforceRange.js";
17
+ import { cloneValueForInsertion } from "./lib/cloneValueForInsertion.js";
17
18
  const confirmActiveTransaction = objectStore => {
18
19
  if (objectStore._rawObjectStore.deleted) {
19
20
  throw new InvalidStateError();
@@ -32,7 +33,7 @@ const buildRecordAddPut = (objectStore, value, key) => {
32
33
  throw new DataError();
33
34
  }
34
35
  }
35
- const clone = structuredClone(value);
36
+ const clone = cloneValueForInsertion(value, objectStore.transaction);
36
37
  if (objectStore.keyPath !== null) {
37
38
  const tempKey = extractKey(objectStore.keyPath, clone);
38
39
  if (tempKey.type === "found") {
@@ -103,17 +104,21 @@ class FDBObjectStore {
103
104
  this.transaction._scope.delete(oldName);
104
105
  transaction._scope.add(name);
105
106
  transaction.objectStoreNames = new FakeDOMStringList(...Array.from(transaction._scope).sort());
106
- transaction._rollbackLog.push(() => {
107
- this._name = oldName;
108
- this._rawObjectStore.name = oldName;
109
- this.transaction._objectStoresCache.delete(name);
110
- this.transaction._objectStoresCache.set(oldName, this);
111
- this._rawObjectStore.rawDatabase.rawObjectStores.delete(name);
112
- this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore);
113
- transaction.db.objectStoreNames = new FakeDOMStringList(...oldObjectStoreNames);
114
- transaction._scope = oldScope;
115
- transaction.objectStoreNames = new FakeDOMStringList(...oldTransactionObjectStoreNames);
116
- });
107
+
108
+ // 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."
109
+ if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) {
110
+ transaction._rollbackLog.push(() => {
111
+ this._name = oldName;
112
+ this._rawObjectStore.name = oldName;
113
+ this.transaction._objectStoresCache.delete(name);
114
+ this.transaction._objectStoresCache.set(oldName, this);
115
+ this._rawObjectStore.rawDatabase.rawObjectStores.delete(name);
116
+ this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore);
117
+ transaction.db.objectStoreNames = new FakeDOMStringList(...oldObjectStoreNames);
118
+ transaction._scope = oldScope;
119
+ transaction.objectStoreNames = new FakeDOMStringList(...oldTransactionObjectStoreNames);
120
+ });
121
+ }
117
122
  }
118
123
  put(value, key) {
119
124
  if (arguments.length === 0) {
@@ -299,21 +304,20 @@ class FDBObjectStore {
299
304
  // create and return an IDBIndex object. Instead the implementation must queue up an operation to abort the
300
305
  // "versionchange" transaction which was used for the createIndex call.
301
306
 
307
+ // Save for rollbackLog
302
308
  const indexNames = [...this.indexNames];
303
- this.transaction._rollbackLog.push(() => {
304
- const index2 = this._rawObjectStore.rawIndexes.get(name);
305
- if (index2) {
306
- index2.deleted = true;
307
- }
308
- this.indexNames = new FakeDOMStringList(...indexNames);
309
- this._rawObjectStore.rawIndexes.delete(name);
310
- });
311
309
  const index = new Index(this._rawObjectStore, name, keyPath, multiEntry, unique);
312
310
  this.indexNames._push(name);
313
311
  this.indexNames._sort();
312
+ this.transaction._createdIndexes.add(index);
314
313
  this._rawObjectStore.rawIndexes.set(name, index);
315
314
  index.initialize(this.transaction); // This is async by design
316
315
 
316
+ this.transaction._rollbackLog.push(() => {
317
+ index.deleted = true;
318
+ this.indexNames = new FakeDOMStringList(...indexNames);
319
+ this._rawObjectStore.rawIndexes.delete(index.name);
320
+ });
317
321
  return new FDBIndex(this, index);
318
322
  }
319
323
 
@@ -351,8 +355,8 @@ class FDBObjectStore {
351
355
  }
352
356
  this.transaction._rollbackLog.push(() => {
353
357
  rawIndex.deleted = false;
354
- this._rawObjectStore.rawIndexes.set(name, rawIndex);
355
- this.indexNames._push(name);
358
+ this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex);
359
+ this.indexNames._push(rawIndex.name);
356
360
  this.indexNames._sort();
357
361
  });
358
362
  this.indexNames = new FakeDOMStringList(...Array.from(this.indexNames).filter(indexName => {
@@ -17,6 +17,8 @@ class FDBTransaction extends FakeEventTarget {
17
17
  oncomplete = null;
18
18
  onerror = null;
19
19
  _requests = [];
20
+ _createdIndexes = new Set();
21
+ _createdObjectStores = new Set();
20
22
  constructor(storeNames, mode, durability, db) {
21
23
  super();
22
24
  this._scope = new Set(storeNames);
@@ -17,8 +17,10 @@ class Database {
17
17
 
18
18
  // The next transaction to run is the first waiting one that doesn't overlap with either a running one or a
19
19
  // preceding waiting one. This allows non-overlapping transactions to run in parallel.
20
+ // The exception is readonly transactions, which are allowed to run in parallel with other readonly
21
+ // transactions, even with overlapping scopes, since no data is being modified.
20
22
  const next = waiting.find((transaction, i) => {
21
- const anyRunning = running.some(other => intersection(other._scope, transaction._scope).size > 0);
23
+ const anyRunning = running.some(other => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0);
22
24
  if (anyRunning) {
23
25
  return false;
24
26
  }
@@ -26,6 +28,8 @@ class Database {
26
28
  // If any _preceding_ waiting transactions are blocked, then that's also blocking.
27
29
  // E.g. if you have 3 transactions: [a], [a,b], and [b,c], then [a] blocks [a,b] which blocks [b,c]
28
30
  // until [a] is complete, even though [a] and [b,c] share no overlap.
31
+ // Note that readonly transactions do not have to be handled as a special case here,
32
+ // because if any transactions with overlapping scopes are blocked, then we can assume they are
29
33
  const anyWaiting = waiting.slice(0, i).some(other => intersection(other._scope, transaction._scope).size > 0);
30
34
  return !anyWaiting;
31
35
  });
@@ -82,14 +82,22 @@ class ObjectStore {
82
82
  newRecord.key = key;
83
83
  }
84
84
  }
85
+ const rollbackLogForThisOperation = [];
85
86
  if (this.keyGenerator !== null && newRecord.key === undefined) {
87
+ let rolledBack = false;
88
+ const keyGeneratorBefore = this.keyGenerator.num;
89
+ const rollbackKeyGenerator = () => {
90
+ if (rolledBack) {
91
+ return;
92
+ }
93
+ rolledBack = true;
94
+ if (this.keyGenerator) {
95
+ this.keyGenerator.num = keyGeneratorBefore;
96
+ }
97
+ };
98
+ rollbackLogForThisOperation.push(rollbackKeyGenerator);
86
99
  if (rollbackLog) {
87
- const keyGeneratorBefore = this.keyGenerator.num;
88
- rollbackLog.push(() => {
89
- if (this.keyGenerator) {
90
- this.keyGenerator.num = keyGeneratorBefore;
91
- }
92
- });
100
+ rollbackLog.push(rollbackKeyGenerator);
93
101
  }
94
102
  newRecord.key = this.keyGenerator.next();
95
103
 
@@ -112,28 +120,50 @@ class ObjectStore {
112
120
  identifier = remainingKeyPath.slice(0, i);
113
121
  remainingKeyPath = remainingKeyPath.slice(i + 1);
114
122
  if (!Object.hasOwn(object, identifier)) {
115
- object[identifier] = {};
123
+ // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`)
124
+ // Equivalent to `object[identifier] = ...` without using `Object.prototype`
125
+ Object.defineProperty(object, identifier, {
126
+ configurable: true,
127
+ enumerable: true,
128
+ writable: true,
129
+ value: {}
130
+ });
116
131
  }
117
132
  object = object[identifier];
118
133
  }
119
134
  }
120
135
  identifier = remainingKeyPath;
121
- object[identifier] = newRecord.key;
136
+
137
+ // Bypass prototype when setting (See `bindings-inject-values-bypass.any.js`)
138
+ // Equivalent to `object[identifier] = ...` without using `Object.prototype`
139
+ Object.defineProperty(object, identifier, {
140
+ configurable: true,
141
+ enumerable: true,
142
+ writable: true,
143
+ value: newRecord.key
144
+ });
122
145
  }
123
146
  } else if (this.keyGenerator !== null && typeof newRecord.key === "number") {
124
147
  this.keyGenerator.setIfLarger(newRecord.key);
125
148
  }
126
149
  const existingRecord = this.records.put(newRecord, noOverwrite);
150
+ let rolledBack = false;
151
+ const rollbackStoreRecord = () => {
152
+ if (rolledBack) {
153
+ return;
154
+ }
155
+ rolledBack = true;
156
+ if (existingRecord) {
157
+ // overwrite on rollback
158
+ this.storeRecord(existingRecord, false);
159
+ } else {
160
+ // delete on rollback
161
+ this.deleteRecord(newRecord.key);
162
+ }
163
+ };
164
+ rollbackLogForThisOperation.push(rollbackStoreRecord);
127
165
  if (rollbackLog) {
128
- rollbackLog.push(() => {
129
- if (existingRecord) {
130
- // overwrite on rollback
131
- this.storeRecord(existingRecord, false);
132
- } else {
133
- // delete on rollback
134
- this.deleteRecord(newRecord.key);
135
- }
136
- });
166
+ rollbackLog.push(rollbackStoreRecord);
137
167
  }
138
168
 
139
169
  // Delete existing indexes
@@ -144,10 +174,20 @@ class ObjectStore {
144
174
  }
145
175
 
146
176
  // Update indexes
147
- for (const rawIndex of this.rawIndexes.values()) {
148
- if (rawIndex.initialized) {
149
- rawIndex.storeRecord(newRecord);
177
+ try {
178
+ for (const rawIndex of this.rawIndexes.values()) {
179
+ if (rawIndex.initialized) {
180
+ rawIndex.storeRecord(newRecord);
181
+ }
182
+ }
183
+ } catch (err) {
184
+ // 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.
185
+ if (err.name === "ConstraintError") {
186
+ for (const rollback of rollbackLogForThisOperation) {
187
+ rollback();
188
+ }
150
189
  }
190
+ throw err;
151
191
  }
152
192
  return newRecord.key;
153
193
  }
@@ -0,0 +1,24 @@
1
+ // https://w3c.github.io/IndexedDB/#clone-value
2
+ // Note that we only need to call this during insertions because the spec does not expect any cloning during retrieval,
3
+ // only `StructuredDeserialize()` (e.g. see [1]). This is also only required for values, not keys, since keys do not
4
+ // require cloning during insertion (e.g. see [2]).
5
+ // [1]: https://w3c.github.io/IndexedDB/#retrieve-multiple-items-from-an-object-store
6
+ // [2]: https://w3c.github.io/IndexedDB/#add-or-put
7
+ export function cloneValueForInsertion(value, transaction) {
8
+ // Assert: transaction’s state is active.
9
+ if (transaction._state !== "active") {
10
+ throw new Error("Assert: transaction state is active");
11
+ }
12
+
13
+ // Set transaction’s state to inactive.
14
+ transaction._state = "inactive";
15
+ try {
16
+ // Let serialized be StructuredSerializeForStorage(value).
17
+ // Let clone be ? StructuredDeserialize(serialized, targetRealm).
18
+ // Return clone.
19
+ return structuredClone(value);
20
+ } finally {
21
+ // Set transaction’s state to active.
22
+ transaction._state = "active";
23
+ }
24
+ }
@@ -0,0 +1,7 @@
1
+ // WebIDL requires passing the right number of non-optional arguments, e.g. IDBFactory.open() must have at least 1 arg
2
+ export function validateRequiredArguments(numArguments, expectedNumArguments, methodName) {
3
+ if (numArguments < expectedNumArguments) {
4
+ // imitate Firefox's error message
5
+ throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} ` + `required, but only ${arguments.length} passed`);
6
+ }
7
+ }
@@ -51,20 +51,40 @@ const valueToKeyWithoutThrowing = (input, seen) => {
51
51
  return INVALID_VALUE;
52
52
  }
53
53
  seen.add(input);
54
- const keys = [];
55
- for (let i = 0; i < input.length; i++) {
54
+
55
+ // This algorithm is tricky to account for `bindings-inject-keys-bypass.any.js`. We _should_ return early when
56
+ // encountering an invalid key/type, but we also need to avoid triggering `Object.prototype['10']` if it's been
57
+ // overridden. One simple way to do this (and which doesn't rely on sparse arrays or other exotic solutions that
58
+ // could cause de-opts) is to use `Array.from()` with a mapper function, which does not trigger the prototype
59
+ // setter [1]. It does prevent an early return, but we can at least short-circuit inside the mapper function
60
+ // (which isn't strictly necessary to pass the WPTs, but is closer to the spec).
61
+ // [1]: See https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.from, specifically
62
+ // the chain CreateDataPropertyOrThrow -> CreateDataProperty -> DefineOwnProperty which defines
63
+ // the array element as an "own" property.
64
+ let hasInvalid = false;
65
+ const keys = Array.from({
66
+ length: input.length
67
+ }, (_, i) => {
68
+ if (hasInvalid) {
69
+ return;
70
+ }
56
71
  const hop = Object.hasOwn(input, i);
57
72
  if (!hop) {
58
73
  // If hop is false, return "invalid value".
59
- return INVALID_VALUE;
74
+ hasInvalid = true;
75
+ return;
60
76
  }
61
77
  const entry = input[i];
62
78
  const key = valueToKeyWithoutThrowing(entry, seen);
63
79
  // If key is "invalid value" or "invalid type" abort these steps and return "invalid value".
64
80
  if (key === INVALID_VALUE || key === INVALID_TYPE) {
65
- return INVALID_VALUE;
81
+ hasInvalid = true;
82
+ return;
66
83
  }
67
- keys.push(key);
84
+ return key;
85
+ });
86
+ if (hasInvalid) {
87
+ return INVALID_VALUE;
68
88
  }
69
89
  return keys;
70
90
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fake-indexeddb",
3
- "version": "6.2.3",
3
+ "version": "6.2.4",
4
4
  "description": "Fake IndexedDB: a pure JS in-memory implementation of the IndexedDB API",
5
5
  "homepage": "https://github.com/dumbmatter/fakeIndexedDB",
6
6
  "repository": {
@@ -100,7 +100,9 @@
100
100
  "test-qunit": "pnpm run build-qunit && OPENSSL_CONF=/dev/null node-qunit-phantomjs build/esm/test/indexedDBmock/index.html",
101
101
  "test-w3c": "node --test src/test/web-platform-tests/run-all.js",
102
102
  "test": "pnpm run lint && pnpm run build && pnpm run test-jest && node test/test.js && node test/dexie.js && pnpm run test-w3c && pnpm run test-mocha && pnpm run test-qunit",
103
- "prepare": "husky"
103
+ "prepare": "husky",
104
+ "update-wpt-results": "pnpm run build && node ./bin/update-browser-wpt-results.js && WRITE_TO_README=1 pnpm run test-w3c",
105
+ "version": "pnpm run update-wpt-results && git add README.md"
104
106
  },
105
107
  "author": "Jeremy Scheff <jdscheff@gmail.com> (https://dumbmatter.com/)",
106
108
  "license": "Apache-2.0",