fake-indexeddb 6.2.2 → 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.
Files changed (38) hide show
  1. package/README.md +23 -15
  2. package/auto/index.js +1 -1
  3. package/auto/index.mjs +1 -1
  4. package/build/cjs/FDBCursor.js +2 -1
  5. package/build/cjs/FDBDatabase.js +45 -20
  6. package/build/cjs/FDBFactory.js +285 -137
  7. package/build/cjs/FDBIndex.js +13 -9
  8. package/build/cjs/FDBObjectStore.js +26 -22
  9. package/build/cjs/FDBTransaction.js +51 -11
  10. package/build/cjs/lib/Database.js +25 -12
  11. package/build/cjs/lib/FakeEventTarget.js +17 -5
  12. package/build/cjs/lib/ObjectStore.js +60 -20
  13. package/build/cjs/lib/cloneValueForInsertion.js +30 -0
  14. package/build/cjs/lib/extractGetAllOptions.js +2 -2
  15. package/build/cjs/lib/intersection.js +18 -0
  16. package/build/cjs/lib/isPotentiallyValidKeyRange.js +13 -20
  17. package/build/cjs/lib/scheduling.js +4 -4
  18. package/build/cjs/lib/validateRequiredArguments.js +13 -0
  19. package/build/cjs/lib/valueToKey.js +8 -53
  20. package/build/cjs/lib/valueToKeyWithoutThrowing.js +102 -0
  21. package/build/esm/FDBCursor.js +2 -1
  22. package/build/esm/FDBDatabase.js +45 -20
  23. package/build/esm/FDBFactory.js +285 -137
  24. package/build/esm/FDBIndex.js +13 -9
  25. package/build/esm/FDBObjectStore.js +26 -22
  26. package/build/esm/FDBTransaction.js +51 -11
  27. package/build/esm/lib/Database.js +25 -12
  28. package/build/esm/lib/FakeEventTarget.js +17 -5
  29. package/build/esm/lib/ObjectStore.js +60 -20
  30. package/build/esm/lib/cloneValueForInsertion.js +24 -0
  31. package/build/esm/lib/extractGetAllOptions.js +2 -2
  32. package/build/esm/lib/intersection.js +12 -0
  33. package/build/esm/lib/isPotentiallyValidKeyRange.js +12 -20
  34. package/build/esm/lib/scheduling.js +4 -4
  35. package/build/esm/lib/validateRequiredArguments.js +7 -0
  36. package/build/esm/lib/valueToKey.js +7 -52
  37. package/build/esm/lib/valueToKeyWithoutThrowing.js +95 -0
  38. package/package.json +4 -2
@@ -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 => {
@@ -11,11 +11,14 @@ class FDBTransaction extends FakeEventTarget {
11
11
  _started = false;
12
12
  _rollbackLog = [];
13
13
  _objectStoresCache = new Map();
14
+ _openRequest = null;
14
15
  error = null;
15
16
  onabort = null;
16
17
  oncomplete = null;
17
18
  onerror = null;
18
19
  _requests = [];
20
+ _createdIndexes = new Set();
21
+ _createdObjectStores = new Set();
19
22
  constructor(storeNames, mode, durability, db) {
20
23
  super();
21
24
  this._scope = new Set(storeNames);
@@ -25,7 +28,7 @@ class FDBTransaction extends FakeEventTarget {
25
28
  this.objectStoreNames = new FakeDOMStringList(...Array.from(this._scope).sort());
26
29
  }
27
30
 
28
- // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-aborting-a-transaction
31
+ // https://w3c.github.io/IndexedDB/#abort-transaction
29
32
  _abort(errName) {
30
33
  for (const f of this._rollbackLog.reverse()) {
31
34
  f();
@@ -42,24 +45,61 @@ class FDBTransaction extends FakeEventTarget {
42
45
  if (request.readyState !== "done") {
43
46
  request.readyState = "done"; // This will cancel execution of this request's operation
44
47
  if (request.source) {
45
- request.result = undefined;
46
- request.error = new AbortError();
47
- const event = new FakeEvent("error", {
48
- bubbles: true,
49
- cancelable: true
48
+ // https://w3c.github.io/IndexedDB/#ref-for-list-iterate%E2%91%A2
49
+ // For each request of transaction’s request list, abort the steps to asynchronously
50
+ // execute a request for request, set request’s processed flag to true, and queue a
51
+ // database task to run these steps:
52
+ queueTask(() => {
53
+ // Set request’s result to undefined.
54
+ request.result = undefined;
55
+ // Set request’s error to a newly created "AbortError" DOMException.
56
+ request.error = new AbortError();
57
+
58
+ // Fire an event named error at request with its bubbles and cancelable attributes initialized
59
+ // to true.
60
+ const event = new FakeEvent("error", {
61
+ bubbles: true,
62
+ cancelable: true
63
+ });
64
+ event.eventPath = [this.db, this];
65
+ try {
66
+ request.dispatchEvent(event);
67
+ } catch (_err) {
68
+ if (this._state === "active") {
69
+ this._abort("AbortError");
70
+ }
71
+ }
50
72
  });
51
- event.eventPath = [this.db, this];
52
- request.dispatchEvent(event);
53
73
  }
54
74
  }
55
75
  }
76
+
77
+ // Queue a database task to run these steps:
56
78
  queueTask(() => {
79
+ // If transaction is an upgrade transaction, then set transaction’s connection’s associated database’s
80
+ // upgrade transaction to null.
81
+ // (i.e. remove it from the list of `db.connections`)
82
+ const isUpgradeTransaction = this.mode === "versionchange";
83
+ if (isUpgradeTransaction) {
84
+ this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter(connection => !connection._rawDatabase.transactions.includes(this));
85
+ }
86
+ // Fire an event named abort at transaction with its bubbles attribute initialized to true.
57
87
  const event = new FakeEvent("abort", {
58
88
  bubbles: true,
59
89
  cancelable: false
60
90
  });
61
91
  event.eventPath = [this.db];
62
92
  this.dispatchEvent(event);
93
+
94
+ // If transaction is an upgrade transaction, then:
95
+ if (isUpgradeTransaction) {
96
+ // Let request be the open request associated with transaction.
97
+ const request = this._openRequest;
98
+ // Set request’s transaction to null.
99
+ request.transaction = null;
100
+ // Set request’s result to undefined.
101
+ request.result = undefined;
102
+ }
63
103
  });
64
104
  this._state = "finished";
65
105
  }
@@ -171,11 +211,11 @@ class FDBTransaction extends FakeEventTarget {
171
211
  try {
172
212
  event.eventPath = [this.db, this];
173
213
  request.dispatchEvent(event);
174
- } catch (err) {
175
- if (this._state !== "committing") {
214
+ } catch (_err) {
215
+ if (this._state === "active") {
176
216
  this._abort("AbortError");
217
+ defaultAction = undefined; // do not abort again
177
218
  }
178
- throw err;
179
219
  }
180
220
 
181
221
  // Default action of event
@@ -1,7 +1,7 @@
1
1
  import { queueTask } from "./scheduling.js";
2
+ import { intersection } from "./intersection.js";
2
3
  // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-database
3
4
  class Database {
4
- deletePending = false;
5
5
  transactions = [];
6
6
  rawObjectStores = new Map();
7
7
  connections = [];
@@ -12,18 +12,31 @@ class Database {
12
12
  }
13
13
  processTransactions() {
14
14
  queueTask(() => {
15
- const anyRunning = this.transactions.some(transaction => {
16
- return transaction._started && transaction._state !== "finished";
17
- });
18
- if (!anyRunning) {
19
- const next = this.transactions.find(transaction => {
20
- return !transaction._started && transaction._state !== "finished";
21
- });
22
- if (next) {
23
- next.addEventListener("complete", this.processTransactions);
24
- next.addEventListener("abort", this.processTransactions);
25
- next._start();
15
+ const running = this.transactions.filter(transaction => transaction._started && transaction._state !== "finished");
16
+ const waiting = this.transactions.filter(transaction => !transaction._started && transaction._state !== "finished");
17
+
18
+ // The next transaction to run is the first waiting one that doesn't overlap with either a running one or a
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.
22
+ const next = waiting.find((transaction, i) => {
23
+ const anyRunning = running.some(other => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0);
24
+ if (anyRunning) {
25
+ return false;
26
26
  }
27
+
28
+ // If any _preceding_ waiting transactions are blocked, then that's also blocking.
29
+ // E.g. if you have 3 transactions: [a], [a,b], and [b,c], then [a] blocks [a,b] which blocks [b,c]
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
33
+ const anyWaiting = waiting.slice(0, i).some(other => intersection(other._scope, transaction._scope).size > 0);
34
+ return !anyWaiting;
35
+ });
36
+ if (next) {
37
+ next.addEventListener("complete", this.processTransactions);
38
+ next.addEventListener("abort", this.processTransactions);
39
+ next._start();
27
40
  }
28
41
  });
29
42
  }
@@ -6,6 +6,15 @@ const stopped = (event, listener) => {
6
6
  // http://www.w3.org/TR/dom/#concept-event-listener-invoke
7
7
  const invokeEventListeners = (event, obj) => {
8
8
  event.currentTarget = obj;
9
+ const errors = [];
10
+ const invoke = callback => {
11
+ try {
12
+ // @ts-expect-error EventCallback's types are not quite right here
13
+ callback.call(event.currentTarget, event);
14
+ } catch (err) {
15
+ errors.push(err);
16
+ }
17
+ };
9
18
 
10
19
  // The callback might cause obj.listeners to mutate as we traverse it.
11
20
  // Take a copy of the array so that nothing sneaks in and we don't lose
@@ -14,9 +23,7 @@ const invokeEventListeners = (event, obj) => {
14
23
  if (event.type !== listener.type || stopped(event, listener)) {
15
24
  continue;
16
25
  }
17
-
18
- // @ts-ignore
19
- listener.callback.call(event.currentTarget, event);
26
+ invoke(listener.callback);
20
27
  }
21
28
  const typeToProp = {
22
29
  abort: "onabort",
@@ -40,10 +47,15 @@ const invokeEventListeners = (event, obj) => {
40
47
  type: event.type
41
48
  };
42
49
  if (!stopped(event, listener)) {
43
- // @ts-ignore
44
- listener.callback.call(event.currentTarget, event);
50
+ invoke(listener.callback);
45
51
  }
46
52
  }
53
+
54
+ // we want to execute all listeners before deciding if we want to throw, because there could be an error thrown by
55
+ // the first listener, but the second should still be invoked
56
+ if (errors.length) {
57
+ throw new AggregateError(errors);
58
+ }
47
59
  };
48
60
  class FakeEventTarget {
49
61
  listeners = [];
@@ -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
+ }
@@ -4,8 +4,8 @@ import enforceRange from "./enforceRange.js";
4
4
  const extractGetAllOptions = (queryOrOptions, count, numArguments) => {
5
5
  let query;
6
6
  let direction;
7
- if (isPotentiallyValidKeyRange(queryOrOptions)) {
8
- // queryOrOptions is FDBKeyRange | Key
7
+ if (queryOrOptions === undefined || queryOrOptions === null || isPotentiallyValidKeyRange(queryOrOptions)) {
8
+ // queryOrOptions is FDBKeyRange | Key | null | undefined
9
9
  query = queryOrOptions;
10
10
  if (numArguments > 1 && count !== undefined) {
11
11
  count = enforceRange(count, "unsigned long");
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Minimal polyfill of `Set.prototype.intersection`, available in Node 22+.
3
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/intersection
4
+ * @param set1
5
+ * @param set2
6
+ */
7
+ export function intersection(set1, set2) {
8
+ if ("intersection" in set1) {
9
+ return set1.intersection(set2);
10
+ }
11
+ return new Set([...set1].filter(item => set2.has(item)));
12
+ }
@@ -1,26 +1,18 @@
1
1
  import FDBKeyRange from "../FDBKeyRange.js";
2
- import isSharedArrayBuffer from "./isSharedArrayBuffer.js";
2
+ import valueToKeyWithoutThrowing, { INVALID_TYPE } from "./valueToKeyWithoutThrowing.js";
3
3
 
4
4
  // https://www.w3.org/TR/IndexedDB/#is-a-potentially-valid-key-range
5
5
  const isPotentiallyValidKeyRange = value => {
6
- // Many of these conditions recapitulate the same conditions in `valueToKeyRange.ts`
7
- return (
8
- // FDBKeyRange
9
- value instanceof FDBKeyRange ||
10
- // null/undefined - nullDisallowedFlag=false is assumed here
11
- value === null || value === undefined ||
12
- // Number
13
- typeof value === "number" ||
14
- // Date
15
- Object.prototype.toString.call(value) === "[object Date]" ||
16
- // string
17
- typeof value === "string" ||
18
- // buffer source type
19
- // note: we are explicitly _not_ checking for detachedness here, to match Chromium's behavior
20
- // see: https://github.com/w3c/IndexedDB/issues/465
21
- value instanceof ArrayBuffer || isSharedArrayBuffer(value) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(value) ||
22
- // array exotic type
23
- Array.isArray(value)
24
- );
6
+ // If value is a key range, return true.
7
+ if (value instanceof FDBKeyRange) {
8
+ return true;
9
+ }
10
+
11
+ // Let key be the result of converting a value to a key with value.
12
+ const key = valueToKeyWithoutThrowing(value);
13
+
14
+ // If key is "invalid type" return false.
15
+ // Else return true.
16
+ return key !== INVALID_TYPE;
25
17
  };
26
18
  export default isPotentiallyValidKeyRange;
@@ -19,10 +19,10 @@ function getSetImmediateFromJsdom() {
19
19
 
20
20
  // waiting on this PR for typescript types: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1249
21
21
 
22
- // 'user-blocking' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping
23
- const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn, {
24
- priority: "user-blocking"
25
- }));
22
+ // 'postTask' runs right after microtasks, so equivalent to setTimeout but without the 4ms clamping.
23
+ // Using the default priority of 'user-visible' to avoid blocking input while still running fairly quickly.
24
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API#task_priorities
25
+ const schedulerPostTask = typeof scheduler !== "undefined" && (fn => scheduler.postTask(fn));
26
26
 
27
27
  // fallback for environments that don't support any of the above
28
28
  const doSetTimeout = fn => setTimeout(fn, 0);
@@ -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
+ }
@@ -1,59 +1,14 @@
1
1
  import { DataError } from "./errors.js";
2
- import isSharedArrayBuffer from "./isSharedArrayBuffer.js";
2
+ import valueToKeyWithoutThrowing, { INVALID_TYPE, INVALID_VALUE } from "./valueToKeyWithoutThrowing.js";
3
3
  // https://w3c.github.io/IndexedDB/#convert-value-to-key
4
+ // Plus throwing a DataError for invalid value/invalid key, which is commonly done
5
+ // in lots of IndexedDB operations
4
6
  const valueToKey = (input, seen) => {
5
- if (typeof input === "number") {
6
- if (isNaN(input)) {
7
- throw new DataError();
8
- }
9
- return input;
10
- } else if (Object.prototype.toString.call(input) === "[object Date]") {
11
- const ms = input.valueOf();
12
- if (isNaN(ms)) {
13
- throw new DataError();
14
- }
15
- return new Date(ms);
16
- } else if (typeof input === "string") {
17
- return input;
18
- } else if (
19
- // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type
20
- (input instanceof ArrayBuffer || isSharedArrayBuffer(input) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input)) &&
21
- // We can't consistently test detachedness, so instead we check if byteLength === 0
22
- // This isn't foolproof, but there's no perfect way to detect if Uint8Arrays or
23
- // SharedArrayBuffers are detached
24
- !("detached" in input ? input.detached : input.byteLength === 0)) {
25
- let arrayBuffer;
26
- let offset = 0;
27
- let length = 0;
28
- if (input instanceof ArrayBuffer || isSharedArrayBuffer(input)) {
29
- arrayBuffer = input;
30
- length = input.byteLength;
31
- } else {
32
- arrayBuffer = input.buffer;
33
- offset = input.byteOffset;
34
- length = input.byteLength;
35
- }
36
- return arrayBuffer.slice(offset, offset + length);
37
- } else if (Array.isArray(input)) {
38
- if (seen === undefined) {
39
- seen = new Set();
40
- } else if (seen.has(input)) {
41
- throw new DataError();
42
- }
43
- seen.add(input);
44
- const keys = [];
45
- for (let i = 0; i < input.length; i++) {
46
- const hop = Object.hasOwn(input, i);
47
- if (!hop) {
48
- throw new DataError();
49
- }
50
- const entry = input[i];
51
- const key = valueToKey(entry, seen);
52
- keys.push(key);
53
- }
54
- return keys;
55
- } else {
7
+ const result = valueToKeyWithoutThrowing(input, seen);
8
+ if (result === INVALID_VALUE || result === INVALID_TYPE) {
9
+ // If key is "invalid value" or "invalid type", throw a "DataError" DOMException
56
10
  throw new DataError();
57
11
  }
12
+ return result;
58
13
  };
59
14
  export default valueToKey;