indexeddbshim 15.2.0 → 16.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +1 -1
  2. package/badges/licenses-badge-dev.svg +1 -1
  3. package/badges/licenses-badge.svg +1 -1
  4. package/dist/DOMException.d.ts +2 -2
  5. package/dist/DOMException.d.ts.map +1 -1
  6. package/dist/DOMStringList.d.ts.map +1 -1
  7. package/dist/Event.d.ts +1 -1
  8. package/dist/Event.d.ts.map +1 -1
  9. package/dist/IDBCursor.d.ts +3 -2
  10. package/dist/IDBCursor.d.ts.map +1 -1
  11. package/dist/IDBDatabase.d.ts.map +1 -1
  12. package/dist/IDBFactory.d.ts +1 -1
  13. package/dist/IDBFactory.d.ts.map +1 -1
  14. package/dist/IDBIndex.d.ts +3 -3
  15. package/dist/IDBIndex.d.ts.map +1 -1
  16. package/dist/IDBKeyRange.d.ts +2 -2
  17. package/dist/IDBKeyRange.d.ts.map +1 -1
  18. package/dist/IDBObjectStore.d.ts +3 -3
  19. package/dist/IDBObjectStore.d.ts.map +1 -1
  20. package/dist/IDBTransaction.d.ts.map +1 -1
  21. package/dist/Key.d.ts +7 -7
  22. package/dist/Key.d.ts.map +1 -1
  23. package/dist/Sca.d.ts +1 -1
  24. package/dist/Sca.d.ts.map +1 -1
  25. package/dist/indexeddbshim-Key.js +1668 -1839
  26. package/dist/indexeddbshim-Key.js.map +1 -1
  27. package/dist/indexeddbshim-Key.min.js +2 -2
  28. package/dist/indexeddbshim-Key.min.js.map +1 -1
  29. package/dist/indexeddbshim-UnicodeIdentifiers-node.cjs +1257 -1163
  30. package/dist/indexeddbshim-UnicodeIdentifiers-node.cjs.map +1 -1
  31. package/dist/indexeddbshim-UnicodeIdentifiers.js +1850 -2721
  32. package/dist/indexeddbshim-UnicodeIdentifiers.js.map +1 -1
  33. package/dist/indexeddbshim-UnicodeIdentifiers.min.js +2 -2
  34. package/dist/indexeddbshim-UnicodeIdentifiers.min.js.map +1 -1
  35. package/dist/indexeddbshim-node.cjs +1257 -1163
  36. package/dist/indexeddbshim-node.cjs.map +1 -1
  37. package/dist/indexeddbshim-noninvasive.js +1848 -2719
  38. package/dist/indexeddbshim-noninvasive.js.map +1 -1
  39. package/dist/indexeddbshim-noninvasive.min.js +2 -2
  40. package/dist/indexeddbshim-noninvasive.min.js.map +1 -1
  41. package/dist/indexeddbshim.js +1846 -2709
  42. package/dist/indexeddbshim.js.map +1 -1
  43. package/dist/indexeddbshim.min.js +2 -2
  44. package/dist/indexeddbshim.min.js.map +1 -1
  45. package/dist/node-UnicodeIdentifiers.d.ts.map +1 -1
  46. package/dist/node.d.ts.map +1 -1
  47. package/dist/setGlobalVars.d.ts +1 -1
  48. package/dist/setGlobalVars.d.ts.map +1 -1
  49. package/dist/unicode-regex.d.ts +2 -2
  50. package/dist/unicode-regex.d.ts.map +1 -1
  51. package/dist/util.d.ts +1 -1
  52. package/dist/util.d.ts.map +1 -1
  53. package/package.json +30 -31
  54. package/src/DOMException.js +0 -1
  55. package/src/DOMStringList.js +0 -1
  56. package/src/IDBCursor.js +8 -4
  57. package/src/IDBFactory.js +2 -4
  58. package/src/IDBIndex.js +1 -2
  59. package/src/IDBKeyRange.js +1 -0
  60. package/src/IDBObjectStore.js +0 -1
  61. package/src/IDBTransaction.js +0 -1
  62. package/src/Key.js +5 -1
  63. package/src/browser-UnicodeIdentifiers.js +2 -2
  64. package/src/browser-noninvasive.js +1 -1
  65. package/src/browser.js +1 -1
  66. package/src/setGlobalVars.js +0 -2
  67. package/src/unicode-regex.js +12 -3
  68. package/src/util.js +1 -0
@@ -1,1384 +1,1235 @@
1
- /*! indexeddbshim - v15.2.0 - 9/11/2024 */
1
+ /*! indexeddbshim - v16.1.0 - 9/1/2025 */
2
2
 
3
3
  (function (global, factory) {
4
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
5
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
6
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.IDBKeyUtils = {}));
4
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
5
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
6
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.IDBKeyUtils = {}));
7
7
  })(this, (function (exports) { 'use strict';
8
8
 
9
- function _arrayLikeToArray(r, a) {
10
- (null == a || a > r.length) && (a = r.length);
11
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
12
- return n;
13
- }
14
- function _arrayWithHoles(r) {
15
- if (Array.isArray(r)) return r;
16
- }
17
- function _arrayWithoutHoles(r) {
18
- if (Array.isArray(r)) return _arrayLikeToArray(r);
19
- }
20
- function _createForOfIteratorHelper(r, e) {
21
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
22
- if (!t) {
23
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
24
- t && (r = t);
25
- var n = 0,
26
- F = function () {};
27
- return {
28
- s: F,
29
- n: function () {
30
- return n >= r.length ? {
31
- done: !0
32
- } : {
33
- done: !1,
34
- value: r[n++]
35
- };
36
- },
37
- e: function (r) {
38
- throw r;
39
- },
40
- f: F
41
- };
42
- }
43
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
44
- }
45
- var o,
46
- a = !0,
47
- u = !1;
48
- return {
49
- s: function () {
50
- t = t.call(r);
51
- },
52
- n: function () {
53
- var r = t.next();
54
- return a = r.done, r;
55
- },
56
- e: function (r) {
57
- u = !0, o = r;
58
- },
59
- f: function () {
60
- try {
61
- a || null == t.return || t.return();
62
- } finally {
63
- if (u) throw o;
64
- }
9
+ /* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */
10
+ /**
11
+ * @typedef {T[keyof T]} ValueOf<T>
12
+ * @template T
13
+ */
14
+ /* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */
15
+
16
+ /**
17
+ * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi
18
+ */
19
+
20
+ /**
21
+ * @typedef {{
22
+ * DEBUG: boolean,
23
+ * cacheDatabaseInstances: boolean,
24
+ * autoName: boolean,
25
+ * fullIDLSupport: boolean,
26
+ * checkOrigin: boolean,
27
+ * cursorPreloadPackSize: number,
28
+ * UnicodeIDStart: string,
29
+ * UnicodeIDContinue: string,
30
+ * registerSCA: (
31
+ * preset: import('typeson').Preset
32
+ * ) => import('typeson').Preset,
33
+ * avoidAutoShim: boolean,
34
+ * win: {
35
+ * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default
36
+ * },
37
+ * DEFAULT_DB_SIZE: number,
38
+ * useSQLiteIndexes: boolean,
39
+ * fs: FSApi,
40
+ * addNonIDBGlobals: boolean,
41
+ * replaceNonIDBGlobals: boolean,
42
+ * escapeDatabaseName: (name: string) => string,
43
+ * unescapeDatabaseName: (name: string) => string,
44
+ * databaseCharacterEscapeList: string|false,
45
+ * databaseNameLengthLimit: number|false,
46
+ * escapeNFDForDatabaseNames: boolean,
47
+ * addSQLiteExtension: boolean,
48
+ * memoryDatabase: string,
49
+ * deleteDatabaseFiles: boolean,
50
+ * databaseBasePath: string,
51
+ * sysDatabaseBasePath: string,
52
+ * sqlBusyTimeout: number,
53
+ * sqlTrace: () => void,
54
+ * sqlProfile: () => void,
55
+ * createIndexes: boolean
56
+ * }} ConfigValues
57
+ */
58
+
59
+ /**
60
+ * @typedef {ValueOf<ConfigValues>} ConfigValue
61
+ */
62
+
63
+ /** @type {{[key: string]: ConfigValue}} */
64
+ const map = {};
65
+ const CFG = /** @type {ConfigValues} */{};
66
+
67
+ /**
68
+ * @typedef {keyof ConfigValues} KeyofConfigValues
69
+ */
70
+
71
+ /**
72
+ * @typedef {KeyofConfigValues[]} Config
73
+ */
74
+
75
+ /** @type {Config} */
76
+ [
77
+ // Boolean for verbose reporting
78
+ 'DEBUG',
79
+ // Effectively defaults to false (ignored unless `true`)
80
+
81
+ // Boolean (effectively defaults to true) on whether to cache WebSQL
82
+ // `openDatabase` instances
83
+ 'cacheDatabaseInstances',
84
+ // Boolean on whether to auto-name databases (based on an
85
+ // auto-increment) when the empty string is supplied; useful with
86
+ // `memoryDatabase`; defaults to `false` which means the empty string
87
+ // will be used as the (valid) database name
88
+ 'autoName',
89
+ // Determines whether the slow-performing `Object.setPrototypeOf`
90
+ // calls required for full WebIDL compliance will be used. Probably
91
+ // only needed for testing or environments where full introspection
92
+ // on class relationships is required; see
93
+ // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements
94
+ 'fullIDLSupport',
95
+ // Effectively defaults to false (ignored unless `true`)
96
+
97
+ // Boolean on whether to perform origin checks in `IDBFactory` methods
98
+ // Effectively defaults to `true` (must be set to `false` to cancel checks)
99
+ 'checkOrigin',
100
+ // Used by `IDBCursor` continue methods for number of records to cache;
101
+ // Defaults to 100
102
+ 'cursorPreloadPackSize',
103
+ // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);
104
+ // or just use the Unicode builds which invoke this method
105
+ // automatically using the large, fully spec-compliant, regular
106
+ // expression strings of `src/UnicodeIdentifiers.js`)
107
+ // In the non-Unicode builds, defaults to /[$A-Z_a-z]/
108
+ 'UnicodeIDStart',
109
+ // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/
110
+ 'UnicodeIDContinue',
111
+ // Used by SCA.js for optional restructuring of typeson-registry
112
+ // Structured Cloning Algorithm; should only be needed for ensuring data
113
+ // created in 3.* versions of IndexedDBShim continue to work; see the
114
+ // library `typeson-registry-sca-reverter` to get a function to do this
115
+ 'registerSCA',
116
+ // BROWSER-SPECIFIC CONFIG
117
+ 'avoidAutoShim',
118
+ // Where WebSQL is detected but where `indexedDB` is
119
+ // missing or poor support is known (non-Chrome Android or
120
+ // non-Safari iOS9), the shim will be auto-applied without
121
+ // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing
122
+ // the shim for such cases.
123
+
124
+ // -----------SQL CONFIG----------
125
+ // Object (`window` in the browser) on which there may be an
126
+ // `openDatabase` method (if any) for WebSQL. (The browser
127
+ // throws if attempting to call `openDatabase` without the window
128
+ // so this is why the config doesn't just allow the function.)
129
+ // Defaults to `window` or `self` in browser builds or
130
+ // a singleton object with the `openDatabase` method set to
131
+ // the "websql" package in Node.
132
+ 'win',
133
+ // For internal `openDatabase` calls made by `IDBFactory` methods;
134
+ // per the WebSQL spec, "User agents are expected to use the display name
135
+ // and the estimated database size to optimize the user experience.
136
+ // For example, a user agent could use the estimated size to suggest an
137
+ // initial quota to the user. This allows a site that is aware that it
138
+ // will try to use hundreds of megabytes to declare this upfront, instead
139
+ // of the user agent prompting the user for permission to increase the
140
+ // quota every five megabytes."
141
+ // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari
142
+ 'DEFAULT_DB_SIZE',
143
+ // Whether to create indexes on SQLite tables (and also whether to try
144
+ // dropping)
145
+ // Effectively defaults to `false` (ignored unless `true`)
146
+ 'useSQLiteIndexes',
147
+ // NODE-IMPINGING SETTINGS (created for sake of limitations in Node
148
+ // or desktop file system implementation but applied by default in
149
+ // browser for parity)
150
+
151
+ // File system module with `unlink` to remove deleted database files
152
+ 'fs',
153
+ // Used when setting global shims to determine whether to try to add
154
+ // other globals shimmed by the library (`ShimDOMException`,
155
+ // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)
156
+ // Effectively defaults to `false` (ignored unless `true`)
157
+ 'addNonIDBGlobals',
158
+ // Used when setting global shims to determine whether to try to overwrite
159
+ // other globals shimmed by the library (`DOMException`, `DOMStringList`,
160
+ // `Event`, `CustomEvent`, `EventTarget`)
161
+ // Effectively defaults to `false` (ignored unless `true`)
162
+ 'replaceNonIDBGlobals',
163
+ // Overcoming limitations with node-sqlite3/storing database name on
164
+ // file systems
165
+ // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
166
+ // Defaults to prefixing database with `D_`, escaping
167
+ // `databaseCharacterEscapeList`, escaping NUL, and
168
+ // escaping upper case letters, as well as enforcing
169
+ // `databaseNameLengthLimit`
170
+ 'escapeDatabaseName',
171
+ // Not used internally; usable as a convenience method
172
+ 'unescapeDatabaseName',
173
+ // Defaults to global regex representing the following
174
+ // (characters nevertheless commonly reserved in modern,
175
+ // Unicode-supporting systems): 0x00-0x1F 0x7F " * / : < > ? \ |
176
+ 'databaseCharacterEscapeList',
177
+ // Defaults to 254 (shortest typical modern file length limit)
178
+ 'databaseNameLengthLimit',
179
+ // Boolean defaulting to true on whether to escape NFD-escaping
180
+ // characters to avoid clashes on MacOS which performs NFD on files
181
+ 'escapeNFDForDatabaseNames',
182
+ // Boolean on whether to add the `.sqlite` extension to file names;
183
+ // defaults to `true`
184
+ 'addSQLiteExtension',
185
+ // Various types of in-memory databases that can auto-delete
186
+ ['memoryDatabase',
187
+ /**
188
+ * @param {string} val
189
+ * @throws {TypeError}
190
+ * @returns {void}
191
+ */
192
+ val => {
193
+ if (!/^(?::memory:|file::memory:(\?[^#]*)?(#.*)?)?$/u.test(/** @type {string} */val)) {
194
+ throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a ' + '"file::memory:[?queryString][#hash] URL".');
65
195
  }
66
- };
67
- }
68
- function _iterableToArray(r) {
69
- if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
70
- }
71
- function _iterableToArrayLimit(r, l) {
72
- var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
73
- if (null != t) {
74
- var e,
75
- n,
76
- i,
77
- u,
78
- a = [],
79
- f = !0,
80
- o = !1;
81
- try {
82
- if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
83
- } catch (r) {
84
- o = !0, n = r;
85
- } finally {
86
- try {
87
- if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
88
- } finally {
89
- if (o) throw n;
90
- }
196
+ }],
197
+ // NODE-SPECIFIC CONFIG
198
+ // Boolean on whether to delete the database file itself after
199
+ // `deleteDatabase`; defaults to `true` as the database will be empty
200
+ 'deleteDatabaseFiles', 'databaseBasePath', 'sysDatabaseBasePath',
201
+ // NODE-SPECIFIC WEBSQL CONFIG
202
+ 'sqlBusyTimeout',
203
+ // Defaults to 1000
204
+ 'sqlTrace',
205
+ // Callback not used by default
206
+ 'sqlProfile',
207
+ // Callback not used by default
208
+
209
+ 'createIndexes'].forEach(prop => {
210
+ /** @type {(val: any) => void} */
211
+ let validator;
212
+ if (Array.isArray(prop)) {
213
+ [prop, validator] = prop;
91
214
  }
92
- return a;
93
- }
94
- }
95
- function _nonIterableRest() {
96
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
97
- }
98
- function _nonIterableSpread() {
99
- throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
100
- }
101
- function _slicedToArray(r, e) {
102
- return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
103
- }
104
- function _toConsumableArray(r) {
105
- return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
106
- }
107
- function _typeof(o) {
108
- "@babel/helpers - typeof";
109
-
110
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
111
- return typeof o;
112
- } : function (o) {
113
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
114
- }, _typeof(o);
115
- }
116
- function _unsupportedIterableToArray(r, a) {
117
- if (r) {
118
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
119
- var t = {}.toString.call(r).slice(8, -1);
120
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
121
- }
122
- }
123
-
124
- /* eslint-disable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */
125
- /**
126
- * @typedef {T[keyof T]} ValueOf<T>
127
- * @template T
128
- */
129
- /* eslint-enable jsdoc/valid-types -- https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/147 */
130
-
131
- /**
132
- * @typedef {{unlink: (path: string, cb: import('fs').NoParamCallback) => void}} FSApi
133
- */
134
-
135
- /**
136
- * @typedef {{
137
- * DEBUG: boolean,
138
- * cacheDatabaseInstances: boolean,
139
- * autoName: boolean,
140
- * fullIDLSupport: boolean,
141
- * checkOrigin: boolean,
142
- * cursorPreloadPackSize: number,
143
- * UnicodeIDStart: string,
144
- * UnicodeIDContinue: string,
145
- * registerSCA: (
146
- * preset: import('typeson').Preset
147
- * ) => import('typeson').Preset,
148
- * avoidAutoShim: boolean,
149
- * win: {
150
- * openDatabase: (name: string, version: string, displayName: string, estimatedSize: number) => import('websql-configurable').default
151
- * },
152
- * DEFAULT_DB_SIZE: number,
153
- * useSQLiteIndexes: boolean,
154
- * fs: FSApi,
155
- * addNonIDBGlobals: boolean,
156
- * replaceNonIDBGlobals: boolean,
157
- * escapeDatabaseName: (name: string) => string,
158
- * unescapeDatabaseName: (name: string) => string,
159
- * databaseCharacterEscapeList: string|false,
160
- * databaseNameLengthLimit: number|false,
161
- * escapeNFDForDatabaseNames: boolean,
162
- * addSQLiteExtension: boolean,
163
- * memoryDatabase: string,
164
- * deleteDatabaseFiles: boolean,
165
- * databaseBasePath: string,
166
- * sysDatabaseBasePath: string,
167
- * sqlBusyTimeout: number,
168
- * sqlTrace: () => void,
169
- * sqlProfile: () => void,
170
- * createIndexes: boolean
171
- * }} ConfigValues
172
- */
173
-
174
- /**
175
- * @typedef {ValueOf<ConfigValues>} ConfigValue
176
- */
177
-
178
- /** @type {{[key: string]: ConfigValue}} */
179
- var map = {};
180
- var CFG = /** @type {ConfigValues} */{};
181
-
182
- /**
183
- * @typedef {keyof ConfigValues} KeyofConfigValues
184
- */
185
-
186
- /**
187
- * @typedef {KeyofConfigValues[]} Config
188
- */
189
-
190
- /** @type {Config} */
191
- [
192
- // Boolean for verbose reporting
193
- 'DEBUG',
194
- // Effectively defaults to false (ignored unless `true`)
195
-
196
- // Boolean (effectively defaults to true) on whether to cache WebSQL
197
- // `openDatabase` instances
198
- 'cacheDatabaseInstances',
199
- // Boolean on whether to auto-name databases (based on an
200
- // auto-increment) when the empty string is supplied; useful with
201
- // `memoryDatabase`; defaults to `false` which means the empty string
202
- // will be used as the (valid) database name
203
- 'autoName',
204
- // Determines whether the slow-performing `Object.setPrototypeOf`
205
- // calls required for full WebIDL compliance will be used. Probably
206
- // only needed for testing or environments where full introspection
207
- // on class relationships is required; see
208
- // http://stackoverflow.com/questions/41927589/rationales-consequences-of-webidl-class-inheritance-requirements
209
- 'fullIDLSupport',
210
- // Effectively defaults to false (ignored unless `true`)
211
-
212
- // Boolean on whether to perform origin checks in `IDBFactory` methods
213
- // Effectively defaults to `true` (must be set to `false` to cancel checks)
214
- 'checkOrigin',
215
- // Used by `IDBCursor` continue methods for number of records to cache;
216
- // Defaults to 100
217
- 'cursorPreloadPackSize',
218
- // See optional API (`shimIndexedDB.__setUnicodeIdentifiers`);
219
- // or just use the Unicode builds which invoke this method
220
- // automatically using the large, fully spec-compliant, regular
221
- // expression strings of `src/UnicodeIdentifiers.js`)
222
- // In the non-Unicode builds, defaults to /[$A-Z_a-z]/
223
- 'UnicodeIDStart',
224
- // In the non-Unicode builds, defaults to /[$0-9A-Z_a-z]/
225
- 'UnicodeIDContinue',
226
- // Used by SCA.js for optional restructuring of typeson-registry
227
- // Structured Cloning Algorithm; should only be needed for ensuring data
228
- // created in 3.* versions of IndexedDBShim continue to work; see the
229
- // library `typeson-registry-sca-reverter` to get a function to do this
230
- 'registerSCA',
231
- // BROWSER-SPECIFIC CONFIG
232
- 'avoidAutoShim',
233
- // Where WebSQL is detected but where `indexedDB` is
234
- // missing or poor support is known (non-Chrome Android or
235
- // non-Safari iOS9), the shim will be auto-applied without
236
- // `shimIndexedDB.__useShim()`. Set this to `true` to avoid forcing
237
- // the shim for such cases.
238
-
239
- // -----------SQL CONFIG----------
240
- // Object (`window` in the browser) on which there may be an
241
- // `openDatabase` method (if any) for WebSQL. (The browser
242
- // throws if attempting to call `openDatabase` without the window
243
- // so this is why the config doesn't just allow the function.)
244
- // Defaults to `window` or `self` in browser builds or
245
- // a singleton object with the `openDatabase` method set to
246
- // the "websql" package in Node.
247
- 'win',
248
- // For internal `openDatabase` calls made by `IDBFactory` methods;
249
- // per the WebSQL spec, "User agents are expected to use the display name
250
- // and the estimated database size to optimize the user experience.
251
- // For example, a user agent could use the estimated size to suggest an
252
- // initial quota to the user. This allows a site that is aware that it
253
- // will try to use hundreds of megabytes to declare this upfront, instead
254
- // of the user agent prompting the user for permission to increase the
255
- // quota every five megabytes."
256
- // Defaults to (4 * 1024 * 1024) or (25 * 1024 * 1024) in Safari
257
- 'DEFAULT_DB_SIZE',
258
- // Whether to create indexes on SQLite tables (and also whether to try
259
- // dropping)
260
- // Effectively defaults to `false` (ignored unless `true`)
261
- 'useSQLiteIndexes',
262
- // NODE-IMPINGING SETTINGS (created for sake of limitations in Node
263
- // or desktop file system implementation but applied by default in
264
- // browser for parity)
265
-
266
- // File system module with `unlink` to remove deleted database files
267
- 'fs',
268
- // Used when setting global shims to determine whether to try to add
269
- // other globals shimmed by the library (`ShimDOMException`,
270
- // `ShimDOMStringList`, `ShimEvent`, `ShimCustomEvent`, `ShimEventTarget`)
271
- // Effectively defaults to `false` (ignored unless `true`)
272
- 'addNonIDBGlobals',
273
- // Used when setting global shims to determine whether to try to overwrite
274
- // other globals shimmed by the library (`DOMException`, `DOMStringList`,
275
- // `Event`, `CustomEvent`, `EventTarget`)
276
- // Effectively defaults to `false` (ignored unless `true`)
277
- 'replaceNonIDBGlobals',
278
- // Overcoming limitations with node-sqlite3/storing database name on
279
- // file systems
280
- // https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
281
- // Defaults to prefixing database with `D_`, escaping
282
- // `databaseCharacterEscapeList`, escaping NUL, and
283
- // escaping upper case letters, as well as enforcing
284
- // `databaseNameLengthLimit`
285
- 'escapeDatabaseName',
286
- // Not used internally; usable as a convenience method
287
- 'unescapeDatabaseName',
288
- // Defaults to global regex representing the following
289
- // (characters nevertheless commonly reserved in modern,
290
- // Unicode-supporting systems): 0x00-0x1F 0x7F " * / : < > ? \ |
291
- 'databaseCharacterEscapeList',
292
- // Defaults to 254 (shortest typical modern file length limit)
293
- 'databaseNameLengthLimit',
294
- // Boolean defaulting to true on whether to escape NFD-escaping
295
- // characters to avoid clashes on MacOS which performs NFD on files
296
- 'escapeNFDForDatabaseNames',
297
- // Boolean on whether to add the `.sqlite` extension to file names;
298
- // defaults to `true`
299
- 'addSQLiteExtension',
300
- // Various types of in-memory databases that can auto-delete
301
- ['memoryDatabase',
302
- /**
303
- * @param {string} val
304
- * @throws {TypeError}
305
- * @returns {void}
306
- */
307
- function (val) {
308
- if (!/^(?::memory:|file::memory:(\?(?:[\0-"\$-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?(#(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?)?$/.test(/** @type {string} */val)) {
309
- throw new TypeError('`memoryDatabase` must be the empty string, ":memory:", or a ' + '"file::memory:[?queryString][#hash] URL".');
310
- }
311
- }],
312
- // NODE-SPECIFIC CONFIG
313
- // Boolean on whether to delete the database file itself after
314
- // `deleteDatabase`; defaults to `true` as the database will be empty
315
- 'deleteDatabaseFiles', 'databaseBasePath', 'sysDatabaseBasePath',
316
- // NODE-SPECIFIC WEBSQL CONFIG
317
- 'sqlBusyTimeout',
318
- // Defaults to 1000
319
- 'sqlTrace',
320
- // Callback not used by default
321
- 'sqlProfile',
322
- // Callback not used by default
323
-
324
- 'createIndexes'].forEach(function (prop) {
325
- /** @type {(val: any) => void} */
326
- var validator;
327
- if (Array.isArray(prop)) {
328
- var _prop = prop;
329
- var _prop2 = _slicedToArray(_prop, 2);
330
- prop = _prop2[0];
331
- validator = _prop2[1];
332
- }
333
- Object.defineProperty(CFG, prop, {
334
- get: function get() {
335
- return map[prop];
336
- },
337
- set: function set(val) {
338
- if (validator) {
339
- validator(val);
215
+ Object.defineProperty(CFG, prop, {
216
+ get() {
217
+ return map[prop];
218
+ },
219
+ set(val) {
220
+ if (validator) {
221
+ validator(val);
222
+ }
223
+ map[prop] = val;
340
224
  }
341
- map[prop] = val;
342
- }
225
+ });
343
226
  });
344
- });
345
-
346
- /**
347
- * Creates a native DOMException, for browsers that support it.
348
- * @param {string} name
349
- * @param {string} message
350
- * @returns {DOMException}
351
- */
352
- function createNativeDOMException(name, message) {
353
- // @ts-expect-error It's ok
354
- return new DOMException.prototype.constructor(message, name || 'DOMException');
355
- }
356
-
357
- // From web-platform-tests testharness.js name_code_map (though not in new spec)
358
-
359
- /**
360
- * @typedef {"IndexSizeError"|"HierarchyRequestError"|"WrongDocumentError"|
361
- * "InvalidCharacterError"|"NoModificationAllowedError"|"NotFoundError"|
362
- * "NotSupportedError"|"InUseAttributeError"|"InvalidStateError"|
363
- * "SyntaxError"|"InvalidModificationError"|"NamespaceError"|
364
- * "InvalidAccessError"|"TypeMismatchError"|"SecurityError"|
365
- * "NetworkError"|"AbortError"|"URLMismatchError"|"QuotaExceededError"|
366
- * "TimeoutError"|"InvalidNodeTypeError"|"DataCloneError"|"EncodingError"|
367
- * "NotReadableError"|"UnknownError"|"ConstraintError"|"DataError"|
368
- * "TransactionInactiveError"|"ReadOnlyError"|"VersionError"|
369
- * "OperationError"|"NotAllowedError"} Code
370
- */
371
-
372
- var codes = {
373
- IndexSizeError: 1,
374
- HierarchyRequestError: 3,
375
- WrongDocumentError: 4,
376
- InvalidCharacterError: 5,
377
- NoModificationAllowedError: 7,
378
- NotFoundError: 8,
379
- NotSupportedError: 9,
380
- InUseAttributeError: 10,
381
- InvalidStateError: 11,
382
- SyntaxError: 12,
383
- InvalidModificationError: 13,
384
- NamespaceError: 14,
385
- InvalidAccessError: 15,
386
- TypeMismatchError: 17,
387
- SecurityError: 18,
388
- NetworkError: 19,
389
- AbortError: 20,
390
- URLMismatchError: 21,
391
- QuotaExceededError: 22,
392
- TimeoutError: 23,
393
- InvalidNodeTypeError: 24,
394
- DataCloneError: 25,
395
- EncodingError: 0,
396
- NotReadableError: 0,
397
- UnknownError: 0,
398
- ConstraintError: 0,
399
- DataError: 0,
400
- TransactionInactiveError: 0,
401
- ReadOnlyError: 0,
402
- VersionError: 0,
403
- OperationError: 0,
404
- NotAllowedError: 0
405
- };
406
-
407
- /**
408
- * @typedef {"INDEX_SIZE_ERR"|"DOMSTRING_SIZE_ERR"|"HIERARCHY_REQUEST_ERR"|
409
- * "WRONG_DOCUMENT_ERR"|"INVALID_CHARACTER_ERR"|"NO_DATA_ALLOWED_ERR"|
410
- * "NO_MODIFICATION_ALLOWED_ERR"|"NOT_FOUND_ERR"|"NOT_SUPPORTED_ERR"|
411
- * "INUSE_ATTRIBUTE_ERR"|"INVALID_STATE_ERR"|"SYNTAX_ERR"|
412
- * "INVALID_MODIFICATION_ERR"|"NAMESPACE_ERR"|"INVALID_ACCESS_ERR"|
413
- * "VALIDATION_ERR"|"TYPE_MISMATCH_ERR"|"SECURITY_ERR"|"NETWORK_ERR"|
414
- * "ABORT_ERR"|"URL_MISMATCH_ERR"|"QUOTA_EXCEEDED_ERR"|"TIMEOUT_ERR"|
415
- * "INVALID_NODE_TYPE_ERR"|"DATA_CLONE_ERR"} LegacyCode
416
- */
417
-
418
- var legacyCodes = {
419
- INDEX_SIZE_ERR: 1,
420
- DOMSTRING_SIZE_ERR: 2,
421
- HIERARCHY_REQUEST_ERR: 3,
422
- WRONG_DOCUMENT_ERR: 4,
423
- INVALID_CHARACTER_ERR: 5,
424
- NO_DATA_ALLOWED_ERR: 6,
425
- NO_MODIFICATION_ALLOWED_ERR: 7,
426
- NOT_FOUND_ERR: 8,
427
- NOT_SUPPORTED_ERR: 9,
428
- INUSE_ATTRIBUTE_ERR: 10,
429
- INVALID_STATE_ERR: 11,
430
- SYNTAX_ERR: 12,
431
- INVALID_MODIFICATION_ERR: 13,
432
- NAMESPACE_ERR: 14,
433
- INVALID_ACCESS_ERR: 15,
434
- VALIDATION_ERR: 16,
435
- TYPE_MISMATCH_ERR: 17,
436
- SECURITY_ERR: 18,
437
- NETWORK_ERR: 19,
438
- ABORT_ERR: 20,
439
- URL_MISMATCH_ERR: 21,
440
- QUOTA_EXCEEDED_ERR: 22,
441
- TIMEOUT_ERR: 23,
442
- INVALID_NODE_TYPE_ERR: 24,
443
- DATA_CLONE_ERR: 25
444
- };
445
-
446
- /**
447
- *
448
- * @returns {typeof DOMException}
449
- */
450
- function createNonNativeDOMExceptionClass() {
451
- /**
452
- * @param {string|undefined} message
453
- * @param {Code|LegacyCode} name
454
- * @returns {void}
227
+
228
+ /**
229
+ * Creates a native DOMException, for browsers that support it.
230
+ * @param {string} name
231
+ * @param {string} message
232
+ * @returns {DOMException}
455
233
  */
456
- function DOMException(message, name) {
457
- // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message
458
- this[Symbol.toStringTag] = 'DOMException';
459
- this._code = name in codes ? codes[(/** @type {Code} */name)] : legacyCodes[(/** @type {LegacyCode} */name)] || 0;
460
- this._name = name || 'Error';
461
- // We avoid `String()` in this next line as it converts Symbols
462
- this._message = message === undefined ? '' : '' + message; // eslint-disable-line no-implicit-coercion -- Don't convert symbols
463
- Object.defineProperty(this, 'code', {
464
- configurable: true,
465
- enumerable: true,
466
- writable: true,
467
- value: this._code
468
- });
469
- if (name !== undefined) {
470
- Object.defineProperty(this, 'name', {
234
+ function createNativeDOMException(name, message) {
235
+ // @ts-expect-error It's ok
236
+ return new DOMException.prototype.constructor(message, name || 'DOMException');
237
+ }
238
+
239
+ // From web-platform-tests testharness.js name_code_map (though not in new spec)
240
+
241
+ /**
242
+ * @typedef {"IndexSizeError"|"HierarchyRequestError"|"WrongDocumentError"|
243
+ * "InvalidCharacterError"|"NoModificationAllowedError"|"NotFoundError"|
244
+ * "NotSupportedError"|"InUseAttributeError"|"InvalidStateError"|
245
+ * "SyntaxError"|"InvalidModificationError"|"NamespaceError"|
246
+ * "InvalidAccessError"|"TypeMismatchError"|"SecurityError"|
247
+ * "NetworkError"|"AbortError"|"URLMismatchError"|"QuotaExceededError"|
248
+ * "TimeoutError"|"InvalidNodeTypeError"|"DataCloneError"|"EncodingError"|
249
+ * "NotReadableError"|"UnknownError"|"ConstraintError"|"DataError"|
250
+ * "TransactionInactiveError"|"ReadOnlyError"|"VersionError"|
251
+ * "OperationError"|"NotAllowedError"} Code
252
+ */
253
+
254
+ const codes = {
255
+ IndexSizeError: 1,
256
+ HierarchyRequestError: 3,
257
+ WrongDocumentError: 4,
258
+ InvalidCharacterError: 5,
259
+ NoModificationAllowedError: 7,
260
+ NotFoundError: 8,
261
+ NotSupportedError: 9,
262
+ InUseAttributeError: 10,
263
+ InvalidStateError: 11,
264
+ SyntaxError: 12,
265
+ InvalidModificationError: 13,
266
+ NamespaceError: 14,
267
+ InvalidAccessError: 15,
268
+ TypeMismatchError: 17,
269
+ SecurityError: 18,
270
+ NetworkError: 19,
271
+ AbortError: 20,
272
+ URLMismatchError: 21,
273
+ QuotaExceededError: 22,
274
+ TimeoutError: 23,
275
+ InvalidNodeTypeError: 24,
276
+ DataCloneError: 25,
277
+ EncodingError: 0,
278
+ NotReadableError: 0,
279
+ UnknownError: 0,
280
+ ConstraintError: 0,
281
+ DataError: 0,
282
+ TransactionInactiveError: 0,
283
+ ReadOnlyError: 0,
284
+ VersionError: 0,
285
+ OperationError: 0,
286
+ NotAllowedError: 0
287
+ };
288
+
289
+ /**
290
+ * @typedef {"INDEX_SIZE_ERR"|"DOMSTRING_SIZE_ERR"|"HIERARCHY_REQUEST_ERR"|
291
+ * "WRONG_DOCUMENT_ERR"|"INVALID_CHARACTER_ERR"|"NO_DATA_ALLOWED_ERR"|
292
+ * "NO_MODIFICATION_ALLOWED_ERR"|"NOT_FOUND_ERR"|"NOT_SUPPORTED_ERR"|
293
+ * "INUSE_ATTRIBUTE_ERR"|"INVALID_STATE_ERR"|"SYNTAX_ERR"|
294
+ * "INVALID_MODIFICATION_ERR"|"NAMESPACE_ERR"|"INVALID_ACCESS_ERR"|
295
+ * "VALIDATION_ERR"|"TYPE_MISMATCH_ERR"|"SECURITY_ERR"|"NETWORK_ERR"|
296
+ * "ABORT_ERR"|"URL_MISMATCH_ERR"|"QUOTA_EXCEEDED_ERR"|"TIMEOUT_ERR"|
297
+ * "INVALID_NODE_TYPE_ERR"|"DATA_CLONE_ERR"} LegacyCode
298
+ */
299
+
300
+ const legacyCodes = {
301
+ INDEX_SIZE_ERR: 1,
302
+ DOMSTRING_SIZE_ERR: 2,
303
+ HIERARCHY_REQUEST_ERR: 3,
304
+ WRONG_DOCUMENT_ERR: 4,
305
+ INVALID_CHARACTER_ERR: 5,
306
+ NO_DATA_ALLOWED_ERR: 6,
307
+ NO_MODIFICATION_ALLOWED_ERR: 7,
308
+ NOT_FOUND_ERR: 8,
309
+ NOT_SUPPORTED_ERR: 9,
310
+ INUSE_ATTRIBUTE_ERR: 10,
311
+ INVALID_STATE_ERR: 11,
312
+ SYNTAX_ERR: 12,
313
+ INVALID_MODIFICATION_ERR: 13,
314
+ NAMESPACE_ERR: 14,
315
+ INVALID_ACCESS_ERR: 15,
316
+ VALIDATION_ERR: 16,
317
+ TYPE_MISMATCH_ERR: 17,
318
+ SECURITY_ERR: 18,
319
+ NETWORK_ERR: 19,
320
+ ABORT_ERR: 20,
321
+ URL_MISMATCH_ERR: 21,
322
+ QUOTA_EXCEEDED_ERR: 22,
323
+ TIMEOUT_ERR: 23,
324
+ INVALID_NODE_TYPE_ERR: 24,
325
+ DATA_CLONE_ERR: 25
326
+ };
327
+
328
+ /**
329
+ *
330
+ * @returns {typeof DOMException}
331
+ */
332
+ function createNonNativeDOMExceptionClass() {
333
+ /**
334
+ * @param {string|undefined} message
335
+ * @param {Code|LegacyCode} name
336
+ * @returns {void}
337
+ */
338
+ function DOMException(message, name) {
339
+ // const err = Error.prototype.constructor.call(this, message); // Any use to this? Won't set this.message
340
+ this[Symbol.toStringTag] = 'DOMException';
341
+ this._code = name in codes ? codes[(/** @type {Code} */name)] : legacyCodes[(/** @type {LegacyCode} */name)] || 0;
342
+ this._name = name || 'Error';
343
+ // We avoid `String()` in this next line as it converts Symbols
344
+ this._message = message === undefined ? '' : '' + message; // eslint-disable-line no-implicit-coercion -- Don't convert symbols
345
+ Object.defineProperty(this, 'code', {
471
346
  configurable: true,
472
347
  enumerable: true,
473
348
  writable: true,
474
- value: this._name
475
- });
476
- }
477
- if (message !== undefined) {
478
- Object.defineProperty(this, 'message', {
479
- configurable: true,
480
- enumerable: false,
481
- writable: true,
482
- value: this._message
349
+ value: this._code
483
350
  });
351
+ if (name !== undefined) {
352
+ Object.defineProperty(this, 'name', {
353
+ configurable: true,
354
+ enumerable: true,
355
+ writable: true,
356
+ value: this._name
357
+ });
358
+ }
359
+ if (message !== undefined) {
360
+ Object.defineProperty(this, 'message', {
361
+ configurable: true,
362
+ enumerable: false,
363
+ writable: true,
364
+ value: this._message
365
+ });
366
+ }
484
367
  }
485
- }
486
368
 
487
- // Necessary for W3C tests which complains if `DOMException` has properties on its "own" prototype
369
+ // Necessary for W3C tests which complains if `DOMException` has properties on its "own" prototype
488
370
 
489
- // class DummyDOMException extends Error {}; // Sometimes causing problems in Node
490
- /* eslint-disable func-name-matching -- See above */
491
- /**
492
- * @class
493
- */
494
- var DummyDOMException = function DOMException() {/* */};
495
- /* eslint-enable func-name-matching -- See above */
496
- DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing
497
- /** @type {const} */
498
- ['name', 'message'].forEach(function (prop) {
499
- Object.defineProperty(DummyDOMException.prototype, prop, {
500
- enumerable: true,
501
- /**
502
- * @this {DOMException}
503
- * @returns {string}
504
- */
505
- get: function get() {
506
- if (!(this instanceof DOMException ||
507
- // @ts-expect-error Just checking
508
- this instanceof DummyDOMException ||
509
- // @ts-expect-error Just checking
510
- this instanceof Error)) {
511
- throw new TypeError('Illegal invocation');
371
+ // class DummyDOMException extends Error {}; // Sometimes causing problems in Node
372
+ /* eslint-disable func-name-matching -- See above */
373
+ /**
374
+ * @class
375
+ */
376
+ const DummyDOMException = function DOMException() {/* */};
377
+ /* eslint-enable func-name-matching -- See above */
378
+ DummyDOMException.prototype = Object.create(Error.prototype); // Intended for subclassing
379
+ /** @type {const} */
380
+ ['name', 'message'].forEach(prop => {
381
+ Object.defineProperty(DummyDOMException.prototype, prop, {
382
+ enumerable: true,
383
+ /**
384
+ * @this {DOMException}
385
+ * @returns {string}
386
+ */
387
+ get() {
388
+ if (!(this instanceof DOMException ||
389
+ // @ts-expect-error Just checking
390
+ this instanceof DummyDOMException ||
391
+ // @ts-expect-error Just checking
392
+ this instanceof Error)) {
393
+ throw new TypeError('Illegal invocation');
394
+ }
395
+ return this[prop === 'name' ? '_name' : '_message'];
512
396
  }
513
- return this[prop === 'name' ? '_name' : '_message'];
514
- }
397
+ });
515
398
  });
516
- });
517
- // DOMException uses the same `toString` as `Error`
518
- Object.defineProperty(DummyDOMException.prototype, 'code', {
519
- configurable: true,
520
- enumerable: true,
521
- get: function get() {
522
- throw new TypeError('Illegal invocation');
523
- }
524
- });
525
- // @ts-expect-error It's ok
526
- DOMException.prototype = new DummyDOMException();
527
- DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';
528
- Object.defineProperty(DOMException, 'prototype', {
529
- writable: false
530
- });
531
- var keys = Object.keys(codes);
532
-
533
- /** @type {(keyof codes)[]} */
534
- keys.forEach(function (codeName) {
535
- Object.defineProperty(DOMException.prototype, codeName, {
399
+ // DOMException uses the same `toString` as `Error`
400
+ Object.defineProperty(DummyDOMException.prototype, 'code', {
401
+ configurable: true,
536
402
  enumerable: true,
537
- configurable: false,
538
- value: codes[codeName]
403
+ get() {
404
+ throw new TypeError('Illegal invocation');
405
+ }
539
406
  });
540
- Object.defineProperty(DOMException, codeName, {
541
- enumerable: true,
542
- configurable: false,
543
- value: codes[codeName]
407
+ // @ts-expect-error It's ok
408
+ DOMException.prototype = new DummyDOMException();
409
+ DOMException.prototype[Symbol.toStringTag] = 'DOMExceptionPrototype';
410
+ Object.defineProperty(DOMException, 'prototype', {
411
+ writable: false
544
412
  });
545
- });
546
- /** @type {(keyof legacyCodes)[]} */
547
- Object.keys(legacyCodes).forEach(function (codeName) {
548
- Object.defineProperty(DOMException.prototype, codeName, {
549
- enumerable: true,
550
- configurable: false,
551
- value: legacyCodes[codeName]
413
+ const keys = Object.keys(codes);
414
+
415
+ /** @type {(keyof codes)[]} */
416
+ keys.forEach(codeName => {
417
+ Object.defineProperty(DOMException.prototype, codeName, {
418
+ enumerable: true,
419
+ configurable: false,
420
+ value: codes[codeName]
421
+ });
422
+ Object.defineProperty(DOMException, codeName, {
423
+ enumerable: true,
424
+ configurable: false,
425
+ value: codes[codeName]
426
+ });
552
427
  });
553
- Object.defineProperty(DOMException, codeName, {
554
- enumerable: true,
555
- configurable: false,
556
- value: legacyCodes[codeName]
428
+ /** @type {(keyof legacyCodes)[]} */
429
+ Object.keys(legacyCodes).forEach(codeName => {
430
+ Object.defineProperty(DOMException.prototype, codeName, {
431
+ enumerable: true,
432
+ configurable: false,
433
+ value: legacyCodes[codeName]
434
+ });
435
+ Object.defineProperty(DOMException, codeName, {
436
+ enumerable: true,
437
+ configurable: false,
438
+ value: legacyCodes[codeName]
439
+ });
440
+ });
441
+ Object.defineProperty(DOMException.prototype, 'constructor', {
442
+ writable: true,
443
+ configurable: true,
444
+ enumerable: false,
445
+ value: DOMException
557
446
  });
558
- });
559
- Object.defineProperty(DOMException.prototype, 'constructor', {
560
- writable: true,
561
- configurable: true,
562
- enumerable: false,
563
- value: DOMException
564
- });
565
447
 
566
- // @ts-expect-error We don't need all its properties
567
- return DOMException;
568
- }
569
- var ShimNonNativeDOMException = createNonNativeDOMExceptionClass();
570
-
571
- /**
572
- * Creates a generic Error object.
573
- * @param {string} name
574
- * @param {string} message
575
- * @returns {Error}
576
- */
577
- function createNonNativeDOMException(name, message) {
578
- return new ShimNonNativeDOMException(message, name);
579
- }
580
-
581
- /**
582
- * @typedef {{
583
- * message: string|DOMString
584
- * }} ErrorLike
585
- */
586
-
587
- /**
588
- * Logs detailed error information to the console.
589
- * @param {string} name
590
- * @param {string} message
591
- * @param {string|ErrorLike|boolean|null} [error]
592
- * @returns {void}
593
- */
594
- function logError(name, message, error) {
595
- if (CFG.DEBUG) {
596
- var msg = error && _typeof(error) === 'object' && error.message ? error.message : (/** @type {string} */error);
597
- var method = typeof console.error === 'function' ? 'error' : 'log';
598
- console[method](name + ': ' + message + '. ' + (msg || ''));
599
- if (console.trace) {
600
- console.trace();
601
- }
448
+ // @ts-expect-error We don't need all its properties
449
+ return DOMException;
602
450
  }
603
- }
604
-
605
- /**
606
- * @typedef {any} ArbitraryValue
607
- */
608
-
609
- /**
610
- * @param {ArbitraryValue} obj
611
- * @returns {boolean}
612
- */
613
- function isErrorOrDOMErrorOrDOMException(obj) {
614
- return obj && _typeof(obj) === 'object' &&
615
- // We don't use util.isObj here as mutual dependency causing problems in Babel with browser
616
- typeof obj.name === 'string';
617
- }
618
- var test,
619
- useNativeDOMException = false;
620
-
621
- // Test whether we can use the browser's native DOMException class
622
- try {
623
- test = createNativeDOMException('test name', 'test message');
624
- if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {
625
- // Native DOMException works as expected
626
- useNativeDOMException = true;
451
+ const ShimNonNativeDOMException = createNonNativeDOMExceptionClass();
452
+
453
+ /**
454
+ * Creates a generic Error object.
455
+ * @param {string} name
456
+ * @param {string} message
457
+ * @returns {Error}
458
+ */
459
+ function createNonNativeDOMException(name, message) {
460
+ return new ShimNonNativeDOMException(message, name);
627
461
  }
628
- // eslint-disable-next-line no-unused-vars -- Problem with commonJS rollup
629
- } catch (err) {}
630
- var createDOMException = useNativeDOMException
631
- // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
632
- ?
633
- /**
634
- * @param {string} name
635
- * @param {string} message
636
- * @param {ErrorLike} [error]
637
- * @returns {DOMException}
638
- */
639
- function (name, message, error) {
640
- logError(name, message, error);
641
- return createNativeDOMException(name, message);
642
- }
643
- // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
644
- :
645
- /**
646
- * @param {string} name
647
- * @param {string} message
648
- * @param {ErrorLike} [error]
649
- * @returns {Error}
650
- */
651
- function (name, message, error) {
652
- logError(name, message, error);
653
- return createNonNativeDOMException(name, message);
654
- };
655
-
656
- /**
657
- * @typedef {number} Integer
658
- */
659
-
660
- /**
661
- * @param {string} arg
662
- * @returns {string}
663
- */
664
- function escapeUnmatchedSurrogates(arg) {
665
- // http://stackoverflow.com/a/6701665/271577
666
- return arg.replaceAll(/((?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])))(?!(?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))|(^|(?:[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))((?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g, function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {
667
- // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577
668
- // but Chrome having problems
669
- if (unmatchedHighSurrogate) {
670
- return '^2' + unmatchedHighSurrogate.codePointAt().toString(16).padStart(4, '0');
671
- }
672
- return (precedingLow || '') + '^3' + unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');
673
- });
674
- }
675
-
676
- /**
677
- * The escaping of unmatched surrogates was needed by Chrome but not Node.
678
- * @param {string} arg
679
- * @returns {string}
680
- */
681
- function escapeSQLiteStatement(arg) {
682
- return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\0', '^0'));
683
- }
684
-
685
- /**
686
- *
687
- * @param {AnyValue} obj
688
- * @returns {obj is object}
689
- */
690
- function isObj(obj) {
691
- return obj !== null && _typeof(obj) === 'object';
692
- }
693
-
694
- /**
695
- *
696
- * @param {object} obj
697
- * @returns {boolean}
698
- */
699
- function isDate(obj) {
700
- return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';
701
- }
702
-
703
- /**
704
- *
705
- * @param {object} obj
706
- * @returns {boolean}
707
- */
708
- function isBlob(obj) {
709
- return isObj(obj) && 'size' in obj && typeof obj.size === 'number' && 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);
710
- }
711
-
712
- /**
713
- *
714
- * @param {object} obj
715
- * @returns {boolean}
716
- */
717
- function isFile(obj) {
718
- return isObj(obj) && 'name' in obj && typeof obj.name === 'string' && 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;
719
- }
720
-
721
- /**
722
- *
723
- * @param {AnyValue} obj
724
- * @returns {boolean}
725
- */
726
- function isBinary(obj) {
727
- return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && ('slice' in obj && typeof obj.slice === 'function' ||
728
- // `TypedArray` (view on buffer) or `ArrayBuffer`
729
- 'getFloat64' in obj && typeof obj.getFloat64 === 'function' // `DataView` (view on buffer)
730
- );
731
- }
732
-
733
- /**
734
- * @param {AnyValue} v
735
- * @returns {v is null|undefined}
736
- */
737
- function isNullish(v) {
738
- return v === null || v === undefined;
739
- }
740
-
741
- /**
742
- * Compares two keys.
743
- * @param {import('./Key.js').Key} first
744
- * @param {import('./Key.js').Key} second
745
- * @returns {0|1|-1}
746
- */
747
- function cmp(first, second) {
748
- var encodedKey1 = /** @type {string} */_encode(first);
749
- var encodedKey2 = /** @type {string} */_encode(second);
750
- var result = encodedKey1 > encodedKey2 ? 1 : encodedKey1 === encodedKey2 ? 0 : -1;
751
- if (CFG.DEBUG) {
752
- // verify that the keys encoded correctly
753
- var decodedKey1 = _decode(encodedKey1);
754
- var decodedKey2 = _decode(encodedKey2);
755
- if (_typeof(first) === 'object') {
756
- first = JSON.stringify(first);
757
- decodedKey1 = JSON.stringify(decodedKey1);
758
- }
759
- if (_typeof(second) === 'object') {
760
- second = JSON.stringify(second);
761
- decodedKey2 = JSON.stringify(decodedKey2);
462
+
463
+ /**
464
+ * @typedef {{
465
+ * message: string|DOMString
466
+ * }} ErrorLike
467
+ */
468
+
469
+ /**
470
+ * Logs detailed error information to the console.
471
+ * @param {string} name
472
+ * @param {string} message
473
+ * @param {string|ErrorLike|boolean|null} [error]
474
+ * @returns {void}
475
+ */
476
+ function logError(name, message, error) {
477
+ if (CFG.DEBUG) {
478
+ const msg = error && typeof error === 'object' && error.message ? error.message : (/** @type {string} */error);
479
+ const method = typeof console.error === 'function' ? 'error' : 'log';
480
+ console[method](name + ': ' + message + '. ' + (msg || ''));
481
+ if (console.trace) {
482
+ console.trace();
483
+ }
762
484
  }
485
+ }
763
486
 
764
- // Encoding/decoding mismatches are usually due to a loss of
765
- // floating-point precision
766
- if (decodedKey1 !== first) {
767
- console.warn(first + ' was incorrectly encoded as ' + decodedKey1);
487
+ /**
488
+ * @typedef {any} ArbitraryValue
489
+ */
490
+
491
+ /**
492
+ * @param {ArbitraryValue} obj
493
+ * @returns {boolean}
494
+ */
495
+ function isErrorOrDOMErrorOrDOMException(obj) {
496
+ return obj && typeof obj === 'object' &&
497
+ // We don't use util.isObj here as mutual dependency causing problems in Babel with browser
498
+ typeof obj.name === 'string';
499
+ }
500
+ let test,
501
+ useNativeDOMException = false;
502
+
503
+ // Test whether we can use the browser's native DOMException class
504
+ try {
505
+ test = createNativeDOMException('test name', 'test message');
506
+ if (isErrorOrDOMErrorOrDOMException(test) && test.name === 'test name' && test.message === 'test message') {
507
+ // Native DOMException works as expected
508
+ useNativeDOMException = true;
768
509
  }
769
- if (decodedKey2 !== second) {
770
- console.warn(second + ' was incorrectly encoded as ' + decodedKey2);
510
+ } catch (err) {}
511
+ const createDOMException = useNativeDOMException
512
+ // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
513
+ ?
514
+ /**
515
+ * @param {string} name
516
+ * @param {string} message
517
+ * @param {ErrorLike} [error]
518
+ * @returns {DOMException}
519
+ */
520
+ function (name, message, error) {
521
+ logError(name, message, error);
522
+ return createNativeDOMException(name, message);
523
+ }
524
+ // eslint-disable-next-line @stylistic/operator-linebreak -- Need JSDoc
525
+ :
526
+ /**
527
+ * @param {string} name
528
+ * @param {string} message
529
+ * @param {ErrorLike} [error]
530
+ * @returns {Error}
531
+ */
532
+ function (name, message, error) {
533
+ logError(name, message, error);
534
+ return createNonNativeDOMException(name, message);
535
+ };
536
+
537
+ /* eslint-disable new-cap -- ToString is how it is defined */
538
+ /* eslint-disable sonarjs/no-control-regex -- Needed */
539
+
540
+ /**
541
+ * @typedef {number} Integer
542
+ */
543
+
544
+ /**
545
+ * @param {string} arg
546
+ * @returns {string}
547
+ */
548
+ function escapeUnmatchedSurrogates(arg) {
549
+ // http://stackoverflow.com/a/6701665/271577
550
+ return arg.replaceAll(/([\uD800-\uDBFF])(?![\uDC00-\uDFFF])|(^|[^\uD800-\uDBFF])([\uDC00-\uDFFF])/gu, function (_, unmatchedHighSurrogate, precedingLow, unmatchedLowSurrogate) {
551
+ // Could add a corresponding surrogate for compatibility with `node-sqlite3`: http://bugs.python.org/issue12569 and http://stackoverflow.com/a/6701665/271577
552
+ // but Chrome having problems
553
+ if (unmatchedHighSurrogate) {
554
+ return '^2' + unmatchedHighSurrogate.codePointAt().toString(16).padStart(4, '0');
555
+ }
556
+ return (precedingLow || '') + '^3' + unmatchedLowSurrogate.codePointAt().toString(16).padStart(4, '0');
557
+ });
558
+ }
559
+
560
+ /**
561
+ * The escaping of unmatched surrogates was needed by Chrome but not Node.
562
+ * @param {string} arg
563
+ * @returns {string}
564
+ */
565
+ function escapeSQLiteStatement(arg) {
566
+ return escapeUnmatchedSurrogates(arg.replaceAll('^', '^^').replaceAll('\0', '^0'));
567
+ }
568
+
569
+ /**
570
+ *
571
+ * @param {AnyValue} obj
572
+ * @returns {obj is object}
573
+ */
574
+ function isObj(obj) {
575
+ return obj !== null && typeof obj === 'object';
576
+ }
577
+
578
+ /**
579
+ *
580
+ * @param {object} obj
581
+ * @returns {boolean}
582
+ */
583
+ function isDate(obj) {
584
+ return isObj(obj) && 'getDate' in obj && typeof obj.getDate === 'function';
585
+ }
586
+
587
+ /**
588
+ *
589
+ * @param {object} obj
590
+ * @returns {boolean}
591
+ */
592
+ function isBlob(obj) {
593
+ return isObj(obj) && 'size' in obj && typeof obj.size === 'number' && 'slice' in obj && typeof obj.slice === 'function' && !('lastModified' in obj);
594
+ }
595
+
596
+ /**
597
+ *
598
+ * @param {object} obj
599
+ * @returns {boolean}
600
+ */
601
+ function isFile(obj) {
602
+ return isObj(obj) && 'name' in obj && typeof obj.name === 'string' && 'slice' in obj && typeof obj.slice === 'function' && 'lastModified' in obj;
603
+ }
604
+
605
+ /**
606
+ *
607
+ * @param {AnyValue} obj
608
+ * @returns {boolean}
609
+ */
610
+ function isBinary(obj) {
611
+ return isObj(obj) && 'byteLength' in obj && typeof obj.byteLength === 'number' && ('slice' in obj && typeof obj.slice === 'function' ||
612
+ // `TypedArray` (view on buffer) or `ArrayBuffer`
613
+ 'getFloat64' in obj && typeof obj.getFloat64 === 'function' // `DataView` (view on buffer)
614
+ );
615
+ }
616
+
617
+ /**
618
+ * @param {AnyValue} v
619
+ * @returns {v is null|undefined}
620
+ */
621
+ function isNullish(v) {
622
+ return v === null || v === undefined;
623
+ }
624
+
625
+ /**
626
+ * Compares two keys.
627
+ * @param {import('./Key.js').Key} first
628
+ * @param {import('./Key.js').Key} second
629
+ * @returns {0|1|-1}
630
+ */
631
+ function cmp(first, second) {
632
+ const encodedKey1 = /** @type {string} */encode(first);
633
+ const encodedKey2 = /** @type {string} */encode(second);
634
+ const result = encodedKey1 > encodedKey2 ? 1 : encodedKey1 === encodedKey2 ? 0 : -1;
635
+ if (CFG.DEBUG) {
636
+ // verify that the keys encoded correctly
637
+ let decodedKey1 = decode(encodedKey1);
638
+ let decodedKey2 = decode(encodedKey2);
639
+ if (typeof first === 'object') {
640
+ first = JSON.stringify(first);
641
+ decodedKey1 = JSON.stringify(decodedKey1);
642
+ }
643
+ if (typeof second === 'object') {
644
+ second = JSON.stringify(second);
645
+ decodedKey2 = JSON.stringify(decodedKey2);
646
+ }
647
+
648
+ // Encoding/decoding mismatches are usually due to a loss of
649
+ // floating-point precision
650
+ if (decodedKey1 !== first) {
651
+ console.warn(first + ' was incorrectly encoded as ' + decodedKey1);
652
+ }
653
+ if (decodedKey2 !== second) {
654
+ console.warn(second + ' was incorrectly encoded as ' + decodedKey2);
655
+ }
771
656
  }
657
+ return result;
772
658
  }
773
- return result;
774
- }
775
-
776
- /**
777
- * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView
778
- */
779
-
780
- /**
781
- * @typedef {ArrayBufferView|ArrayBuffer} BufferSource
782
- */
783
-
784
- /**
785
- * @typedef {"number"|"date"|"string"|"binary"|"array"} KeyType
786
- */
787
-
788
- /**
789
- * @typedef {any} Value
790
- */
791
-
792
- /**
793
- * @typedef {any} Key
794
- * @todo Specify possible value more precisely
795
- */
796
-
797
- /**
798
- * @typedef {KeyPath[]} KeyPathArray
799
- */
800
- /**
801
- * @typedef {string|KeyPathArray} KeyPath
802
- */
803
-
804
- /**
805
- * @typedef {object} KeyValueObject
806
- * @property {KeyType|"NaN"|"null"|"undefined"|"boolean"|"object"|"symbol"|
807
- * "function"|"bigint"} type If not `KeyType`, indicates invalid value
808
- * @property {Value} [value]
809
- * @property {boolean} [invalid]
810
- * @property {string} [message]
811
- * @todo Specify acceptable `value` more precisely
812
- */
813
-
814
- /**
815
- * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive
816
- */
817
- /**
818
- * @typedef {ValueType[]} ValueTypeArray
819
- */
820
- /**
821
- * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType
822
- */
823
-
824
- /**
825
- * Encodes the keys based on their types. This is required to maintain collations
826
- * We leave space for future keys.
827
- * @type {{[key: string]: Integer|string}}
828
- */
829
- var keyTypeToEncodedChar = {
830
- invalid: 100,
831
- number: 200,
832
- date: 300,
833
- string: 400,
834
- binary: 500,
835
- array: 600
836
- };
837
- var keyTypes = /** @type {(KeyType|"invalid")[]} */Object.keys(keyTypeToEncodedChar);
838
- keyTypes.forEach(function (k) {
839
- keyTypeToEncodedChar[k] = String.fromCodePoint(/** @type {number} */keyTypeToEncodedChar[k]);
840
- });
841
- var encodedCharToKeyType = keyTypes.reduce(function (o, k) {
842
- o[keyTypeToEncodedChar[k]] = k;
843
- return o;
844
- }, /** @type {{[key: string]: KeyType|"invalid"}} */{});
845
-
846
- /**
847
- * The sign values for numbers, ordered from least to greatest.
848
- * - "negativeInfinity": Sorts below all other values.
849
- * - "bigNegative": Negative values less than or equal to negative one.
850
- * - "smallNegative": Negative values between negative one and zero, noninclusive.
851
- * - "smallPositive": Positive values between zero and one, including zero but not one.
852
- * - "largePositive": Positive values greater than or equal to one.
853
- * - "positiveInfinity": Sorts above all other values.
854
- */
855
- var signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];
856
-
857
- /**
858
- * @typedef {any} AnyValue
859
- */
860
-
861
- /**
862
- * @type {{
863
- * [key: string]: {
864
- * encode: (param: any, inArray?: boolean) => string,
865
- * decode: (param: string, inArray?: boolean) => any
866
- * }
867
- * }}
868
- */
869
- var types = {
870
- invalid: {
871
- /**
872
- * @returns {string}
873
- */
874
- encode: function encode() {
875
- return keyTypeToEncodedChar.invalid + '-';
659
+
660
+ /**
661
+ * @typedef {NodeJS.TypedArray|DataView} ArrayBufferView
662
+ */
663
+
664
+ /**
665
+ * @typedef {ArrayBufferView|ArrayBuffer} BufferSource
666
+ */
667
+
668
+ /**
669
+ * @typedef {"number"|"date"|"string"|"binary"|"array"} KeyType
670
+ */
671
+
672
+ /**
673
+ * @typedef {any} Value
674
+ */
675
+
676
+ /**
677
+ * @typedef {any} Key
678
+ * @todo Specify possible value more precisely
679
+ */
680
+
681
+ /**
682
+ * @typedef {KeyPath[]} KeyPathArray
683
+ */
684
+ /**
685
+ * @typedef {string|KeyPathArray} KeyPath
686
+ */
687
+
688
+ /**
689
+ * @typedef {object} KeyValueObject
690
+ * @property {KeyType|"NaN"|"null"|"undefined"|"boolean"|"object"|"symbol"|
691
+ * "function"|"bigint"} type If not `KeyType`, indicates invalid value
692
+ * @property {Value} [value]
693
+ * @property {boolean} [invalid]
694
+ * @property {string} [message]
695
+ * @todo Specify acceptable `value` more precisely
696
+ */
697
+
698
+ /**
699
+ * @typedef {number|string|Date|ArrayBuffer} ValueTypePrimitive
700
+ */
701
+ /**
702
+ * @typedef {ValueType[]} ValueTypeArray
703
+ */
704
+ /**
705
+ * @typedef {ValueTypePrimitive|ValueTypeArray} ValueType
706
+ */
707
+
708
+ /**
709
+ * Encodes the keys based on their types. This is required to maintain collations
710
+ * We leave space for future keys.
711
+ * @type {{[key: string]: Integer|string}}
712
+ */
713
+ const keyTypeToEncodedChar = {
714
+ invalid: 100,
715
+ number: 200,
716
+ date: 300,
717
+ string: 400,
718
+ binary: 500,
719
+ array: 600
720
+ };
721
+ const keyTypes = /** @type {(KeyType|"invalid")[]} */Object.keys(keyTypeToEncodedChar);
722
+ keyTypes.forEach(k => {
723
+ keyTypeToEncodedChar[k] = String.fromCodePoint(/** @type {number} */keyTypeToEncodedChar[k]);
724
+ });
725
+ const encodedCharToKeyType = keyTypes.reduce((o, k) => {
726
+ o[keyTypeToEncodedChar[k]] = k;
727
+ return o;
728
+ }, /** @type {{[key: string]: KeyType|"invalid"}} */{});
729
+
730
+ /**
731
+ * The sign values for numbers, ordered from least to greatest.
732
+ * - "negativeInfinity": Sorts below all other values.
733
+ * - "bigNegative": Negative values less than or equal to negative one.
734
+ * - "smallNegative": Negative values between negative one and zero, noninclusive.
735
+ * - "smallPositive": Positive values between zero and one, including zero but not one.
736
+ * - "largePositive": Positive values greater than or equal to one.
737
+ * - "positiveInfinity": Sorts above all other values.
738
+ */
739
+ const signValues = ['negativeInfinity', 'bigNegative', 'smallNegative', 'smallPositive', 'bigPositive', 'positiveInfinity'];
740
+
741
+ /**
742
+ * @typedef {any} AnyValue
743
+ */
744
+
745
+ /**
746
+ * @type {{
747
+ * [key: string]: {
748
+ * encode: (param: any, inArray?: boolean) => string,
749
+ * decode: (param: string, inArray?: boolean) => any
750
+ * }
751
+ * }}
752
+ */
753
+ const types = {
754
+ invalid: {
755
+ /**
756
+ * @returns {string}
757
+ */
758
+ encode() {
759
+ return keyTypeToEncodedChar.invalid + '-';
760
+ },
761
+ /**
762
+ * @returns {undefined}
763
+ */
764
+ decode() {
765
+ return undefined;
766
+ }
876
767
  },
877
- /**
878
- * @returns {undefined}
879
- */
880
- decode: function decode() {
881
- return undefined;
882
- }
883
- },
884
- // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa
885
- // notation.
886
- //
887
- // sign: takes a value between zero and five, inclusive. Represents infinite cases
888
- // and the signs of both the exponent and the fractional part of the number.
889
- // exponent: padded to two base-32 digits, represented by the 32's compliment in the
890
- // "smallPositive" and "bigNegative" cases to ensure proper lexical sorting.
891
- // mantissa: also called the fractional part. Normed 11-digit base-32 representation.
892
- // Represented by the 32's compliment in the "smallNegative" and "bigNegative"
893
- // cases to ensure proper lexical sorting.
894
- number: {
895
- // The encode step checks for six numeric cases and generates 14-digit encoded
896
- // sign-exponent-mantissa strings.
897
- /**
898
- * @param {number} key
899
- * @returns {string}
900
- */
901
- encode: function encode(key) {
902
- var key32 = key === Number.MIN_VALUE
903
- // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some
904
- // Node (and Chrome) versions with `Number.MIN_VALUE` being treated
905
- // as 0
906
- // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring
907
- ? '0.' + '0'.repeat(214) + '2' : Math.abs(key).toString(32);
908
- // Get the index of the decimal.
909
- var decimalIndex = key32.indexOf('.');
910
- // Remove the decimal.
911
- key32 = decimalIndex !== -1 ? key32.replace('.', '') : key32;
912
- // Get the index of the first significant digit.
913
- var significantDigitIndex = key32.search(/(?:[\0-\/1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/);
914
- // Truncate leading zeros.
915
- key32 = key32.slice(significantDigitIndex);
916
- var sign, exponent, mantissa;
917
-
918
- // Finite cases:
919
- if (Number.isFinite(Number(key))) {
920
- // Negative cases:
921
- if (key < 0) {
922
- // Negative exponent case:
923
- if (key > -1) {
924
- sign = signValues.indexOf('smallNegative');
925
- exponent = padBase32Exponent(significantDigitIndex);
926
- mantissa = flipBase32(padBase32Mantissa(key32));
768
+ // Numbers are represented in a lexically sortable base-32 sign-exponent-mantissa
769
+ // notation.
770
+ //
771
+ // sign: takes a value between zero and five, inclusive. Represents infinite cases
772
+ // and the signs of both the exponent and the fractional part of the number.
773
+ // exponent: padded to two base-32 digits, represented by the 32's compliment in the
774
+ // "smallPositive" and "bigNegative" cases to ensure proper lexical sorting.
775
+ // mantissa: also called the fractional part. Normed 11-digit base-32 representation.
776
+ // Represented by the 32's compliment in the "smallNegative" and "bigNegative"
777
+ // cases to ensure proper lexical sorting.
778
+ number: {
779
+ // The encode step checks for six numeric cases and generates 14-digit encoded
780
+ // sign-exponent-mantissa strings.
781
+ /**
782
+ * @param {number} key
783
+ * @returns {string}
784
+ */
785
+ encode(key) {
786
+ let key32 = key === Number.MIN_VALUE
787
+ // Mocha test `IDBFactory/cmp-spec.js` exposed problem for some
788
+ // Node (and Chrome) versions with `Number.MIN_VALUE` being treated
789
+ // as 0
790
+ // https://stackoverflow.com/questions/43305403/number-min-value-and-tostring
791
+ ? '0.' + '0'.repeat(214) + '2' : Math.abs(key).toString(32);
792
+ // Get the index of the decimal.
793
+ const decimalIndex = key32.indexOf('.');
794
+ // Remove the decimal.
795
+ key32 = decimalIndex !== -1 ? key32.replace('.', '') : key32;
796
+ // Get the index of the first significant digit.
797
+ const significantDigitIndex = key32.search(/[^0]/u);
798
+ // Truncate leading zeros.
799
+ key32 = key32.slice(significantDigitIndex);
800
+ let sign, exponent, mantissa;
801
+
802
+ // Finite cases:
803
+ if (Number.isFinite(Number(key))) {
804
+ // Negative cases:
805
+ if (key < 0) {
806
+ // Negative exponent case:
807
+ if (key > -1) {
808
+ sign = signValues.indexOf('smallNegative');
809
+ exponent = padBase32Exponent(significantDigitIndex);
810
+ mantissa = flipBase32(padBase32Mantissa(key32));
811
+ // Non-negative exponent case:
812
+ } else {
813
+ sign = signValues.indexOf('bigNegative');
814
+ exponent = flipBase32(padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length));
815
+ mantissa = flipBase32(padBase32Mantissa(key32));
816
+ }
817
+ // Non-negative cases:
818
+ // Negative exponent case:
819
+ } else if (key < 1) {
820
+ sign = signValues.indexOf('smallPositive');
821
+ exponent = flipBase32(padBase32Exponent(significantDigitIndex));
822
+ mantissa = padBase32Mantissa(key32);
927
823
  // Non-negative exponent case:
928
824
  } else {
929
- sign = signValues.indexOf('bigNegative');
930
- exponent = flipBase32(padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length));
931
- mantissa = flipBase32(padBase32Mantissa(key32));
825
+ sign = signValues.indexOf('bigPositive');
826
+ exponent = padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length);
827
+ mantissa = padBase32Mantissa(key32);
932
828
  }
933
- // Non-negative cases:
934
- // Negative exponent case:
935
- } else if (key < 1) {
936
- sign = signValues.indexOf('smallPositive');
937
- exponent = flipBase32(padBase32Exponent(significantDigitIndex));
938
- mantissa = padBase32Mantissa(key32);
939
- // Non-negative exponent case:
829
+ // Infinite cases:
940
830
  } else {
941
- sign = signValues.indexOf('bigPositive');
942
- exponent = padBase32Exponent(decimalIndex !== -1 ? decimalIndex : key32.length);
943
- mantissa = padBase32Mantissa(key32);
831
+ exponent = zeros(2);
832
+ mantissa = zeros(11);
833
+ sign = signValues.indexOf(key > 0 ? 'positiveInfinity' : 'negativeInfinity');
834
+ }
835
+ return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;
836
+ },
837
+ // The decode step must interpret the sign, reflip values encoded as the 32's complements,
838
+ // apply signs to the exponent and mantissa, do the base-32 power operation, and return
839
+ // the original JavaScript number values.
840
+ /**
841
+ * @param {string} key
842
+ * @returns {number}
843
+ */
844
+ decode(key) {
845
+ const sign = Number(key.slice(2, 3));
846
+ let exponent = key.slice(3, 5);
847
+ let mantissa = key.slice(5, 16);
848
+ switch (signValues[sign]) {
849
+ case 'negativeInfinity':
850
+ return Number.NEGATIVE_INFINITY;
851
+ case 'positiveInfinity':
852
+ return Number.POSITIVE_INFINITY;
853
+ case 'bigPositive':
854
+ return pow32(mantissa, exponent);
855
+ case 'smallPositive':
856
+ exponent = negate(flipBase32(exponent));
857
+ return pow32(mantissa, exponent);
858
+ case 'smallNegative':
859
+ exponent = negate(exponent);
860
+ mantissa = flipBase32(mantissa);
861
+ return -pow32(mantissa, exponent);
862
+ case 'bigNegative':
863
+ exponent = flipBase32(exponent);
864
+ mantissa = flipBase32(mantissa);
865
+ return -pow32(mantissa, exponent);
866
+ default:
867
+ throw new Error('Invalid number.');
944
868
  }
945
- // Infinite cases:
946
- } else {
947
- exponent = zeros(2);
948
- mantissa = zeros(11);
949
- sign = signValues.indexOf(key > 0 ? 'positiveInfinity' : 'negativeInfinity');
950
869
  }
951
- return keyTypeToEncodedChar.number + '-' + sign + exponent + mantissa;
952
870
  },
953
- // The decode step must interpret the sign, reflip values encoded as the 32's complements,
954
- // apply signs to the exponent and mantissa, do the base-32 power operation, and return
955
- // the original JavaScript number values.
956
- /**
957
- * @param {string} key
958
- * @returns {number}
959
- */
960
- decode: function decode(key) {
961
- var sign = Number(key.slice(2, 3));
962
- var exponent = key.slice(3, 5);
963
- var mantissa = key.slice(5, 16);
964
- switch (signValues[sign]) {
965
- case 'negativeInfinity':
966
- return Number.NEGATIVE_INFINITY;
967
- case 'positiveInfinity':
968
- return Number.POSITIVE_INFINITY;
969
- case 'bigPositive':
970
- return pow32(mantissa, exponent);
971
- case 'smallPositive':
972
- exponent = negate(flipBase32(exponent));
973
- return pow32(mantissa, exponent);
974
- case 'smallNegative':
975
- exponent = negate(exponent);
976
- mantissa = flipBase32(mantissa);
977
- return -pow32(mantissa, exponent);
978
- case 'bigNegative':
979
- exponent = flipBase32(exponent);
980
- mantissa = flipBase32(mantissa);
981
- return -pow32(mantissa, exponent);
982
- default:
983
- throw new Error('Invalid number.');
984
- }
985
- }
986
- },
987
- // Strings are encoded as JSON strings (with quotes and unicode characters escaped).
988
- //
989
- // If the strings are in an array, then some extra encoding is done to make sorting work correctly:
990
- // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly
991
- // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.
992
- // To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string.
993
- // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,
994
- // the indexes of each string's characters line up with each other.
995
- string: {
996
- /**
997
- * @param {string} key
998
- * @param {boolean} [inArray]
999
- * @returns {string}
1000
- */
1001
- encode: function encode(key, inArray) {
1002
- if (inArray) {
1003
- // prepend each character with a dash, and append a space to the end
1004
- key = key.replaceAll(/((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g, '-$1') + ' ';
871
+ // Strings are encoded as JSON strings (with quotes and unicode characters escaped).
872
+ //
873
+ // If the strings are in an array, then some extra encoding is done to make sorting work correctly:
874
+ // Since we can't force all strings to be the same length, we need to ensure that characters line-up properly
875
+ // for sorting, while also accounting for the extra characters that are added when the array itself is encoded as JSON.
876
+ // To do this, each character of the string is prepended with a dash ("-"), and a space is added to the end of the string.
877
+ // This effectively doubles the size of every string, but it ensures that when two arrays of strings are compared,
878
+ // the indexes of each string's characters line up with each other.
879
+ string: {
880
+ /**
881
+ * @param {string} key
882
+ * @param {boolean} [inArray]
883
+ * @returns {string}
884
+ */
885
+ encode(key, inArray) {
886
+ if (inArray) {
887
+ // prepend each character with a dash, and append a space to the end
888
+ key = key.replaceAll(/(.)/gu, '-$1') + ' ';
889
+ }
890
+ return keyTypeToEncodedChar.string + '-' + key;
891
+ },
892
+ /**
893
+ * @param {string} key
894
+ * @param {boolean} [inArray]
895
+ * @returns {string}
896
+ */
897
+ decode(key, inArray) {
898
+ key = key.slice(2);
899
+ if (inArray) {
900
+ // remove the space at the end, and the dash before each character
901
+ key = key.slice(0, -1).replaceAll(/-(.)/gu, '$1');
902
+ }
903
+ return key;
1005
904
  }
1006
- return keyTypeToEncodedChar.string + '-' + key;
1007
905
  },
1008
- /**
1009
- * @param {string} key
1010
- * @param {boolean} [inArray]
1011
- * @returns {string}
1012
- */
1013
- decode: function decode(key, inArray) {
1014
- key = key.slice(2);
1015
- if (inArray) {
1016
- // remove the space at the end, and the dash before each character
1017
- key = key.slice(0, -1).replaceAll(/\x2D((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g, '$1');
1018
- }
1019
- return key;
1020
- }
1021
- },
1022
- // Arrays are encoded as JSON strings.
1023
- // An extra, value is added to each array during encoding to make
1024
- // empty arrays sort correctly.
1025
- array: {
1026
- /**
1027
- * @param {ValueTypeArray} key
1028
- * @returns {string}
1029
- */
1030
- encode: function encode(key) {
1031
- var encoded = [];
1032
- var _iterator = _createForOfIteratorHelper(key.entries()),
1033
- _step;
1034
- try {
1035
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
1036
- var _step$value = _slicedToArray(_step.value, 2),
1037
- i = _step$value[0],
1038
- item = _step$value[1];
1039
- var encodedItem = _encode(item, true); // encode the array item
906
+ // Arrays are encoded as JSON strings.
907
+ // An extra, value is added to each array during encoding to make
908
+ // empty arrays sort correctly.
909
+ array: {
910
+ /**
911
+ * @param {ValueTypeArray} key
912
+ * @returns {string}
913
+ */
914
+ encode(key) {
915
+ const encoded = [];
916
+ for (const [i, item] of key.entries()) {
917
+ const encodedItem = encode(item, true); // encode the array item
1040
918
  encoded[i] = encodedItem;
1041
919
  }
1042
- } catch (err) {
1043
- _iterator.e(err);
1044
- } finally {
1045
- _iterator.f();
1046
- }
1047
- encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly
1048
- return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);
1049
- },
1050
- /**
1051
- * @param {string} key
1052
- * @returns {ValueTypeArray}
1053
- */
1054
- decode: function decode(key) {
1055
- var decoded = JSON.parse(key.slice(2));
1056
- decoded.pop(); // remove the extra item
1057
- for (var i = 0; i < decoded.length; i++) {
1058
- var item = decoded[i];
1059
- var decodedItem = _decode(item, true); // decode the item
1060
- decoded[i] = decodedItem;
920
+ encoded.push(keyTypeToEncodedChar.invalid + '-'); // append an extra item, so empty arrays sort correctly
921
+ return keyTypeToEncodedChar.array + '-' + JSON.stringify(encoded);
922
+ },
923
+ /**
924
+ * @param {string} key
925
+ * @returns {ValueTypeArray}
926
+ */
927
+ decode(key) {
928
+ const decoded = JSON.parse(key.slice(2));
929
+ decoded.pop(); // remove the extra item
930
+ for (let i = 0; i < decoded.length; i++) {
931
+ const item = decoded[i];
932
+ const decodedItem = decode(item, true); // decode the item
933
+ decoded[i] = decodedItem;
934
+ }
935
+ return decoded;
1061
936
  }
1062
- return decoded;
1063
- }
1064
- },
1065
- // Dates are encoded as ISO 8601 strings, in UTC time zone.
1066
- date: {
1067
- /**
1068
- * @param {Date} key
1069
- * @returns {string}
1070
- */
1071
- encode: function encode(key) {
1072
- return keyTypeToEncodedChar.date + '-' + key.toJSON();
1073
937
  },
1074
- /**
1075
- * @param {string} key
1076
- * @returns {Date}
1077
- */
1078
- decode: function decode(key) {
1079
- return new Date(key.slice(2));
1080
- }
1081
- },
1082
- binary: {
1083
- // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)
1084
- /**
1085
- * @param {BufferSource} key
1086
- * @returns {string}
1087
- */
1088
- encode: function encode(key) {
1089
- return keyTypeToEncodedChar.binary + '-' + (key.byteLength ? _toConsumableArray(getCopyBytesHeldByBufferSource(key)).map(function (b) {
1090
- return String(b).padStart(3, '0');
1091
- }) // e.g., '255,005,254,000,001,033'
1092
- : '');
938
+ // Dates are encoded as ISO 8601 strings, in UTC time zone.
939
+ date: {
940
+ /**
941
+ * @param {Date} key
942
+ * @returns {string}
943
+ */
944
+ encode(key) {
945
+ return keyTypeToEncodedChar.date + '-' + key.toJSON();
946
+ },
947
+ /**
948
+ * @param {string} key
949
+ * @returns {Date}
950
+ */
951
+ decode(key) {
952
+ return new Date(key.slice(2));
953
+ }
1093
954
  },
1094
- /**
1095
- * @param {string} key
1096
- * @returns {ArrayBuffer}
1097
- */
1098
- decode: function decode(key) {
1099
- // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
1100
- var k = key.slice(2);
1101
- var arr = k.length ? k.split(',').map(function (s) {
1102
- return Number.parseInt(s);
1103
- }) : [];
1104
- var buffer = new ArrayBuffer(arr.length);
1105
- var uint8 = new Uint8Array(buffer);
1106
- uint8.set(arr);
1107
- return buffer;
955
+ binary: {
956
+ // `ArrayBuffer`/Views on buffers (`TypedArray` or `DataView`)
957
+ /**
958
+ * @param {BufferSource} key
959
+ * @returns {string}
960
+ */
961
+ encode(key) {
962
+ return keyTypeToEncodedChar.binary + '-' + (key.byteLength ? [...getCopyBytesHeldByBufferSource(key)].map(b => String(b).padStart(3, '0')) // e.g., '255,005,254,000,001,033'
963
+ : '');
964
+ },
965
+ /**
966
+ * @param {string} key
967
+ * @returns {ArrayBuffer}
968
+ */
969
+ decode(key) {
970
+ // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
971
+ const k = key.slice(2);
972
+ const arr = k.length ? k.split(',').map(s => Number.parseInt(s)) : [];
973
+ const buffer = new ArrayBuffer(arr.length);
974
+ const uint8 = new Uint8Array(buffer);
975
+ uint8.set(arr);
976
+ return buffer;
977
+ }
1108
978
  }
979
+ };
980
+
981
+ /**
982
+ * Return a padded base-32 exponent value.
983
+ * @param {number} n
984
+ * @returns {string}
985
+ */
986
+ function padBase32Exponent(n) {
987
+ const exp = n.toString(32);
988
+ return exp.length === 1 ? '0' + exp : exp;
1109
989
  }
1110
- };
1111
-
1112
- /**
1113
- * Return a padded base-32 exponent value.
1114
- * @param {number} n
1115
- * @returns {string}
1116
- */
1117
- function padBase32Exponent(n) {
1118
- var exp = n.toString(32);
1119
- return exp.length === 1 ? '0' + exp : exp;
1120
- }
1121
-
1122
- /**
1123
- * Return a padded base-32 mantissa.
1124
- * @param {string} s
1125
- * @returns {string}
1126
- */
1127
- function padBase32Mantissa(s) {
1128
- return (s + zeros(11)).slice(0, 11);
1129
- }
1130
-
1131
- /**
1132
- * Flips each digit of a base-32 encoded string.
1133
- * @param {string} encoded
1134
- * @returns {string}
1135
- */
1136
- function flipBase32(encoded) {
1137
- var flipped = '';
1138
- var _iterator2 = _createForOfIteratorHelper(encoded),
1139
- _step2;
1140
- try {
1141
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
1142
- var ch = _step2.value;
990
+
991
+ /**
992
+ * Return a padded base-32 mantissa.
993
+ * @param {string} s
994
+ * @returns {string}
995
+ */
996
+ function padBase32Mantissa(s) {
997
+ return (s + zeros(11)).slice(0, 11);
998
+ }
999
+
1000
+ /**
1001
+ * Flips each digit of a base-32 encoded string.
1002
+ * @param {string} encoded
1003
+ * @returns {string}
1004
+ */
1005
+ function flipBase32(encoded) {
1006
+ let flipped = '';
1007
+ for (const ch of encoded) {
1143
1008
  flipped += (31 - Number.parseInt(ch, 32)).toString(32);
1144
1009
  }
1145
- } catch (err) {
1146
- _iterator2.e(err);
1147
- } finally {
1148
- _iterator2.f();
1010
+ return flipped;
1011
+ }
1012
+
1013
+ /**
1014
+ * Base-32 power function.
1015
+ * RESEARCH: This function does not precisely decode floats because it performs
1016
+ * floating point arithmetic to recover values. But can the original values be
1017
+ * recovered exactly?
1018
+ * Someone may have already figured out a good way to store JavaScript floats as
1019
+ * binary strings and convert back. Barring a better method, however, one route
1020
+ * may be to generate decimal strings that `parseFloat` decodes predictably.
1021
+ * @param {string} mantissa
1022
+ * @param {string} exponent
1023
+ * @returns {number}
1024
+ */
1025
+ function pow32(mantissa, exponent) {
1026
+ const exp = Number.parseInt(exponent, 32);
1027
+ if (exp < 0) {
1028
+ return roundToPrecision(Number.parseInt(mantissa, 32) * 32 ** (exp - 10));
1029
+ }
1030
+ if (exp < 11) {
1031
+ const whole = mantissa.slice(0, exp);
1032
+ const wholeNum = Number.parseInt(whole, 32);
1033
+ const fraction = mantissa.slice(exp);
1034
+ const fractionNum = Number.parseInt(fraction, 32) * 32 ** (exp - 11);
1035
+ return roundToPrecision(wholeNum + fractionNum);
1036
+ }
1037
+ const expansion = mantissa + zeros(exp - 11);
1038
+ return Number.parseInt(expansion, 32);
1039
+ }
1040
+
1041
+ /**
1042
+ * @typedef {number} Float
1043
+ */
1044
+
1045
+ /**
1046
+ * @param {Float} num
1047
+ * @param {Float} [precision]
1048
+ * @returns {Float}
1049
+ */
1050
+ function roundToPrecision(num, precision = 16) {
1051
+ return Number.parseFloat(num.toPrecision(precision));
1149
1052
  }
1150
- return flipped;
1151
- }
1152
-
1153
- /**
1154
- * Base-32 power function.
1155
- * RESEARCH: This function does not precisely decode floats because it performs
1156
- * floating point arithmetic to recover values. But can the original values be
1157
- * recovered exactly?
1158
- * Someone may have already figured out a good way to store JavaScript floats as
1159
- * binary strings and convert back. Barring a better method, however, one route
1160
- * may be to generate decimal strings that `parseFloat` decodes predictably.
1161
- * @param {string} mantissa
1162
- * @param {string} exponent
1163
- * @returns {number}
1164
- */
1165
- function pow32(mantissa, exponent) {
1166
- var exp = Number.parseInt(exponent, 32);
1167
- if (exp < 0) {
1168
- return roundToPrecision(Number.parseInt(mantissa, 32) * Math.pow(32, exp - 10));
1053
+
1054
+ /**
1055
+ * Returns a string of n zeros.
1056
+ * @param {number} n
1057
+ * @returns {string}
1058
+ */
1059
+ function zeros(n) {
1060
+ return '0'.repeat(n);
1169
1061
  }
1170
- if (exp < 11) {
1171
- var whole = mantissa.slice(0, exp);
1172
- var wholeNum = Number.parseInt(whole, 32);
1173
- var fraction = mantissa.slice(exp);
1174
- var fractionNum = Number.parseInt(fraction, 32) * Math.pow(32, exp - 11);
1175
- return roundToPrecision(wholeNum + fractionNum);
1062
+
1063
+ /**
1064
+ * Negates numeric strings.
1065
+ * @param {string} s
1066
+ * @returns {string}
1067
+ */
1068
+ function negate(s) {
1069
+ return '-' + s;
1176
1070
  }
1177
- var expansion = mantissa + zeros(exp - 11);
1178
- return Number.parseInt(expansion, 32);
1179
- }
1180
-
1181
- /**
1182
- * @typedef {number} Float
1183
- */
1184
-
1185
- /**
1186
- * @param {Float} num
1187
- * @param {Float} [precision]
1188
- * @returns {Float}
1189
- */
1190
- function roundToPrecision(num) {
1191
- var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16;
1192
- return Number.parseFloat(num.toPrecision(precision));
1193
- }
1194
-
1195
- /**
1196
- * Returns a string of n zeros.
1197
- * @param {number} n
1198
- * @returns {string}
1199
- */
1200
- function zeros(n) {
1201
- return '0'.repeat(n);
1202
- }
1203
-
1204
- /**
1205
- * Negates numeric strings.
1206
- * @param {string} s
1207
- * @returns {string}
1208
- */
1209
- function negate(s) {
1210
- return '-' + s;
1211
- }
1212
-
1213
- /**
1214
- * @param {Key} key
1215
- * @returns {KeyType|"invalid"}
1216
- */
1217
- function getKeyType(key) {
1218
- if (Array.isArray(key)) {
1219
- return 'array';
1071
+
1072
+ /**
1073
+ * @param {Key} key
1074
+ * @returns {KeyType|"invalid"}
1075
+ */
1076
+ function getKeyType(key) {
1077
+ if (Array.isArray(key)) {
1078
+ return 'array';
1079
+ }
1080
+ if (isDate(key)) {
1081
+ return 'date';
1082
+ }
1083
+ if (isBinary(key)) {
1084
+ return 'binary';
1085
+ }
1086
+ const keyType = typeof key;
1087
+ return ['string', 'number'].includes(keyType) ? (/** @type {"string"|"number"} */keyType) : 'invalid';
1220
1088
  }
1221
- if (isDate(key)) {
1222
- return 'date';
1089
+
1090
+ /**
1091
+ * Keys must be strings, numbers (besides `NaN`), Dates (if value is not
1092
+ * `NaN`), binary objects or Arrays.
1093
+ * @param {Value} input The key input
1094
+ * @param {Value[]|null|undefined} [seen] An array of already seen keys
1095
+ * @returns {KeyValueObject}
1096
+ */
1097
+ function convertValueToKey(input, seen) {
1098
+ return convertValueToKeyValueDecoded(input, seen, false, true);
1223
1099
  }
1224
- if (isBinary(key)) {
1225
- return 'binary';
1100
+
1101
+ /**
1102
+ * Currently not in use.
1103
+ * @param {Value} input
1104
+ * @returns {KeyValueObject}
1105
+ */
1106
+ function convertValueToMultiEntryKey(input) {
1107
+ return convertValueToKeyValueDecoded(input, null, true, true);
1226
1108
  }
1227
- var keyType = _typeof(key);
1228
- return ['string', 'number'].includes(keyType) ? (/** @type {"string"|"number"} */keyType) : 'invalid';
1229
- }
1230
-
1231
- /**
1232
- * Keys must be strings, numbers (besides `NaN`), Dates (if value is not
1233
- * `NaN`), binary objects or Arrays.
1234
- * @param {Value} input The key input
1235
- * @param {Value[]|null|undefined} [seen] An array of already seen keys
1236
- * @returns {KeyValueObject}
1237
- */
1238
- function convertValueToKey(input, seen) {
1239
- return convertValueToKeyValueDecoded(input, seen, false, true);
1240
- }
1241
-
1242
- /**
1243
- * Currently not in use.
1244
- * @param {Value} input
1245
- * @returns {KeyValueObject}
1246
- */
1247
- function convertValueToMultiEntryKey(input) {
1248
- return convertValueToKeyValueDecoded(input, null, true, true);
1249
- }
1250
-
1251
- /**
1252
- *
1253
- * @param {BufferSource} O
1254
- * @throws {TypeError}
1255
- * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1256
- * @returns {Uint8Array}
1257
- */
1258
- function getCopyBytesHeldByBufferSource(O) {
1259
- var offset = 0;
1260
- var length = 0;
1261
- if (ArrayBuffer.isView(O)) {
1262
- // Has [[ViewedArrayBuffer]] internal slot
1263
- var arrayBuffer = O.buffer;
1264
- if (arrayBuffer === undefined) {
1265
- throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.');
1109
+
1110
+ /**
1111
+ *
1112
+ * @param {BufferSource} O
1113
+ * @throws {TypeError}
1114
+ * @see https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1115
+ * @returns {Uint8Array}
1116
+ */
1117
+ function getCopyBytesHeldByBufferSource(O) {
1118
+ let offset = 0;
1119
+ let length = 0;
1120
+ if (ArrayBuffer.isView(O)) {
1121
+ // Has [[ViewedArrayBuffer]] internal slot
1122
+ const arrayBuffer = O.buffer;
1123
+ if (arrayBuffer === undefined) {
1124
+ throw new TypeError('Could not copy the bytes held by a buffer source as the buffer was undefined.');
1125
+ }
1126
+ offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)
1127
+ length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)
1128
+ } else {
1129
+ length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)
1266
1130
  }
1267
- offset = O.byteOffset; // [[ByteOffset]] (will also throw as desired if detached)
1268
- length = O.byteLength; // [[ByteLength]] (will also throw as desired if detached)
1269
- } else {
1270
- length = O.byteLength; // [[ArrayBufferByteLength]] on ArrayBuffer (will also throw as desired if detached)
1131
+ // const octets = new Uint8Array(input);
1132
+ // const octets = types.binary.decode(types.binary.encode(input));
1133
+ return new Uint8Array(
1134
+ // Should allow DataView
1135
+ /** @type {ArrayBuffer} */
1136
+ 'buffer' in O && O.buffer || O, offset, length);
1271
1137
  }
1272
- // const octets = new Uint8Array(input);
1273
- // const octets = types.binary.decode(types.binary.encode(input));
1274
- return new Uint8Array(
1275
- // Should allow DataView
1276
- /** @type {ArrayBuffer} */
1277
- 'buffer' in O && O.buffer || O, offset, length);
1278
- }
1279
-
1280
- /**
1281
- * Shortcut utility to avoid returning full keys from `convertValueToKey`
1282
- * and subsequent need to process in calling code unless `fullKeys` is
1283
- * set; may throw.
1284
- * @param {Value} input
1285
- * @param {Value[]|null} [seen]
1286
- * @param {boolean} [multiEntry]
1287
- * @param {boolean} [fullKeys]
1288
- * @throws {TypeError} See `getCopyBytesHeldByBufferSource`
1289
- * @todo Document other allowable `input`
1290
- * @returns {KeyValueObject}
1291
- */
1292
- function convertValueToKeyValueDecoded(input, seen, multiEntry, fullKeys) {
1293
- seen = seen || [];
1294
- if (seen.includes(input)) {
1295
- return {
1296
- type: 'array',
1297
- invalid: true,
1298
- message: 'An array key cannot be circular'
1138
+
1139
+ /**
1140
+ * Shortcut utility to avoid returning full keys from `convertValueToKey`
1141
+ * and subsequent need to process in calling code unless `fullKeys` is
1142
+ * set; may throw.
1143
+ * @param {Value} input
1144
+ * @param {Value[]|null} [seen]
1145
+ * @param {boolean} [multiEntry]
1146
+ * @param {boolean} [fullKeys]
1147
+ * @throws {TypeError} See `getCopyBytesHeldByBufferSource`
1148
+ * @todo Document other allowable `input`
1149
+ * @returns {KeyValueObject}
1150
+ */
1151
+ function convertValueToKeyValueDecoded(input, seen, multiEntry, fullKeys) {
1152
+ seen = seen || [];
1153
+ if (seen.includes(input)) {
1154
+ return {
1155
+ type: 'array',
1156
+ invalid: true,
1157
+ message: 'An array key cannot be circular'
1158
+ };
1159
+ }
1160
+ const type = getKeyType(input);
1161
+ const ret = {
1162
+ type,
1163
+ value: input
1299
1164
  };
1300
- }
1301
- var type = getKeyType(input);
1302
- var ret = {
1303
- type: type,
1304
- value: input
1305
- };
1306
- switch (type) {
1307
- case 'number':
1308
- {
1309
- if (Number.isNaN(input)) {
1310
- // List as 'NaN' type for convenience of consumers in reporting errors
1311
- return {
1312
- type: 'NaN',
1313
- invalid: true
1314
- };
1315
- }
1165
+ switch (type) {
1166
+ case 'number':
1167
+ {
1168
+ if (Number.isNaN(input)) {
1169
+ // List as 'NaN' type for convenience of consumers in reporting errors
1170
+ return {
1171
+ type: 'NaN',
1172
+ invalid: true
1173
+ };
1174
+ }
1316
1175
 
1317
- // https://github.com/w3c/IndexedDB/issues/375
1318
- // https://github.com/w3c/IndexedDB/pull/386
1319
- if (Object.is(input, -0)) {
1176
+ // https://github.com/w3c/IndexedDB/issues/375
1177
+ // https://github.com/w3c/IndexedDB/pull/386
1178
+ if (Object.is(input, -0)) {
1179
+ return {
1180
+ type,
1181
+ value: 0
1182
+ };
1183
+ }
1184
+ return /** @type {{type: KeyType; value: Value}} */ret;
1185
+ }
1186
+ case 'string':
1187
+ {
1188
+ return /** @type {{type: KeyType; value: Value}} */ret;
1189
+ }
1190
+ case 'binary':
1191
+ {
1192
+ // May throw (if detached)
1193
+ // Get a copy of the bytes held by the buffer source
1194
+ // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1195
+ const octets = getCopyBytesHeldByBufferSource(/** @type {BufferSource} */input);
1320
1196
  return {
1321
- type: type,
1322
- value: 0
1197
+ type: 'binary',
1198
+ value: octets
1323
1199
  };
1324
1200
  }
1325
- return /** @type {{type: KeyType; value: Value}} */ret;
1326
- }
1327
- case 'string':
1328
- {
1329
- return /** @type {{type: KeyType; value: Value}} */ret;
1330
- }
1331
- case 'binary':
1332
- {
1333
- // May throw (if detached)
1334
- // Get a copy of the bytes held by the buffer source
1335
- // https://heycam.github.io/webidl/#ref-for-dfn-get-buffer-source-copy-2
1336
- var octets = getCopyBytesHeldByBufferSource(/** @type {BufferSource} */input);
1337
- return {
1338
- type: 'binary',
1339
- value: octets
1340
- };
1341
- }
1342
- case 'array':
1343
- {
1344
- // May throw (from binary)
1345
- var arr = /** @type {Array<any>} */input;
1346
- var len = arr.length;
1347
- seen.push(input);
1348
-
1349
- /** @type {(KeyValueObject|Value)[]} */
1350
- var keys = [];
1351
- var _loop = function _loop() {
1201
+ case 'array':
1202
+ {
1203
+ // May throw (from binary)
1204
+ const arr = /** @type {Array<any>} */input;
1205
+ const len = arr.length;
1206
+ seen.push(input);
1207
+
1208
+ /** @type {(KeyValueObject|Value)[]} */
1209
+ const keys = [];
1210
+ for (let i = 0; i < len; i++) {
1352
1211
  // We cannot iterate here with array extras as we must ensure sparse arrays are invalidated
1353
1212
  if (!multiEntry && !Object.hasOwn(arr, i)) {
1354
1213
  return {
1355
- v: {
1356
- type: type,
1357
- invalid: true,
1358
- message: 'Does not have own index property'
1359
- }
1214
+ type,
1215
+ invalid: true,
1216
+ message: 'Does not have own index property'
1360
1217
  };
1361
1218
  }
1362
1219
  try {
1363
- var entry = arr[i];
1364
- var key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry
1220
+ const entry = arr[i];
1221
+ const key = convertValueToKeyValueDecoded(entry, seen, false, fullKeys); // Though steps do not list rethrowing, the next is returnifabrupt when not multiEntry
1365
1222
  if (key.invalid) {
1366
1223
  if (multiEntry) {
1367
- return 0; // continue
1224
+ continue;
1368
1225
  }
1369
1226
  return {
1370
- v: {
1371
- type: type,
1372
- invalid: true,
1373
- message: 'Bad array entry value-to-key conversion'
1374
- }
1227
+ type,
1228
+ invalid: true,
1229
+ message: 'Bad array entry value-to-key conversion'
1375
1230
  };
1376
1231
  }
1377
- if (!multiEntry || !fullKeys && keys.every(function (k) {
1378
- return cmp(k, key.value) !== 0;
1379
- }) || fullKeys && keys.every(function (k) {
1380
- return cmp(k, key) !== 0;
1381
- })) {
1232
+ if (!multiEntry || !fullKeys && keys.every(k => cmp(k, key.value) !== 0) || fullKeys && keys.every(k => cmp(k, key) !== 0)) {
1382
1233
  keys.push(fullKeys ? key : key.value);
1383
1234
  }
1384
1235
  } catch (err) {
@@ -1386,309 +1237,290 @@
1386
1237
  throw err;
1387
1238
  }
1388
1239
  }
1389
- },
1390
- _ret;
1391
- for (var i = 0; i < len; i++) {
1392
- _ret = _loop();
1393
- if (_ret === 0) continue;
1394
- if (_ret) return _ret.v;
1240
+ }
1241
+ return {
1242
+ type,
1243
+ value: keys
1244
+ };
1395
1245
  }
1396
- return {
1397
- type: type,
1398
- value: keys
1399
- };
1400
- }
1401
- case 'date':
1402
- {
1403
- var date = /** @type {Date} */input;
1404
- if (!Number.isNaN(date.getTime())) {
1405
- return fullKeys ? {
1406
- type: type,
1407
- value: date.getTime()
1408
- } : {
1409
- type: type,
1410
- value: new Date(date.getTime())
1246
+ case 'date':
1247
+ {
1248
+ const date = /** @type {Date} */input;
1249
+ if (!Number.isNaN(date.getTime())) {
1250
+ return fullKeys ? {
1251
+ type,
1252
+ value: date.getTime()
1253
+ } : {
1254
+ type,
1255
+ value: new Date(date)
1256
+ };
1257
+ }
1258
+ return {
1259
+ type,
1260
+ invalid: true,
1261
+ message: 'Not a valid date'
1411
1262
  };
1263
+ // Falls through
1412
1264
  }
1413
- return {
1414
- type: type,
1415
- invalid: true,
1416
- message: 'Not a valid date'
1417
- };
1418
- // Falls through
1419
- }
1420
- case 'invalid':
1421
- default:
1422
- {
1423
- // Other `typeof` types which are not valid keys:
1424
- // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'
1425
- var _type = input === null ? 'null' : _typeof(input); // Convert `null` for convenience of consumers in reporting errors
1426
- return {
1427
- type: _type,
1428
- invalid: true,
1429
- message: 'Not a valid key; type ' + _type
1430
- };
1431
- }
1265
+ case 'invalid':
1266
+ default:
1267
+ {
1268
+ // Other `typeof` types which are not valid keys:
1269
+ // 'undefined', 'boolean', 'object' (including `null`), 'symbol', 'function'
1270
+ const type = input === null ? 'null' : typeof input; // Convert `null` for convenience of consumers in reporting errors
1271
+ return {
1272
+ type,
1273
+ invalid: true,
1274
+ message: 'Not a valid key; type ' + type
1275
+ };
1276
+ }
1277
+ }
1278
+ }
1279
+
1280
+ /**
1281
+ *
1282
+ * @param {Key} key
1283
+ * @param {boolean} [fullKeys]
1284
+ * @returns {KeyValueObject}
1285
+ * @todo Document other allowable `key`?
1286
+ */
1287
+ function convertValueToMultiEntryKeyDecoded(key, fullKeys) {
1288
+ return convertValueToKeyValueDecoded(key, null, true, fullKeys);
1289
+ }
1290
+
1291
+ /**
1292
+ * An internal utility.
1293
+ * @param {Value} input
1294
+ * @param {Value[]|null|undefined} [seen]
1295
+ * @throws {DOMException} `DataError`
1296
+ * @returns {KeyValueObject}
1297
+ */
1298
+ function convertValueToKeyRethrowingAndIfInvalid(input, seen) {
1299
+ const key = convertValueToKey(input, seen);
1300
+ if (key.invalid) {
1301
+ throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);
1302
+ }
1303
+ return key;
1432
1304
  }
1433
- }
1434
-
1435
- /**
1436
- *
1437
- * @param {Key} key
1438
- * @param {boolean} [fullKeys]
1439
- * @returns {KeyValueObject}
1440
- * @todo Document other allowable `key`?
1441
- */
1442
- function convertValueToMultiEntryKeyDecoded(key, fullKeys) {
1443
- return convertValueToKeyValueDecoded(key, null, true, fullKeys);
1444
- }
1445
-
1446
- /**
1447
- * An internal utility.
1448
- * @param {Value} input
1449
- * @param {Value[]|null|undefined} [seen]
1450
- * @throws {DOMException} `DataError`
1451
- * @returns {KeyValueObject}
1452
- */
1453
- function convertValueToKeyRethrowingAndIfInvalid(input, seen) {
1454
- var key = convertValueToKey(input, seen);
1455
- if (key.invalid) {
1456
- throw createDOMException('DataError', key.message || 'Not a valid key; type: ' + key.type);
1305
+
1306
+ /**
1307
+ *
1308
+ * @param {Value} value
1309
+ * @param {KeyPath} keyPath
1310
+ * @param {boolean} multiEntry
1311
+ * @returns {KeyValueObject|KeyPathEvaluateValue}
1312
+ * @todo Document other possible return?
1313
+ */
1314
+ function extractKeyFromValueUsingKeyPath(value, keyPath, multiEntry) {
1315
+ return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);
1457
1316
  }
1458
- return key;
1459
- }
1460
-
1461
- /**
1462
- *
1463
- * @param {Value} value
1464
- * @param {KeyPath} keyPath
1465
- * @param {boolean} multiEntry
1466
- * @returns {KeyValueObject|KeyPathEvaluateValue}
1467
- * @todo Document other possible return?
1468
- */
1469
- function extractKeyFromValueUsingKeyPath(value, keyPath, multiEntry) {
1470
- return extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, true);
1471
- }
1472
- /**
1473
- * Not currently in use.
1474
- * @param {Value} value
1475
- * @param {KeyPath} keyPath
1476
- * @param {boolean} multiEntry
1477
- * @returns {KeyPathEvaluateValue}
1478
- */
1479
- function evaluateKeyPathOnValue(value, keyPath, multiEntry) {
1480
- return evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1481
- }
1482
-
1483
- /**
1484
- * May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)
1485
- * or `{invalid: true}` (e.g., `NaN`).
1486
- * @param {Value} value
1487
- * @param {KeyPath} keyPath
1488
- * @param {boolean} [multiEntry]
1489
- * @param {boolean} [fullKeys]
1490
- * @returns {KeyValueObject|KeyPathEvaluateValue}
1491
- * @todo Document other possible return?
1492
- */
1493
- function extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, fullKeys) {
1494
- var r = evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1495
- if (r.failure) {
1496
- return r;
1317
+ /**
1318
+ * Not currently in use.
1319
+ * @param {Value} value
1320
+ * @param {KeyPath} keyPath
1321
+ * @param {boolean} multiEntry
1322
+ * @returns {KeyPathEvaluateValue}
1323
+ */
1324
+ function evaluateKeyPathOnValue(value, keyPath, multiEntry) {
1325
+ return evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1497
1326
  }
1498
- if (!multiEntry) {
1499
- return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);
1327
+
1328
+ /**
1329
+ * May throw, return `{failure: true}` (e.g., non-object on keyPath resolution)
1330
+ * or `{invalid: true}` (e.g., `NaN`).
1331
+ * @param {Value} value
1332
+ * @param {KeyPath} keyPath
1333
+ * @param {boolean} [multiEntry]
1334
+ * @param {boolean} [fullKeys]
1335
+ * @returns {KeyValueObject|KeyPathEvaluateValue}
1336
+ * @todo Document other possible return?
1337
+ */
1338
+ function extractKeyValueDecodedFromValueUsingKeyPath(value, keyPath, multiEntry, fullKeys) {
1339
+ const r = evaluateKeyPathOnValueToDecodedValue(value, keyPath);
1340
+ if (r.failure) {
1341
+ return r;
1342
+ }
1343
+ if (!multiEntry) {
1344
+ return convertValueToKeyValueDecoded(r.value, null, false, fullKeys);
1345
+ }
1346
+ return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);
1500
1347
  }
1501
- return convertValueToMultiEntryKeyDecoded(r.value, fullKeys);
1502
- }
1503
-
1504
- /**
1505
- * Unused?
1506
- * @typedef {object} KeyPathEvaluateFailure
1507
- * @property {boolean} failure
1508
- */
1509
-
1510
- /**
1511
- * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray
1512
- */
1513
-
1514
- /**
1515
- * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue
1516
- */
1517
-
1518
- /**
1519
- * @typedef {object} KeyPathEvaluateValue
1520
- * @property {KeyPathEvaluateValueValue} [value]
1521
- * @property {boolean} [failure]
1522
- */
1523
-
1524
- /**
1525
- * Returns the value of an inline key based on a key path (wrapped in an
1526
- * object with key `value`) or `{failure: true}`
1527
- * @param {Value} value
1528
- * @param {KeyPath} keyPath
1529
- * @param {boolean} [multiEntry]
1530
- * @param {boolean} [fullKeys]
1531
- * @returns {KeyPathEvaluateValue}
1532
- */
1533
- function evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys) {
1534
- if (Array.isArray(keyPath)) {
1535
- /** @type {KeyPathEvaluateValueValueArray} */
1536
- var result = [];
1537
- return keyPath.some(function (item) {
1538
- var key = evaluateKeyPathOnValueToDecodedValue(value, item);
1539
- if (key.failure) {
1348
+
1349
+ /**
1350
+ * Unused?
1351
+ * @typedef {object} KeyPathEvaluateFailure
1352
+ * @property {boolean} failure
1353
+ */
1354
+
1355
+ /**
1356
+ * @typedef {KeyPathEvaluateValueValue[]} KeyPathEvaluateValueValueArray
1357
+ */
1358
+
1359
+ /**
1360
+ * @typedef {undefined|number|string|Date|object|KeyPathEvaluateValueValueArray} KeyPathEvaluateValueValue
1361
+ */
1362
+
1363
+ /**
1364
+ * @typedef {object} KeyPathEvaluateValue
1365
+ * @property {KeyPathEvaluateValueValue} [value]
1366
+ * @property {boolean} [failure]
1367
+ */
1368
+
1369
+ /**
1370
+ * Returns the value of an inline key based on a key path (wrapped in an
1371
+ * object with key `value`) or `{failure: true}`
1372
+ * @param {Value} value
1373
+ * @param {KeyPath} keyPath
1374
+ * @param {boolean} [multiEntry]
1375
+ * @param {boolean} [fullKeys]
1376
+ * @returns {KeyPathEvaluateValue}
1377
+ */
1378
+ function evaluateKeyPathOnValueToDecodedValue(value, keyPath, multiEntry, fullKeys) {
1379
+ if (Array.isArray(keyPath)) {
1380
+ /** @type {KeyPathEvaluateValueValueArray} */
1381
+ const result = [];
1382
+ return keyPath.some(item => {
1383
+ const key = evaluateKeyPathOnValueToDecodedValue(value, item);
1384
+ if (key.failure) {
1385
+ return true;
1386
+ }
1387
+ result.push(key.value);
1388
+ return false;
1389
+ }) ? {
1390
+ failure: true
1391
+ } : {
1392
+ value: result
1393
+ };
1394
+ }
1395
+ if (keyPath === '') {
1396
+ return {
1397
+ value
1398
+ };
1399
+ }
1400
+ const identifiers = keyPath.split('.');
1401
+ return identifiers.some(idntfr => {
1402
+ if (idntfr === 'length' && (typeof value === 'string' || Array.isArray(value))) {
1403
+ value = value.length;
1404
+ } else if (isBlob(value)) {
1405
+ switch (idntfr) {
1406
+ case 'size':
1407
+ case 'type':
1408
+ value = /** @type {Blob} */value[idntfr];
1409
+ break;
1410
+ }
1411
+ } else if (isFile(value)) {
1412
+ switch (idntfr) {
1413
+ case 'name':
1414
+ case 'lastModified':
1415
+ value = /** @type {File} */value[idntfr];
1416
+ break;
1417
+ case 'lastModifiedDate':
1418
+ value = new Date(/** @type {File} */value.lastModified);
1419
+ break;
1420
+ }
1421
+ } else if (!isObj(value) || !Object.hasOwn(value, idntfr)) {
1540
1422
  return true;
1423
+ } else {
1424
+ value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */value[idntfr];
1425
+ return value === undefined;
1541
1426
  }
1542
- result.push(key.value);
1543
1427
  return false;
1544
1428
  }) ? {
1545
1429
  failure: true
1546
1430
  } : {
1547
- value: result
1548
- };
1549
- }
1550
- if (keyPath === '') {
1551
- return {
1552
- value: value
1431
+ value
1553
1432
  };
1554
1433
  }
1555
- var identifiers = keyPath.split('.');
1556
- return identifiers.some(function (idntfr) {
1557
- if (idntfr === 'length' && (typeof value === 'string' || Array.isArray(value))) {
1558
- value = value.length;
1559
- } else if (isBlob(value)) {
1560
- switch (idntfr) {
1561
- case 'size':
1562
- case 'type':
1563
- value = /** @type {Blob} */value[idntfr];
1564
- break;
1565
- }
1566
- } else if (isFile(value)) {
1567
- switch (idntfr) {
1568
- case 'name':
1569
- case 'lastModified':
1570
- value = /** @type {File} */value[idntfr];
1571
- break;
1572
- case 'lastModifiedDate':
1573
- value = new Date(/** @type {File} */value.lastModified);
1574
- break;
1434
+
1435
+ /**
1436
+ * Sets the inline key value.
1437
+ * @param {{[key: string]: AnyValue}} value
1438
+ * @param {Key} key
1439
+ * @param {string} keyPath
1440
+ * @returns {void}
1441
+ */
1442
+ function injectKeyIntoValueUsingKeyPath(value, key, keyPath) {
1443
+ const identifiers = keyPath.split('.');
1444
+ const last = identifiers.pop();
1445
+ identifiers.forEach(identifier => {
1446
+ const hop = Object.hasOwn(value, identifier);
1447
+ if (!hop) {
1448
+ value[identifier] = {};
1575
1449
  }
1576
- } else if (!isObj(value) || !Object.hasOwn(value, idntfr)) {
1577
- return true;
1578
- } else {
1579
- value = /** @type {{[key: string]: KeyPathEvaluateValueValue}} */value[idntfr];
1580
- return value === undefined;
1581
- }
1582
- return false;
1583
- }) ? {
1584
- failure: true
1585
- } : {
1586
- value: value
1587
- };
1588
- }
1589
-
1590
- /**
1591
- * Sets the inline key value.
1592
- * @param {{[key: string]: AnyValue}} value
1593
- * @param {Key} key
1594
- * @param {string} keyPath
1595
- * @returns {void}
1596
- */
1597
- function injectKeyIntoValueUsingKeyPath(value, key, keyPath) {
1598
- var identifiers = keyPath.split('.');
1599
- var last = identifiers.pop();
1600
- identifiers.forEach(function (identifier) {
1601
- var hop = Object.hasOwn(value, identifier);
1602
- if (!hop) {
1603
- value[identifier] = {};
1604
- }
1605
- value = value[identifier];
1606
- });
1607
- value[(/** @type {string} */last)] = key; // key is already a `keyValue` in our processing so no need to convert
1608
- }
1609
-
1610
- /**
1611
- *
1612
- * @param {Value} value
1613
- * @param {string} keyPath
1614
- * @see https://github.com/w3c/IndexedDB/pull/146
1615
- * @returns {boolean}
1616
- */
1617
- function checkKeyCouldBeInjectedIntoValue(value, keyPath) {
1618
- var identifiers = keyPath.split('.');
1619
- identifiers.pop();
1620
- var _iterator3 = _createForOfIteratorHelper(identifiers),
1621
- _step3;
1622
- try {
1623
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1624
- var identifier = _step3.value;
1450
+ value = value[identifier];
1451
+ });
1452
+ value[(/** @type {string} */last)] = key; // key is already a `keyValue` in our processing so no need to convert
1453
+ }
1454
+
1455
+ /**
1456
+ *
1457
+ * @param {Value} value
1458
+ * @param {string} keyPath
1459
+ * @see https://github.com/w3c/IndexedDB/pull/146
1460
+ * @returns {boolean}
1461
+ */
1462
+ function checkKeyCouldBeInjectedIntoValue(value, keyPath) {
1463
+ const identifiers = keyPath.split('.');
1464
+ identifiers.pop();
1465
+ for (const identifier of identifiers) {
1625
1466
  if (!isObj(value)) {
1626
1467
  return false;
1627
1468
  }
1628
- var hop = Object.hasOwn(value, identifier);
1469
+ const hop = Object.hasOwn(value, identifier);
1629
1470
  if (!hop) {
1630
1471
  return true;
1631
1472
  }
1632
1473
  value = /** @type {{[key: string]: Value}} */value[identifier];
1633
1474
  }
1634
- } catch (err) {
1635
- _iterator3.e(err);
1636
- } finally {
1637
- _iterator3.f();
1475
+ return isObj(value);
1638
1476
  }
1639
- return isObj(value);
1640
- }
1641
-
1642
- /**
1643
- *
1644
- * @param {Key} key
1645
- * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range
1646
- * @param {boolean} [checkCached]
1647
- * @returns {boolean}
1648
- */
1649
- function isKeyInRange(key, range, checkCached) {
1650
- var lowerMatch = range.lower === undefined;
1651
- var upperMatch = range.upper === undefined;
1652
- var encodedKey = _encode(key, true);
1653
- var lower = checkCached ? range.__lowerCached : _encode(range.lower, true);
1654
- var upper = checkCached ? range.__upperCached : _encode(range.upper, true);
1655
- if (!lowerMatch && (range.lowerOpen && encodedKey !== null && lower !== null && encodedKey > lower || !range.lowerOpen && (!encodedKey && !lower || encodedKey !== null && lower !== null && encodedKey >= lower))) {
1656
- lowerMatch = true;
1657
- }
1658
- if (!upperMatch && (range.upperOpen && encodedKey !== null && upper !== null && encodedKey < upper || !range.upperOpen && (!encodedKey && !upper || encodedKey !== null && upper !== null && encodedKey <= upper))) {
1659
- upperMatch = true;
1477
+
1478
+ /**
1479
+ *
1480
+ * @param {Key} key
1481
+ * @param {import('./IDBKeyRange.js').IDBKeyRangeFull} range
1482
+ * @param {boolean} [checkCached]
1483
+ * @returns {boolean}
1484
+ */
1485
+ function isKeyInRange(key, range, checkCached) {
1486
+ let lowerMatch = range.lower === undefined;
1487
+ let upperMatch = range.upper === undefined;
1488
+ const encodedKey = encode(key, true);
1489
+ const lower = checkCached ? range.__lowerCached : encode(range.lower, true);
1490
+ const upper = checkCached ? range.__upperCached : encode(range.upper, true);
1491
+ if (!lowerMatch && (range.lowerOpen && encodedKey !== null && lower !== null && encodedKey > lower || !range.lowerOpen && (!encodedKey && !lower || encodedKey !== null && lower !== null && encodedKey >= lower))) {
1492
+ lowerMatch = true;
1493
+ }
1494
+ if (!upperMatch && (range.upperOpen && encodedKey !== null && upper !== null && encodedKey < upper || !range.upperOpen && (!encodedKey && !upper || encodedKey !== null && upper !== null && encodedKey <= upper))) {
1495
+ upperMatch = true;
1496
+ }
1497
+ return lowerMatch && upperMatch;
1660
1498
  }
1661
- return lowerMatch && upperMatch;
1662
- }
1663
-
1664
- /**
1665
- * Determines whether an index entry matches a multi-entry key value.
1666
- * @param {string} encodedEntry The entry value (already encoded)
1667
- * @param {string} encodedKey The full index key (already encoded)
1668
- * @returns {boolean}
1669
- */
1670
- function isMultiEntryMatch(encodedEntry, encodedKey) {
1671
- var keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];
1672
- if (keyType === 'array') {
1673
- return encodedKey.indexOf(encodedEntry) > 1;
1499
+
1500
+ /**
1501
+ * Determines whether an index entry matches a multi-entry key value.
1502
+ * @param {string} encodedEntry The entry value (already encoded)
1503
+ * @param {string} encodedKey The full index key (already encoded)
1504
+ * @returns {boolean}
1505
+ */
1506
+ function isMultiEntryMatch(encodedEntry, encodedKey) {
1507
+ const keyType = encodedCharToKeyType[encodedKey.slice(0, 1)];
1508
+ if (keyType === 'array') {
1509
+ return encodedKey.indexOf(encodedEntry) > 1;
1510
+ }
1511
+ return encodedKey === encodedEntry;
1674
1512
  }
1675
- return encodedKey === encodedEntry;
1676
- }
1677
-
1678
- /**
1679
- *
1680
- * @param {Key} keyEntry
1681
- * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range
1682
- * @returns {Key[]}
1683
- */
1684
- function findMultiEntryMatches(keyEntry, range) {
1685
- var matches = [];
1686
- if (Array.isArray(keyEntry)) {
1687
- var _iterator4 = _createForOfIteratorHelper(keyEntry),
1688
- _step4;
1689
- try {
1690
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1691
- var key = _step4.value;
1513
+
1514
+ /**
1515
+ *
1516
+ * @param {Key} keyEntry
1517
+ * @param {import('./IDBKeyRange.js').IDBKeyRangeFull|undefined} range
1518
+ * @returns {Key[]}
1519
+ */
1520
+ function findMultiEntryMatches(keyEntry, range) {
1521
+ const matches = [];
1522
+ if (Array.isArray(keyEntry)) {
1523
+ for (let key of keyEntry) {
1692
1524
  if (Array.isArray(key)) {
1693
1525
  if (range && range.lower === range.upper) {
1694
1526
  continue;
@@ -1697,7 +1529,7 @@
1697
1529
  // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient
1698
1530
  key = key[0];
1699
1531
  } else {
1700
- var nested = findMultiEntryMatches(key, range);
1532
+ const nested = findMultiEntryMatches(key, range);
1701
1533
  if (nested.length > 0) {
1702
1534
  matches.push(key);
1703
1535
  }
@@ -1708,273 +1540,270 @@
1708
1540
  matches.push(key);
1709
1541
  }
1710
1542
  }
1711
- } catch (err) {
1712
- _iterator4.e(err);
1713
- } finally {
1714
- _iterator4.f();
1543
+ } else if (isNullish(range) || isKeyInRange(keyEntry, range, true)) {
1544
+ matches.push(keyEntry);
1715
1545
  }
1716
- } else if (isNullish(range) || isKeyInRange(keyEntry, range, true)) {
1717
- matches.push(keyEntry);
1546
+ return matches;
1718
1547
  }
1719
- return matches;
1720
- }
1721
-
1722
- /**
1723
- * Not currently in use but keeping for spec parity.
1724
- * @param {Key} key
1725
- * @throws {Error} Upon a "bad key"
1726
- * @returns {ValueType}
1727
- */
1728
- function convertKeyToValue(key) {
1729
- var type = key.type,
1730
- value = key.value;
1731
- switch (type) {
1732
- case 'number':
1733
- case 'string':
1734
- {
1735
- return value;
1736
- }
1737
- case 'array':
1738
- {
1739
- var array = [];
1740
- var len = value.length;
1741
- var index = 0;
1742
- while (index < len) {
1743
- var entry = convertKeyToValue(value[index]);
1744
- array[index] = entry;
1745
- index++;
1548
+
1549
+ /**
1550
+ * Not currently in use but keeping for spec parity.
1551
+ * @param {Key} key
1552
+ * @throws {Error} Upon a "bad key"
1553
+ * @returns {ValueType}
1554
+ */
1555
+ function convertKeyToValue(key) {
1556
+ const {
1557
+ type,
1558
+ value
1559
+ } = key;
1560
+ switch (type) {
1561
+ case 'number':
1562
+ case 'string':
1563
+ {
1564
+ return value;
1746
1565
  }
1747
- return array;
1748
- }
1749
- case 'date':
1750
- {
1751
- return new Date(value);
1752
- }
1753
- case 'binary':
1754
- {
1755
- var _len = value.length;
1756
- var buffer = new ArrayBuffer(_len);
1757
- // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
1758
- var uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);
1759
- uint8.set(value);
1760
- return buffer;
1761
- }
1762
- case 'invalid':
1763
- default:
1764
- throw new Error('Bad key');
1765
- }
1766
- }
1767
-
1768
- /**
1769
- *
1770
- * @param {Key} key
1771
- * @param {boolean} [inArray]
1772
- * @returns {string|null}
1773
- */
1774
- function _encode(key, inArray) {
1775
- // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation
1776
- if (key === undefined) {
1777
- return null;
1778
- }
1779
- // array, date, number, string, binary (should already have detected "invalid")
1780
- return types[getKeyType(key)].encode(key, inArray);
1781
- }
1782
-
1783
- /**
1784
- *
1785
- * @param {Key} key
1786
- * @param {boolean} [inArray]
1787
- * @throws {Error} Invalid number
1788
- * @returns {undefined|ValueType}
1789
- */
1790
- function _decode(key, inArray) {
1791
- if (typeof key !== 'string') {
1792
- return undefined;
1566
+ case 'array':
1567
+ {
1568
+ const array = [];
1569
+ const len = value.length;
1570
+ let index = 0;
1571
+ while (index < len) {
1572
+ const entry = convertKeyToValue(value[index]);
1573
+ array[index] = entry;
1574
+ index++;
1575
+ }
1576
+ return array;
1577
+ }
1578
+ case 'date':
1579
+ {
1580
+ return new Date(value);
1581
+ }
1582
+ case 'binary':
1583
+ {
1584
+ const len = value.length;
1585
+ const buffer = new ArrayBuffer(len);
1586
+ // Set the entries in buffer's [[ArrayBufferData]] to those in `value`
1587
+ const uint8 = new Uint8Array(buffer, value.byteOffset || 0, value.byteLength);
1588
+ uint8.set(value);
1589
+ return buffer;
1590
+ }
1591
+ case 'invalid':
1592
+ default:
1593
+ throw new Error('Bad key');
1594
+ }
1793
1595
  }
1794
- return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);
1795
- }
1796
-
1797
- /**
1798
- *
1799
- * @param {Key} key
1800
- * @param {boolean} [inArray]
1801
- * @returns {undefined|ValueType}
1802
- */
1803
- function roundTrip(key, inArray) {
1804
- return _decode(_encode(key, inArray), inArray);
1805
- }
1806
- var MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)
1807
-
1808
- /**
1809
- * @typedef {number} Integer
1810
- */
1811
-
1812
- /**
1813
- * @callback CurrentNumberCallback
1814
- * @param {Integer} cn The current number
1815
- * @returns {void}
1816
- */
1817
-
1818
- /**
1819
- * @callback SQLFailureCallback
1820
- * @param {DOMException|Error} exception
1821
- * @returns {void}
1822
- */
1823
-
1824
- /**
1825
- *
1826
- * @param {SQLTransaction} tx
1827
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1828
- * @param {CurrentNumberCallback} func
1829
- * @param {SQLFailureCallback} sqlFailCb
1830
- * @returns {void}
1831
- */
1832
- function getCurrentNumber(tx, store, func, sqlFailCb) {
1833
- tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function (tx, data) {
1834
- if (data.rows.length !== 1) {
1835
- func(1);
1836
- } else {
1837
- func(data.rows.item(0).currNum);
1596
+
1597
+ /**
1598
+ *
1599
+ * @param {Key} key
1600
+ * @param {boolean} [inArray]
1601
+ * @returns {string|null}
1602
+ */
1603
+ function encode(key, inArray) {
1604
+ // Bad keys like `null`, `object`, `boolean`, 'function', 'symbol' should not be passed here due to prior validation
1605
+ if (key === undefined) {
1606
+ return null;
1838
1607
  }
1839
- }, function (tx, error) {
1840
- sqlFailCb(createDOMException('DataError', 'Could not get the auto increment value for key', error));
1841
- return false;
1842
- });
1843
- }
1844
-
1845
- /**
1846
- *
1847
- * @param {SQLTransaction} tx
1848
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1849
- * @param {Integer} num
1850
- * @param {CurrentNumberCallback} successCb
1851
- * @param {SQLFailureCallback} failCb
1852
- * @returns {void}
1853
- */
1854
- function assignCurrentNumber(tx, store, num, successCb, failCb) {
1855
- var sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?';
1856
- var sqlValues = [num, escapeSQLiteStatement(store.__currentName)];
1857
- if (CFG.DEBUG) {
1858
- console.log(sql, sqlValues);
1608
+ // array, date, number, string, binary (should already have detected "invalid")
1609
+ return types[getKeyType(key)].encode(key, inArray);
1859
1610
  }
1860
- tx.executeSql(sql, sqlValues, function () {
1861
- successCb(num);
1862
- }, function (tx, err) {
1863
- failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));
1864
- return false;
1865
- });
1866
- }
1867
-
1868
- /**
1869
- * Bump up the auto-inc counter if the key path-resolved value is valid
1870
- * (greater than old value and >=1) OR if a manually passed in key is
1871
- * valid (numeric and >= 1) and >= any primaryKey.
1872
- * @param {SQLTransaction} tx
1873
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1874
- * @param {Integer} num
1875
- * @param {CurrentNumberCallback} successCb
1876
- * @param {SQLFailureCallback} failCb
1877
- * @returns {void}
1878
- */
1879
- function setCurrentNumber(tx, store, num, successCb, failCb) {
1880
- num = num === MAX_ALLOWED_CURRENT_NUMBER ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner
1881
- : num + 1;
1882
- return assignCurrentNumber(tx, store, num, successCb, failCb);
1883
- }
1884
-
1885
- /**
1886
- * @callback KeyForStoreCallback
1887
- * @param {"failure"|null} arg1
1888
- * @param {Integer} [arg2]
1889
- * @param {Integer} [arg3]
1890
- * @returns {void}
1891
- */
1892
-
1893
- /**
1894
- *
1895
- * @param {SQLTransaction} tx
1896
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1897
- * @param {KeyForStoreCallback} cb
1898
- * @param {SQLFailureCallback} sqlFailCb
1899
- * @returns {void}
1900
- */
1901
- function generateKeyForStore(tx, store, cb, sqlFailCb) {
1902
- getCurrentNumber(tx, store, function (key) {
1903
- if (key > MAX_ALLOWED_CURRENT_NUMBER) {
1904
- // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>)
1905
- cb('failure');
1906
- return;
1611
+
1612
+ /**
1613
+ *
1614
+ * @param {Key} key
1615
+ * @param {boolean} [inArray]
1616
+ * @throws {Error} Invalid number
1617
+ * @returns {undefined|ValueType}
1618
+ */
1619
+ function decode(key, inArray) {
1620
+ if (typeof key !== 'string') {
1621
+ return undefined;
1907
1622
  }
1908
- // Increment current number by 1 (we cannot leverage SQLite's
1909
- // autoincrement (and decrement when not needed), as decrementing
1910
- // will be overwritten/ignored upon the next insert)
1911
- setCurrentNumber(tx, store, key, function () {
1912
- cb(null, key, key);
1913
- }, sqlFailCb);
1914
- }, sqlFailCb);
1915
- }
1916
-
1917
- // Fractional or numbers exceeding the max do not get changed in the result
1918
- // per https://github.com/w3c/IndexedDB/issues/147
1919
- // so we do not return a key
1920
- /**
1921
- *
1922
- * @param {SQLTransaction} tx
1923
- * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1924
- * @param {Key} key
1925
- * @param {(num?: Integer) => void} successCb
1926
- * @param {SQLFailureCallback} sqlFailCb
1927
- * @returns {void}
1928
- */
1929
- function possiblyUpdateKeyGenerator(tx, store, key, successCb, sqlFailCb) {
1930
- // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers
1931
- // (or numbers larger than the max) are now to have the explicit effect of
1932
- // setting the current number (up to the max), so we do not optimize them
1933
- // out here
1934
- if (typeof key !== 'number' || key < 1) {
1935
- // Optimize with no need to get the current number
1936
- // Auto-increment attempted with a bad key;
1937
- // we are not to change the current number, but the steps don't call for failure
1938
- // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1
1939
- successCb();
1940
- } else {
1941
- // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher
1942
- // to determine which to use and whether to update the current number
1943
- getCurrentNumber(tx, store, function (cn) {
1944
- var value = Math.floor(Math.min(key, MAX_ALLOWED_CURRENT_NUMBER));
1945
- var useNewKeyForAutoInc = value >= cn;
1946
- if (useNewKeyForAutoInc) {
1947
- setCurrentNumber(tx, store, value, function () {
1948
- successCb(cn); // Supply old current number in case needs to be reverted
1949
- }, sqlFailCb);
1623
+ return types[encodedCharToKeyType[key.slice(0, 1)]].decode(key, inArray);
1624
+ }
1625
+
1626
+ /**
1627
+ *
1628
+ * @param {Key} key
1629
+ * @param {boolean} [inArray]
1630
+ * @returns {undefined|ValueType}
1631
+ */
1632
+ function roundTrip(key, inArray) {
1633
+ return decode(encode(key, inArray), inArray);
1634
+ }
1635
+ const MAX_ALLOWED_CURRENT_NUMBER = 9007199254740992; // 2 ^ 53 (Also equal to `Number.MAX_SAFE_INTEGER + 1`)
1636
+
1637
+ /**
1638
+ * @typedef {number} Integer
1639
+ */
1640
+
1641
+ /**
1642
+ * @callback CurrentNumberCallback
1643
+ * @param {Integer} cn The current number
1644
+ * @returns {void}
1645
+ */
1646
+
1647
+ /**
1648
+ * @callback SQLFailureCallback
1649
+ * @param {DOMException|Error} exception
1650
+ * @returns {void}
1651
+ */
1652
+
1653
+ /**
1654
+ *
1655
+ * @param {SQLTransaction} tx
1656
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1657
+ * @param {CurrentNumberCallback} func
1658
+ * @param {SQLFailureCallback} sqlFailCb
1659
+ * @returns {void}
1660
+ */
1661
+ function getCurrentNumber(tx, store, func, sqlFailCb) {
1662
+ tx.executeSql('SELECT "currNum" FROM __sys__ WHERE "name" = ?', [escapeSQLiteStatement(store.__currentName)], function (tx, data) {
1663
+ if (data.rows.length !== 1) {
1664
+ func(1);
1950
1665
  } else {
1951
- // Not updated
1952
- successCb();
1666
+ func(data.rows.item(0).currNum);
1667
+ }
1668
+ }, function (tx, error) {
1669
+ sqlFailCb(createDOMException('DataError', 'Could not get the auto increment value for key', error));
1670
+ return false;
1671
+ });
1672
+ }
1673
+
1674
+ /**
1675
+ *
1676
+ * @param {SQLTransaction} tx
1677
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1678
+ * @param {Integer} num
1679
+ * @param {CurrentNumberCallback} successCb
1680
+ * @param {SQLFailureCallback} failCb
1681
+ * @returns {void}
1682
+ */
1683
+ function assignCurrentNumber(tx, store, num, successCb, failCb) {
1684
+ const sql = 'UPDATE __sys__ SET "currNum" = ? WHERE "name" = ?';
1685
+ const sqlValues = [num, escapeSQLiteStatement(store.__currentName)];
1686
+ if (CFG.DEBUG) {
1687
+ console.log(sql, sqlValues);
1688
+ }
1689
+ tx.executeSql(sql, sqlValues, function () {
1690
+ successCb(num);
1691
+ }, function (tx, err) {
1692
+ failCb(createDOMException('UnknownError', 'Could not set the auto increment value for key', err));
1693
+ return false;
1694
+ });
1695
+ }
1696
+
1697
+ /**
1698
+ * Bump up the auto-inc counter if the key path-resolved value is valid
1699
+ * (greater than old value and >=1) OR if a manually passed in key is
1700
+ * valid (numeric and >= 1) and >= any primaryKey.
1701
+ * @param {SQLTransaction} tx
1702
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1703
+ * @param {Integer} num
1704
+ * @param {CurrentNumberCallback} successCb
1705
+ * @param {SQLFailureCallback} failCb
1706
+ * @returns {void}
1707
+ */
1708
+ function setCurrentNumber(tx, store, num, successCb, failCb) {
1709
+ num = num === MAX_ALLOWED_CURRENT_NUMBER ? num + 2 // Since incrementing by one will have no effect in JavaScript on this unsafe max, we represent the max as a number incremented by two. The getting of the current number is never returned to the user and is only used in safe comparisons, so it is safe for us to represent it in this manner
1710
+ : num + 1;
1711
+ return assignCurrentNumber(tx, store, num, successCb, failCb);
1712
+ }
1713
+
1714
+ /**
1715
+ * @callback KeyForStoreCallback
1716
+ * @param {"failure"|null} arg1
1717
+ * @param {Integer} [arg2]
1718
+ * @param {Integer} [arg3]
1719
+ * @returns {void}
1720
+ */
1721
+
1722
+ /**
1723
+ *
1724
+ * @param {SQLTransaction} tx
1725
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1726
+ * @param {KeyForStoreCallback} cb
1727
+ * @param {SQLFailureCallback} sqlFailCb
1728
+ * @returns {void}
1729
+ */
1730
+ function generateKeyForStore(tx, store, cb, sqlFailCb) {
1731
+ getCurrentNumber(tx, store, function (key) {
1732
+ if (key > MAX_ALLOWED_CURRENT_NUMBER) {
1733
+ // 2 ^ 53 (See <https://github.com/w3c/IndexedDB/issues/147>)
1734
+ cb('failure');
1735
+ return;
1953
1736
  }
1737
+ // Increment current number by 1 (we cannot leverage SQLite's
1738
+ // autoincrement (and decrement when not needed), as decrementing
1739
+ // will be overwritten/ignored upon the next insert)
1740
+ setCurrentNumber(tx, store, key, function () {
1741
+ cb(null, key, key);
1742
+ }, sqlFailCb);
1954
1743
  }, sqlFailCb);
1955
1744
  }
1956
- }
1957
-
1958
- exports.assignCurrentNumber = assignCurrentNumber;
1959
- exports.checkKeyCouldBeInjectedIntoValue = checkKeyCouldBeInjectedIntoValue;
1960
- exports.convertKeyToValue = convertKeyToValue;
1961
- exports.convertValueToKey = convertValueToKey;
1962
- exports.convertValueToKeyRethrowingAndIfInvalid = convertValueToKeyRethrowingAndIfInvalid;
1963
- exports.convertValueToKeyValueDecoded = convertValueToKeyValueDecoded;
1964
- exports.convertValueToMultiEntryKey = convertValueToMultiEntryKey;
1965
- exports.convertValueToMultiEntryKeyDecoded = convertValueToMultiEntryKeyDecoded;
1966
- exports.decode = _decode;
1967
- exports.encode = _encode;
1968
- exports.evaluateKeyPathOnValue = evaluateKeyPathOnValue;
1969
- exports.extractKeyFromValueUsingKeyPath = extractKeyFromValueUsingKeyPath;
1970
- exports.extractKeyValueDecodedFromValueUsingKeyPath = extractKeyValueDecodedFromValueUsingKeyPath;
1971
- exports.findMultiEntryMatches = findMultiEntryMatches;
1972
- exports.generateKeyForStore = generateKeyForStore;
1973
- exports.injectKeyIntoValueUsingKeyPath = injectKeyIntoValueUsingKeyPath;
1974
- exports.isKeyInRange = isKeyInRange;
1975
- exports.isMultiEntryMatch = isMultiEntryMatch;
1976
- exports.possiblyUpdateKeyGenerator = possiblyUpdateKeyGenerator;
1977
- exports.roundTrip = roundTrip;
1745
+
1746
+ // Fractional or numbers exceeding the max do not get changed in the result
1747
+ // per https://github.com/w3c/IndexedDB/issues/147
1748
+ // so we do not return a key
1749
+ /**
1750
+ *
1751
+ * @param {SQLTransaction} tx
1752
+ * @param {import('./IDBObjectStore.js').IDBObjectStoreFull} store
1753
+ * @param {Key} key
1754
+ * @param {(num?: Integer) => void} successCb
1755
+ * @param {SQLFailureCallback} sqlFailCb
1756
+ * @returns {void}
1757
+ */
1758
+ function possiblyUpdateKeyGenerator(tx, store, key, successCb, sqlFailCb) {
1759
+ // Per https://github.com/w3c/IndexedDB/issues/147 , non-finite numbers
1760
+ // (or numbers larger than the max) are now to have the explicit effect of
1761
+ // setting the current number (up to the max), so we do not optimize them
1762
+ // out here
1763
+ if (typeof key !== 'number' || key < 1) {
1764
+ // Optimize with no need to get the current number
1765
+ // Auto-increment attempted with a bad key;
1766
+ // we are not to change the current number, but the steps don't call for failure
1767
+ // Numbers < 1 are optimized out as they will never be greater than the current number which must be at least 1
1768
+ successCb();
1769
+ } else {
1770
+ // If auto-increment and the keyPath item is a valid numeric key, get the old auto-increment to compare if the new is higher
1771
+ // to determine which to use and whether to update the current number
1772
+ getCurrentNumber(tx, store, function (cn) {
1773
+ const value = Math.floor(Math.min(key, MAX_ALLOWED_CURRENT_NUMBER));
1774
+ const useNewKeyForAutoInc = value >= cn;
1775
+ if (useNewKeyForAutoInc) {
1776
+ setCurrentNumber(tx, store, value, function () {
1777
+ successCb(cn); // Supply old current number in case needs to be reverted
1778
+ }, sqlFailCb);
1779
+ } else {
1780
+ // Not updated
1781
+ successCb();
1782
+ }
1783
+ }, sqlFailCb);
1784
+ }
1785
+ }
1786
+
1787
+ exports.assignCurrentNumber = assignCurrentNumber;
1788
+ exports.checkKeyCouldBeInjectedIntoValue = checkKeyCouldBeInjectedIntoValue;
1789
+ exports.convertKeyToValue = convertKeyToValue;
1790
+ exports.convertValueToKey = convertValueToKey;
1791
+ exports.convertValueToKeyRethrowingAndIfInvalid = convertValueToKeyRethrowingAndIfInvalid;
1792
+ exports.convertValueToKeyValueDecoded = convertValueToKeyValueDecoded;
1793
+ exports.convertValueToMultiEntryKey = convertValueToMultiEntryKey;
1794
+ exports.convertValueToMultiEntryKeyDecoded = convertValueToMultiEntryKeyDecoded;
1795
+ exports.decode = decode;
1796
+ exports.encode = encode;
1797
+ exports.evaluateKeyPathOnValue = evaluateKeyPathOnValue;
1798
+ exports.extractKeyFromValueUsingKeyPath = extractKeyFromValueUsingKeyPath;
1799
+ exports.extractKeyValueDecodedFromValueUsingKeyPath = extractKeyValueDecodedFromValueUsingKeyPath;
1800
+ exports.findMultiEntryMatches = findMultiEntryMatches;
1801
+ exports.generateKeyForStore = generateKeyForStore;
1802
+ exports.injectKeyIntoValueUsingKeyPath = injectKeyIntoValueUsingKeyPath;
1803
+ exports.isKeyInRange = isKeyInRange;
1804
+ exports.isMultiEntryMatch = isMultiEntryMatch;
1805
+ exports.possiblyUpdateKeyGenerator = possiblyUpdateKeyGenerator;
1806
+ exports.roundTrip = roundTrip;
1978
1807
 
1979
1808
  }));
1980
1809
  //# sourceMappingURL=indexeddbshim-Key.js.map