@arbidocs/cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -2,111 +2,3353 @@
2
2
  'use strict';
3
3
 
4
4
  var commander = require('commander');
5
- var fs = require('fs');
6
- var path = require('path');
7
- var os = require('os');
8
- require('fake-indexeddb/auto');
5
+ var core = require('@arbidocs/core');
9
6
  var sdk = require('@arbidocs/sdk');
10
7
  var prompts = require('@inquirer/prompts');
8
+ var fs = require('fs');
9
+ var path2 = require('path');
10
+ var child_process = require('child_process');
11
+ var module$1 = require('module');
11
12
 
13
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
14
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
15
 
14
16
  var fs__default = /*#__PURE__*/_interopDefault(fs);
15
- var path__default = /*#__PURE__*/_interopDefault(path);
16
- var os__default = /*#__PURE__*/_interopDefault(os);
17
+ var path2__default = /*#__PURE__*/_interopDefault(path2);
18
+
19
+ var store = new core.FileConfigStore();
20
+ function getConfig() {
21
+ return store.getConfig();
22
+ }
23
+ function updateConfig(updates) {
24
+ store.updateConfig(updates);
25
+ }
26
+ function requireConfig() {
27
+ try {
28
+ return store.requireConfig();
29
+ } catch (err) {
30
+ if (err instanceof core.ArbiError) {
31
+ console.error(err.message);
32
+ process.exit(1);
33
+ }
34
+ throw err;
35
+ }
36
+ }
37
+ function getCredentials() {
38
+ return store.getCredentials();
39
+ }
40
+ function saveCredentials(creds) {
41
+ store.saveCredentials(creds);
42
+ }
43
+ function deleteCredentials() {
44
+ store.deleteCredentials();
45
+ }
46
+ function getChatSession() {
47
+ return store.getChatSession();
48
+ }
49
+ function updateChatSession(updates) {
50
+ store.updateChatSession(updates);
51
+ }
52
+ function clearChatSession() {
53
+ store.clearChatSession();
54
+ }
55
+
56
+ // src/commands/config-cmd.ts
57
+ function registerConfigCommand(program2) {
58
+ const config = program2.command("config").description("Manage CLI configuration");
59
+ config.command("set-url <url>").description("Set the ARBI server URL").action((url) => {
60
+ try {
61
+ const parsed = new URL(url);
62
+ const deploymentDomain = parsed.hostname;
63
+ updateConfig({ baseUrl: url.replace(/\/+$/, ""), deploymentDomain });
64
+ console.log(`Server URL: ${url}`);
65
+ console.log(`Domain: ${deploymentDomain}`);
66
+ } catch {
67
+ console.error(`Invalid URL: ${url}`);
68
+ process.exit(1);
69
+ }
70
+ });
71
+ }
72
+
73
+ // ../../node_modules/fake-indexeddb/build/esm/lib/errors.js
74
+ var messages = {
75
+ AbortError: "A request was aborted, for example through a call to IDBTransaction.abort.",
76
+ ConstraintError: "A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one.",
77
+ DataError: "Data provided to an operation does not meet requirements.",
78
+ InvalidAccessError: "An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided.",
79
+ InvalidStateError: "An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError.",
80
+ NotFoundError: "The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.",
81
+ ReadOnlyError: 'The mutating operation was attempted in a "readonly" transaction.',
82
+ TransactionInactiveError: "A request was placed against a transaction which is currently not active, or which is finished.",
83
+ VersionError: "An attempt was made to open a database using a lower version than the existing version."
84
+ };
85
+ var setErrorCode = (error, value) => {
86
+ Object.defineProperty(error, "code", {
87
+ value,
88
+ writable: false,
89
+ enumerable: true,
90
+ configurable: false
91
+ });
92
+ };
93
+ var AbortError = class extends DOMException {
94
+ constructor(message = messages.AbortError) {
95
+ super(message, "AbortError");
96
+ }
97
+ };
98
+ var ConstraintError = class extends DOMException {
99
+ constructor(message = messages.ConstraintError) {
100
+ super(message, "ConstraintError");
101
+ }
102
+ };
103
+ var DataError = class extends DOMException {
104
+ constructor(message = messages.DataError) {
105
+ super(message, "DataError");
106
+ setErrorCode(this, 0);
107
+ }
108
+ };
109
+ var InvalidAccessError = class extends DOMException {
110
+ constructor(message = messages.InvalidAccessError) {
111
+ super(message, "InvalidAccessError");
112
+ }
113
+ };
114
+ var InvalidStateError = class extends DOMException {
115
+ constructor(message = messages.InvalidStateError) {
116
+ super(message, "InvalidStateError");
117
+ setErrorCode(this, 11);
118
+ }
119
+ };
120
+ var NotFoundError = class extends DOMException {
121
+ constructor(message = messages.NotFoundError) {
122
+ super(message, "NotFoundError");
123
+ }
124
+ };
125
+ var ReadOnlyError = class extends DOMException {
126
+ constructor(message = messages.ReadOnlyError) {
127
+ super(message, "ReadOnlyError");
128
+ }
129
+ };
130
+ var SyntaxError = class extends DOMException {
131
+ constructor(message = messages.VersionError) {
132
+ super(message, "SyntaxError");
133
+ setErrorCode(this, 12);
134
+ }
135
+ };
136
+ var TransactionInactiveError = class extends DOMException {
137
+ constructor(message = messages.TransactionInactiveError) {
138
+ super(message, "TransactionInactiveError");
139
+ setErrorCode(this, 0);
140
+ }
141
+ };
142
+ var VersionError = class extends DOMException {
143
+ constructor(message = messages.VersionError) {
144
+ super(message, "VersionError");
145
+ }
146
+ };
147
+
148
+ // ../../node_modules/fake-indexeddb/build/esm/lib/isSharedArrayBuffer.js
149
+ function isSharedArrayBuffer(input2) {
150
+ return typeof SharedArrayBuffer !== "undefined" && input2 instanceof SharedArrayBuffer;
151
+ }
152
+
153
+ // ../../node_modules/fake-indexeddb/build/esm/lib/valueToKeyWithoutThrowing.js
154
+ var INVALID_TYPE = /* @__PURE__ */ Symbol("INVALID_TYPE");
155
+ var INVALID_VALUE = /* @__PURE__ */ Symbol("INVALID_VALUE");
156
+ var valueToKeyWithoutThrowing = (input2, seen) => {
157
+ if (typeof input2 === "number") {
158
+ if (isNaN(input2)) {
159
+ return INVALID_VALUE;
160
+ }
161
+ return input2;
162
+ } else if (Object.prototype.toString.call(input2) === "[object Date]") {
163
+ const ms = input2.valueOf();
164
+ if (isNaN(ms)) {
165
+ return INVALID_VALUE;
166
+ }
167
+ return new Date(ms);
168
+ } else if (typeof input2 === "string") {
169
+ return input2;
170
+ } else if (
171
+ // https://w3c.github.io/IndexedDB/#ref-for-dfn-buffer-source-type
172
+ input2 instanceof ArrayBuffer || isSharedArrayBuffer(input2) || typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(input2)
173
+ ) {
174
+ if ("detached" in input2 ? input2.detached : input2.byteLength === 0) {
175
+ return INVALID_VALUE;
176
+ }
177
+ let arrayBuffer;
178
+ let offset = 0;
179
+ let length = 0;
180
+ if (input2 instanceof ArrayBuffer || isSharedArrayBuffer(input2)) {
181
+ arrayBuffer = input2;
182
+ length = input2.byteLength;
183
+ } else {
184
+ arrayBuffer = input2.buffer;
185
+ offset = input2.byteOffset;
186
+ length = input2.byteLength;
187
+ }
188
+ return arrayBuffer.slice(offset, offset + length);
189
+ } else if (Array.isArray(input2)) {
190
+ if (seen === void 0) {
191
+ seen = /* @__PURE__ */ new Set();
192
+ } else if (seen.has(input2)) {
193
+ return INVALID_VALUE;
194
+ }
195
+ seen.add(input2);
196
+ let hasInvalid = false;
197
+ const keys = Array.from({
198
+ length: input2.length
199
+ }, (_, i) => {
200
+ if (hasInvalid) {
201
+ return;
202
+ }
203
+ const hop = Object.hasOwn(input2, i);
204
+ if (!hop) {
205
+ hasInvalid = true;
206
+ return;
207
+ }
208
+ const entry = input2[i];
209
+ const key = valueToKeyWithoutThrowing(entry, seen);
210
+ if (key === INVALID_VALUE || key === INVALID_TYPE) {
211
+ hasInvalid = true;
212
+ return;
213
+ }
214
+ return key;
215
+ });
216
+ if (hasInvalid) {
217
+ return INVALID_VALUE;
218
+ }
219
+ return keys;
220
+ } else {
221
+ return INVALID_TYPE;
222
+ }
223
+ };
224
+ var valueToKeyWithoutThrowing_default = valueToKeyWithoutThrowing;
225
+
226
+ // ../../node_modules/fake-indexeddb/build/esm/lib/valueToKey.js
227
+ var valueToKey = (input2, seen) => {
228
+ const result = valueToKeyWithoutThrowing_default(input2, seen);
229
+ if (result === INVALID_VALUE || result === INVALID_TYPE) {
230
+ throw new DataError();
231
+ }
232
+ return result;
233
+ };
234
+ var valueToKey_default = valueToKey;
235
+
236
+ // ../../node_modules/fake-indexeddb/build/esm/lib/cmp.js
237
+ var getType = (x) => {
238
+ if (typeof x === "number") {
239
+ return "Number";
240
+ }
241
+ if (Object.prototype.toString.call(x) === "[object Date]") {
242
+ return "Date";
243
+ }
244
+ if (Array.isArray(x)) {
245
+ return "Array";
246
+ }
247
+ if (typeof x === "string") {
248
+ return "String";
249
+ }
250
+ if (x instanceof ArrayBuffer) {
251
+ return "Binary";
252
+ }
253
+ throw new DataError();
254
+ };
255
+ var cmp = (first, second) => {
256
+ if (second === void 0) {
257
+ throw new TypeError();
258
+ }
259
+ first = valueToKey_default(first);
260
+ second = valueToKey_default(second);
261
+ const t1 = getType(first);
262
+ const t2 = getType(second);
263
+ if (t1 !== t2) {
264
+ if (t1 === "Array") {
265
+ return 1;
266
+ }
267
+ if (t1 === "Binary" && (t2 === "String" || t2 === "Date" || t2 === "Number")) {
268
+ return 1;
269
+ }
270
+ if (t1 === "String" && (t2 === "Date" || t2 === "Number")) {
271
+ return 1;
272
+ }
273
+ if (t1 === "Date" && t2 === "Number") {
274
+ return 1;
275
+ }
276
+ return -1;
277
+ }
278
+ if (t1 === "Binary") {
279
+ first = new Uint8Array(first);
280
+ second = new Uint8Array(second);
281
+ }
282
+ if (t1 === "Array" || t1 === "Binary") {
283
+ const length = Math.min(first.length, second.length);
284
+ for (let i = 0; i < length; i++) {
285
+ const result = cmp(first[i], second[i]);
286
+ if (result !== 0) {
287
+ return result;
288
+ }
289
+ }
290
+ if (first.length > second.length) {
291
+ return 1;
292
+ }
293
+ if (first.length < second.length) {
294
+ return -1;
295
+ }
296
+ return 0;
297
+ }
298
+ if (t1 === "Date") {
299
+ if (first.getTime() === second.getTime()) {
300
+ return 0;
301
+ }
302
+ } else {
303
+ if (first === second) {
304
+ return 0;
305
+ }
306
+ }
307
+ return first > second ? 1 : -1;
308
+ };
309
+ var cmp_default = cmp;
310
+
311
+ // ../../node_modules/fake-indexeddb/build/esm/FDBKeyRange.js
312
+ var FDBKeyRange = class _FDBKeyRange {
313
+ static only(value) {
314
+ if (arguments.length === 0) {
315
+ throw new TypeError();
316
+ }
317
+ value = valueToKey_default(value);
318
+ return new _FDBKeyRange(value, value, false, false);
319
+ }
320
+ static lowerBound(lower, open = false) {
321
+ if (arguments.length === 0) {
322
+ throw new TypeError();
323
+ }
324
+ lower = valueToKey_default(lower);
325
+ return new _FDBKeyRange(lower, void 0, open, true);
326
+ }
327
+ static upperBound(upper, open = false) {
328
+ if (arguments.length === 0) {
329
+ throw new TypeError();
330
+ }
331
+ upper = valueToKey_default(upper);
332
+ return new _FDBKeyRange(void 0, upper, true, open);
333
+ }
334
+ static bound(lower, upper, lowerOpen = false, upperOpen = false) {
335
+ if (arguments.length < 2) {
336
+ throw new TypeError();
337
+ }
338
+ const cmpResult = cmp_default(lower, upper);
339
+ if (cmpResult === 1 || cmpResult === 0 && (lowerOpen || upperOpen)) {
340
+ throw new DataError();
341
+ }
342
+ lower = valueToKey_default(lower);
343
+ upper = valueToKey_default(upper);
344
+ return new _FDBKeyRange(lower, upper, lowerOpen, upperOpen);
345
+ }
346
+ constructor(lower, upper, lowerOpen, upperOpen) {
347
+ this.lower = lower;
348
+ this.upper = upper;
349
+ this.lowerOpen = lowerOpen;
350
+ this.upperOpen = upperOpen;
351
+ }
352
+ // https://w3c.github.io/IndexedDB/#dom-idbkeyrange-includes
353
+ includes(key) {
354
+ if (arguments.length === 0) {
355
+ throw new TypeError();
356
+ }
357
+ key = valueToKey_default(key);
358
+ if (this.lower !== void 0) {
359
+ const cmpResult = cmp_default(this.lower, key);
360
+ if (cmpResult === 1 || cmpResult === 0 && this.lowerOpen) {
361
+ return false;
362
+ }
363
+ }
364
+ if (this.upper !== void 0) {
365
+ const cmpResult = cmp_default(this.upper, key);
366
+ if (cmpResult === -1 || cmpResult === 0 && this.upperOpen) {
367
+ return false;
368
+ }
369
+ }
370
+ return true;
371
+ }
372
+ get [Symbol.toStringTag]() {
373
+ return "IDBKeyRange";
374
+ }
375
+ };
376
+ var FDBKeyRange_default = FDBKeyRange;
377
+
378
+ // ../../node_modules/fake-indexeddb/build/esm/lib/extractKey.js
379
+ var extractKey = (keyPath, value) => {
380
+ if (Array.isArray(keyPath)) {
381
+ const result = [];
382
+ for (let item of keyPath) {
383
+ if (item !== void 0 && item !== null && typeof item !== "string" && item.toString) {
384
+ item = item.toString();
385
+ }
386
+ const key = extractKey(item, value).key;
387
+ result.push(valueToKey_default(key));
388
+ }
389
+ return {
390
+ type: "found",
391
+ key: result
392
+ };
393
+ }
394
+ if (keyPath === "") {
395
+ return {
396
+ type: "found",
397
+ key: value
398
+ };
399
+ }
400
+ let remainingKeyPath = keyPath;
401
+ let object = value;
402
+ while (remainingKeyPath !== null) {
403
+ let identifier;
404
+ const i = remainingKeyPath.indexOf(".");
405
+ if (i >= 0) {
406
+ identifier = remainingKeyPath.slice(0, i);
407
+ remainingKeyPath = remainingKeyPath.slice(i + 1);
408
+ } else {
409
+ identifier = remainingKeyPath;
410
+ remainingKeyPath = null;
411
+ }
412
+ const isSpecialIdentifier = identifier === "length" && (typeof object === "string" || Array.isArray(object)) || (identifier === "size" || identifier === "type") && typeof Blob !== "undefined" && object instanceof Blob || (identifier === "name" || identifier === "lastModified") && typeof File !== "undefined" && object instanceof File;
413
+ if (!isSpecialIdentifier && (typeof object !== "object" || object === null || !Object.hasOwn(object, identifier))) {
414
+ return {
415
+ type: "notFound"
416
+ };
417
+ }
418
+ object = object[identifier];
419
+ }
420
+ return {
421
+ type: "found",
422
+ key: object
423
+ };
424
+ };
425
+ var extractKey_default = extractKey;
426
+
427
+ // ../../node_modules/fake-indexeddb/build/esm/lib/cloneValueForInsertion.js
428
+ function cloneValueForInsertion(value, transaction) {
429
+ if (transaction._state !== "active") {
430
+ throw new Error("Assert: transaction state is active");
431
+ }
432
+ transaction._state = "inactive";
433
+ try {
434
+ return structuredClone(value);
435
+ } finally {
436
+ transaction._state = "active";
437
+ }
438
+ }
17
439
 
18
- var CONFIG_DIR = path__default.default.join(os__default.default.homedir(), ".arbi");
19
- var CONFIG_FILE = path__default.default.join(CONFIG_DIR, "config.json");
20
- var CREDENTIALS_FILE = path__default.default.join(CONFIG_DIR, "credentials.json");
21
- function ensureConfigDir() {
22
- if (!fs__default.default.existsSync(CONFIG_DIR)) {
23
- fs__default.default.mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
440
+ // ../../node_modules/fake-indexeddb/build/esm/FDBCursor.js
441
+ var getEffectiveObjectStore = (cursor) => {
442
+ if (cursor.source instanceof FDBObjectStore_default) {
443
+ return cursor.source;
444
+ }
445
+ return cursor.source.objectStore;
446
+ };
447
+ var makeKeyRange = (range, lowers, uppers) => {
448
+ let lower = range !== void 0 ? range.lower : void 0;
449
+ let upper = range !== void 0 ? range.upper : void 0;
450
+ for (const lowerTemp of lowers) {
451
+ if (lowerTemp === void 0) {
452
+ continue;
453
+ }
454
+ if (lower === void 0 || cmp_default(lower, lowerTemp) === 1) {
455
+ lower = lowerTemp;
456
+ }
457
+ }
458
+ for (const upperTemp of uppers) {
459
+ if (upperTemp === void 0) {
460
+ continue;
461
+ }
462
+ if (upper === void 0 || cmp_default(upper, upperTemp) === -1) {
463
+ upper = upperTemp;
464
+ }
465
+ }
466
+ if (lower !== void 0 && upper !== void 0) {
467
+ return FDBKeyRange_default.bound(lower, upper);
468
+ }
469
+ if (lower !== void 0) {
470
+ return FDBKeyRange_default.lowerBound(lower);
471
+ }
472
+ if (upper !== void 0) {
473
+ return FDBKeyRange_default.upperBound(upper);
474
+ }
475
+ };
476
+ var FDBCursor = class {
477
+ _gotValue = false;
478
+ _position = void 0;
479
+ // Key of previously returned record
480
+ _objectStorePosition = void 0;
481
+ _keyOnly = false;
482
+ _key = void 0;
483
+ _primaryKey = void 0;
484
+ constructor(source, range, direction = "next", request, keyOnly = false) {
485
+ this._range = range;
486
+ this._source = source;
487
+ this._direction = direction;
488
+ this._request = request;
489
+ this._keyOnly = keyOnly;
490
+ }
491
+ // Read only properties
492
+ get source() {
493
+ return this._source;
494
+ }
495
+ set source(val) {
496
+ }
497
+ get request() {
498
+ return this._request;
499
+ }
500
+ set request(val) {
501
+ }
502
+ get direction() {
503
+ return this._direction;
504
+ }
505
+ set direction(val) {
506
+ }
507
+ get key() {
508
+ return this._key;
509
+ }
510
+ set key(val) {
511
+ }
512
+ get primaryKey() {
513
+ return this._primaryKey;
514
+ }
515
+ set primaryKey(val) {
516
+ }
517
+ // https://w3c.github.io/IndexedDB/#iterate-a-cursor
518
+ _iterate(key, primaryKey) {
519
+ const sourceIsObjectStore = this.source instanceof FDBObjectStore_default;
520
+ const records = this.source instanceof FDBObjectStore_default ? this.source._rawObjectStore.records : this.source._rawIndex.records;
521
+ let foundRecord;
522
+ if (this.direction === "next") {
523
+ const range = makeKeyRange(this._range, [key, this._position], []);
524
+ for (const record of records.values(range)) {
525
+ const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0;
526
+ const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0;
527
+ if (key !== void 0) {
528
+ if (cmpResultKey === -1) {
529
+ continue;
530
+ }
531
+ }
532
+ if (primaryKey !== void 0) {
533
+ if (cmpResultKey === -1) {
534
+ continue;
535
+ }
536
+ const cmpResultPrimaryKey = cmp_default(record.value, primaryKey);
537
+ if (cmpResultKey === 0 && cmpResultPrimaryKey === -1) {
538
+ continue;
539
+ }
540
+ }
541
+ if (this._position !== void 0 && sourceIsObjectStore) {
542
+ if (cmpResultPosition !== 1) {
543
+ continue;
544
+ }
545
+ }
546
+ if (this._position !== void 0 && !sourceIsObjectStore) {
547
+ if (cmpResultPosition === -1) {
548
+ continue;
549
+ }
550
+ if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== 1) {
551
+ continue;
552
+ }
553
+ }
554
+ if (this._range !== void 0) {
555
+ if (!this._range.includes(record.key)) {
556
+ continue;
557
+ }
558
+ }
559
+ foundRecord = record;
560
+ break;
561
+ }
562
+ } else if (this.direction === "nextunique") {
563
+ const range = makeKeyRange(this._range, [key, this._position], []);
564
+ for (const record of records.values(range)) {
565
+ if (key !== void 0) {
566
+ if (cmp_default(record.key, key) === -1) {
567
+ continue;
568
+ }
569
+ }
570
+ if (this._position !== void 0) {
571
+ if (cmp_default(record.key, this._position) !== 1) {
572
+ continue;
573
+ }
574
+ }
575
+ if (this._range !== void 0) {
576
+ if (!this._range.includes(record.key)) {
577
+ continue;
578
+ }
579
+ }
580
+ foundRecord = record;
581
+ break;
582
+ }
583
+ } else if (this.direction === "prev") {
584
+ const range = makeKeyRange(this._range, [], [key, this._position]);
585
+ for (const record of records.values(range, "prev")) {
586
+ const cmpResultKey = key !== void 0 ? cmp_default(record.key, key) : void 0;
587
+ const cmpResultPosition = this._position !== void 0 ? cmp_default(record.key, this._position) : void 0;
588
+ if (key !== void 0) {
589
+ if (cmpResultKey === 1) {
590
+ continue;
591
+ }
592
+ }
593
+ if (primaryKey !== void 0) {
594
+ if (cmpResultKey === 1) {
595
+ continue;
596
+ }
597
+ const cmpResultPrimaryKey = cmp_default(record.value, primaryKey);
598
+ if (cmpResultKey === 0 && cmpResultPrimaryKey === 1) {
599
+ continue;
600
+ }
601
+ }
602
+ if (this._position !== void 0 && sourceIsObjectStore) {
603
+ if (cmpResultPosition !== -1) {
604
+ continue;
605
+ }
606
+ }
607
+ if (this._position !== void 0 && !sourceIsObjectStore) {
608
+ if (cmpResultPosition === 1) {
609
+ continue;
610
+ }
611
+ if (cmpResultPosition === 0 && cmp_default(record.value, this._objectStorePosition) !== -1) {
612
+ continue;
613
+ }
614
+ }
615
+ if (this._range !== void 0) {
616
+ if (!this._range.includes(record.key)) {
617
+ continue;
618
+ }
619
+ }
620
+ foundRecord = record;
621
+ break;
622
+ }
623
+ } else if (this.direction === "prevunique") {
624
+ let tempRecord;
625
+ const range = makeKeyRange(this._range, [], [key, this._position]);
626
+ for (const record of records.values(range, "prev")) {
627
+ if (key !== void 0) {
628
+ if (cmp_default(record.key, key) === 1) {
629
+ continue;
630
+ }
631
+ }
632
+ if (this._position !== void 0) {
633
+ if (cmp_default(record.key, this._position) !== -1) {
634
+ continue;
635
+ }
636
+ }
637
+ if (this._range !== void 0) {
638
+ if (!this._range.includes(record.key)) {
639
+ continue;
640
+ }
641
+ }
642
+ tempRecord = record;
643
+ break;
644
+ }
645
+ if (tempRecord) {
646
+ foundRecord = records.get(tempRecord.key);
647
+ }
648
+ }
649
+ let result;
650
+ if (!foundRecord) {
651
+ this._key = void 0;
652
+ if (!sourceIsObjectStore) {
653
+ this._objectStorePosition = void 0;
654
+ }
655
+ if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") {
656
+ this.value = void 0;
657
+ }
658
+ result = null;
659
+ } else {
660
+ this._position = foundRecord.key;
661
+ if (!sourceIsObjectStore) {
662
+ this._objectStorePosition = foundRecord.value;
663
+ }
664
+ this._key = foundRecord.key;
665
+ if (sourceIsObjectStore) {
666
+ this._primaryKey = structuredClone(foundRecord.key);
667
+ if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") {
668
+ this.value = structuredClone(foundRecord.value);
669
+ }
670
+ } else {
671
+ this._primaryKey = structuredClone(foundRecord.value);
672
+ if (!this._keyOnly && this.toString() === "[object IDBCursorWithValue]") {
673
+ if (this.source instanceof FDBObjectStore_default) {
674
+ throw new Error("This should never happen");
675
+ }
676
+ const value = this.source.objectStore._rawObjectStore.getValue(foundRecord.value);
677
+ this.value = structuredClone(value);
678
+ }
679
+ }
680
+ this._gotValue = true;
681
+ result = this;
682
+ }
683
+ return result;
684
+ }
685
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-update-IDBRequest-any-value
686
+ update(value) {
687
+ if (value === void 0) {
688
+ throw new TypeError();
689
+ }
690
+ const effectiveObjectStore = getEffectiveObjectStore(this);
691
+ const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position;
692
+ const transaction = effectiveObjectStore.transaction;
693
+ if (transaction._state !== "active") {
694
+ throw new TransactionInactiveError();
695
+ }
696
+ if (transaction.mode === "readonly") {
697
+ throw new ReadOnlyError();
698
+ }
699
+ if (effectiveObjectStore._rawObjectStore.deleted) {
700
+ throw new InvalidStateError();
701
+ }
702
+ if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) {
703
+ throw new InvalidStateError();
704
+ }
705
+ if (!this._gotValue || !Object.hasOwn(this, "value")) {
706
+ throw new InvalidStateError();
707
+ }
708
+ const clone = cloneValueForInsertion(value, transaction);
709
+ if (effectiveObjectStore.keyPath !== null) {
710
+ let tempKey;
711
+ try {
712
+ tempKey = extractKey_default(effectiveObjectStore.keyPath, clone).key;
713
+ } catch (err) {
714
+ }
715
+ if (cmp_default(tempKey, effectiveKey) !== 0) {
716
+ throw new DataError();
717
+ }
718
+ }
719
+ const record = {
720
+ key: effectiveKey,
721
+ value: clone
722
+ };
723
+ return transaction._execRequestAsync({
724
+ operation: effectiveObjectStore._rawObjectStore.storeRecord.bind(effectiveObjectStore._rawObjectStore, record, false, transaction._rollbackLog),
725
+ source: this
726
+ });
727
+ }
728
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-advance-void-unsigned-long-count
729
+ advance(count) {
730
+ if (!Number.isInteger(count) || count <= 0) {
731
+ throw new TypeError();
732
+ }
733
+ const effectiveObjectStore = getEffectiveObjectStore(this);
734
+ const transaction = effectiveObjectStore.transaction;
735
+ if (transaction._state !== "active") {
736
+ throw new TransactionInactiveError();
737
+ }
738
+ if (effectiveObjectStore._rawObjectStore.deleted) {
739
+ throw new InvalidStateError();
740
+ }
741
+ if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) {
742
+ throw new InvalidStateError();
743
+ }
744
+ if (!this._gotValue) {
745
+ throw new InvalidStateError();
746
+ }
747
+ if (this._request) {
748
+ this._request.readyState = "pending";
749
+ }
750
+ transaction._execRequestAsync({
751
+ operation: () => {
752
+ let result;
753
+ for (let i = 0; i < count; i++) {
754
+ result = this._iterate();
755
+ if (!result) {
756
+ break;
757
+ }
758
+ }
759
+ return result;
760
+ },
761
+ request: this._request,
762
+ source: this.source
763
+ });
764
+ this._gotValue = false;
765
+ }
766
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBCursor-continue-void-any-key
767
+ continue(key) {
768
+ const effectiveObjectStore = getEffectiveObjectStore(this);
769
+ const transaction = effectiveObjectStore.transaction;
770
+ if (transaction._state !== "active") {
771
+ throw new TransactionInactiveError();
772
+ }
773
+ if (effectiveObjectStore._rawObjectStore.deleted) {
774
+ throw new InvalidStateError();
775
+ }
776
+ if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) {
777
+ throw new InvalidStateError();
778
+ }
779
+ if (!this._gotValue) {
780
+ throw new InvalidStateError();
781
+ }
782
+ if (key !== void 0) {
783
+ key = valueToKey_default(key);
784
+ const cmpResult = cmp_default(key, this._position);
785
+ if (cmpResult <= 0 && (this.direction === "next" || this.direction === "nextunique") || cmpResult >= 0 && (this.direction === "prev" || this.direction === "prevunique")) {
786
+ throw new DataError();
787
+ }
788
+ }
789
+ if (this._request) {
790
+ this._request.readyState = "pending";
791
+ }
792
+ transaction._execRequestAsync({
793
+ operation: this._iterate.bind(this, key),
794
+ request: this._request,
795
+ source: this.source
796
+ });
797
+ this._gotValue = false;
798
+ }
799
+ // hthttps://w3c.github.io/IndexedDB/#dom-idbcursor-continueprimarykey
800
+ continuePrimaryKey(key, primaryKey) {
801
+ const effectiveObjectStore = getEffectiveObjectStore(this);
802
+ const transaction = effectiveObjectStore.transaction;
803
+ if (transaction._state !== "active") {
804
+ throw new TransactionInactiveError();
805
+ }
806
+ if (effectiveObjectStore._rawObjectStore.deleted) {
807
+ throw new InvalidStateError();
808
+ }
809
+ if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) {
810
+ throw new InvalidStateError();
811
+ }
812
+ if (this.source instanceof FDBObjectStore_default || this.direction !== "next" && this.direction !== "prev") {
813
+ throw new InvalidAccessError();
814
+ }
815
+ if (!this._gotValue) {
816
+ throw new InvalidStateError();
817
+ }
818
+ if (key === void 0 || primaryKey === void 0) {
819
+ throw new DataError();
820
+ }
821
+ key = valueToKey_default(key);
822
+ const cmpResult = cmp_default(key, this._position);
823
+ if (cmpResult === -1 && this.direction === "next" || cmpResult === 1 && this.direction === "prev") {
824
+ throw new DataError();
825
+ }
826
+ const cmpResult2 = cmp_default(primaryKey, this._objectStorePosition);
827
+ if (cmpResult === 0) {
828
+ if (cmpResult2 <= 0 && this.direction === "next" || cmpResult2 >= 0 && this.direction === "prev") {
829
+ throw new DataError();
830
+ }
831
+ }
832
+ if (this._request) {
833
+ this._request.readyState = "pending";
834
+ }
835
+ transaction._execRequestAsync({
836
+ operation: this._iterate.bind(this, key, primaryKey),
837
+ request: this._request,
838
+ source: this.source
839
+ });
840
+ this._gotValue = false;
841
+ }
842
+ delete() {
843
+ const effectiveObjectStore = getEffectiveObjectStore(this);
844
+ const effectiveKey = Object.hasOwn(this.source, "_rawIndex") ? this.primaryKey : this._position;
845
+ const transaction = effectiveObjectStore.transaction;
846
+ if (transaction._state !== "active") {
847
+ throw new TransactionInactiveError();
848
+ }
849
+ if (transaction.mode === "readonly") {
850
+ throw new ReadOnlyError();
851
+ }
852
+ if (effectiveObjectStore._rawObjectStore.deleted) {
853
+ throw new InvalidStateError();
854
+ }
855
+ if (!(this.source instanceof FDBObjectStore_default) && this.source._rawIndex.deleted) {
856
+ throw new InvalidStateError();
857
+ }
858
+ if (!this._gotValue || !Object.hasOwn(this, "value")) {
859
+ throw new InvalidStateError();
860
+ }
861
+ return transaction._execRequestAsync({
862
+ operation: effectiveObjectStore._rawObjectStore.deleteRecord.bind(effectiveObjectStore._rawObjectStore, effectiveKey, transaction._rollbackLog),
863
+ source: this
864
+ });
865
+ }
866
+ get [Symbol.toStringTag]() {
867
+ return "IDBCursor";
868
+ }
869
+ };
870
+ var FDBCursor_default = FDBCursor;
871
+
872
+ // ../../node_modules/fake-indexeddb/build/esm/FDBCursorWithValue.js
873
+ var FDBCursorWithValue = class extends FDBCursor_default {
874
+ value = void 0;
875
+ constructor(source, range, direction, request) {
876
+ super(source, range, direction, request);
877
+ }
878
+ get [Symbol.toStringTag]() {
879
+ return "IDBCursorWithValue";
880
+ }
881
+ };
882
+ var FDBCursorWithValue_default = FDBCursorWithValue;
883
+
884
+ // ../../node_modules/fake-indexeddb/build/esm/lib/FakeEventTarget.js
885
+ var stopped = (event, listener) => {
886
+ return event.immediatePropagationStopped || event.eventPhase === event.CAPTURING_PHASE && listener.capture === false || event.eventPhase === event.BUBBLING_PHASE && listener.capture === true;
887
+ };
888
+ var invokeEventListeners = (event, obj) => {
889
+ event.currentTarget = obj;
890
+ const errors = [];
891
+ const invoke = (callbackOrObject) => {
892
+ try {
893
+ const callback2 = typeof callbackOrObject === "function" ? callbackOrObject : callbackOrObject.handleEvent;
894
+ callback2.call(event.currentTarget, event);
895
+ } catch (err) {
896
+ errors.push(err);
897
+ }
898
+ };
899
+ for (const listener of obj.listeners.slice()) {
900
+ if (event.type !== listener.type || stopped(event, listener)) {
901
+ continue;
902
+ }
903
+ invoke(listener.callback);
904
+ }
905
+ const typeToProp = {
906
+ abort: "onabort",
907
+ blocked: "onblocked",
908
+ close: "onclose",
909
+ complete: "oncomplete",
910
+ error: "onerror",
911
+ success: "onsuccess",
912
+ upgradeneeded: "onupgradeneeded",
913
+ versionchange: "onversionchange"
914
+ };
915
+ const prop = typeToProp[event.type];
916
+ if (prop === void 0) {
917
+ throw new Error(`Unknown event type: "${event.type}"`);
918
+ }
919
+ const callback = event.currentTarget[prop];
920
+ if (callback) {
921
+ const listener = {
922
+ callback,
923
+ capture: false,
924
+ type: event.type
925
+ };
926
+ if (!stopped(event, listener)) {
927
+ invoke(listener.callback);
928
+ }
929
+ }
930
+ if (errors.length) {
931
+ throw new AggregateError(errors);
932
+ }
933
+ };
934
+ var FakeEventTarget = class {
935
+ listeners = [];
936
+ // These will be overridden in individual subclasses and made not readonly
937
+ addEventListener(type, callback, options) {
938
+ const capture = !!(typeof options === "object" && options ? options.capture : options);
939
+ this.listeners.push({
940
+ callback,
941
+ capture,
942
+ type
943
+ });
944
+ }
945
+ removeEventListener(type, callback, options) {
946
+ const capture = !!(typeof options === "object" && options ? options.capture : options);
947
+ const i = this.listeners.findIndex((listener) => {
948
+ return listener.type === type && listener.callback === callback && listener.capture === capture;
949
+ });
950
+ this.listeners.splice(i, 1);
951
+ }
952
+ // http://www.w3.org/TR/dom/#dispatching-events
953
+ dispatchEvent(event) {
954
+ if (event.dispatched || !event.initialized) {
955
+ throw new InvalidStateError("The object is in an invalid state.");
956
+ }
957
+ event.isTrusted = false;
958
+ event.dispatched = true;
959
+ event.target = this;
960
+ event.eventPhase = event.CAPTURING_PHASE;
961
+ for (const obj of event.eventPath) {
962
+ if (!event.propagationStopped) {
963
+ invokeEventListeners(event, obj);
964
+ }
965
+ }
966
+ event.eventPhase = event.AT_TARGET;
967
+ if (!event.propagationStopped) {
968
+ invokeEventListeners(event, event.target);
969
+ }
970
+ if (event.bubbles) {
971
+ event.eventPath.reverse();
972
+ event.eventPhase = event.BUBBLING_PHASE;
973
+ for (const obj of event.eventPath) {
974
+ if (!event.propagationStopped) {
975
+ invokeEventListeners(event, obj);
976
+ }
977
+ }
978
+ }
979
+ event.dispatched = false;
980
+ event.eventPhase = event.NONE;
981
+ event.currentTarget = null;
982
+ if (event.canceled) {
983
+ return false;
984
+ }
985
+ return true;
986
+ }
987
+ };
988
+ var FakeEventTarget_default = FakeEventTarget;
989
+
990
+ // ../../node_modules/fake-indexeddb/build/esm/FDBRequest.js
991
+ var FDBRequest = class extends FakeEventTarget_default {
992
+ _result = null;
993
+ _error = null;
994
+ source = null;
995
+ transaction = null;
996
+ readyState = "pending";
997
+ onsuccess = null;
998
+ onerror = null;
999
+ get error() {
1000
+ if (this.readyState === "pending") {
1001
+ throw new InvalidStateError();
1002
+ }
1003
+ return this._error;
1004
+ }
1005
+ set error(value) {
1006
+ this._error = value;
1007
+ }
1008
+ get result() {
1009
+ if (this.readyState === "pending") {
1010
+ throw new InvalidStateError();
1011
+ }
1012
+ return this._result;
1013
+ }
1014
+ set result(value) {
1015
+ this._result = value;
1016
+ }
1017
+ get [Symbol.toStringTag]() {
1018
+ return "IDBRequest";
1019
+ }
1020
+ };
1021
+ var FDBRequest_default = FDBRequest;
1022
+
1023
+ // ../../node_modules/fake-indexeddb/build/esm/lib/FakeDOMStringList.js
1024
+ var FakeDOMStringList = class {
1025
+ constructor(...values) {
1026
+ this._values = values;
1027
+ for (let i = 0; i < values.length; i++) {
1028
+ this[i] = values[i];
1029
+ }
1030
+ }
1031
+ contains(value) {
1032
+ return this._values.includes(value);
1033
+ }
1034
+ item(i) {
1035
+ if (i < 0 || i >= this._values.length) {
1036
+ return null;
1037
+ }
1038
+ return this._values[i];
1039
+ }
1040
+ get length() {
1041
+ return this._values.length;
1042
+ }
1043
+ [Symbol.iterator]() {
1044
+ return this._values[Symbol.iterator]();
1045
+ }
1046
+ // Handled by proxy
1047
+ // Used internally, should not be used by others. I could maybe get rid of these and replace rather than mutate, but too lazy to check the spec.
1048
+ _push(...values) {
1049
+ for (let i = 0; i < values.length; i++) {
1050
+ this[this._values.length + i] = values[i];
1051
+ }
1052
+ this._values.push(...values);
1053
+ }
1054
+ _sort(...values) {
1055
+ this._values.sort(...values);
1056
+ for (let i = 0; i < this._values.length; i++) {
1057
+ this[i] = this._values[i];
1058
+ }
1059
+ return this;
1060
+ }
1061
+ };
1062
+ var FakeDOMStringList_default = FakeDOMStringList;
1063
+
1064
+ // ../../node_modules/fake-indexeddb/build/esm/lib/valueToKeyRange.js
1065
+ var valueToKeyRange = (value, nullDisallowedFlag = false) => {
1066
+ if (value instanceof FDBKeyRange_default) {
1067
+ return value;
1068
+ }
1069
+ if (value === null || value === void 0) {
1070
+ if (nullDisallowedFlag) {
1071
+ throw new DataError();
1072
+ }
1073
+ return new FDBKeyRange_default(void 0, void 0, false, false);
1074
+ }
1075
+ const key = valueToKey_default(value);
1076
+ return FDBKeyRange_default.only(key);
1077
+ };
1078
+ var valueToKeyRange_default = valueToKeyRange;
1079
+
1080
+ // ../../node_modules/fake-indexeddb/build/esm/lib/getKeyPath.js
1081
+ var convertKey = (key) => typeof key === "object" && key ? key + "" : key;
1082
+ function getKeyPath(keyPath) {
1083
+ return Array.isArray(keyPath) ? keyPath.map(convertKey) : convertKey(keyPath);
1084
+ }
1085
+
1086
+ // ../../node_modules/fake-indexeddb/build/esm/lib/isPotentiallyValidKeyRange.js
1087
+ var isPotentiallyValidKeyRange = (value) => {
1088
+ if (value instanceof FDBKeyRange_default) {
1089
+ return true;
1090
+ }
1091
+ const key = valueToKeyWithoutThrowing_default(value);
1092
+ return key !== INVALID_TYPE;
1093
+ };
1094
+ var isPotentiallyValidKeyRange_default = isPotentiallyValidKeyRange;
1095
+
1096
+ // ../../node_modules/fake-indexeddb/build/esm/lib/enforceRange.js
1097
+ var enforceRange = (num, type) => {
1098
+ const min = 0;
1099
+ const max = type === "unsigned long" ? 4294967295 : 9007199254740991;
1100
+ if (isNaN(num) || num < min || num > max) {
1101
+ throw new TypeError();
1102
+ }
1103
+ if (num >= 0) {
1104
+ return Math.floor(num);
1105
+ }
1106
+ };
1107
+ var enforceRange_default = enforceRange;
1108
+
1109
+ // ../../node_modules/fake-indexeddb/build/esm/lib/extractGetAllOptions.js
1110
+ var extractGetAllOptions = (queryOrOptions, count, numArguments) => {
1111
+ let query;
1112
+ let direction;
1113
+ if (queryOrOptions === void 0 || queryOrOptions === null || isPotentiallyValidKeyRange_default(queryOrOptions)) {
1114
+ query = queryOrOptions;
1115
+ if (numArguments > 1 && count !== void 0) {
1116
+ count = enforceRange_default(count, "unsigned long");
1117
+ }
1118
+ } else {
1119
+ const getAllOptions = queryOrOptions;
1120
+ if (getAllOptions.query !== void 0) {
1121
+ query = getAllOptions.query;
1122
+ }
1123
+ if (getAllOptions.count !== void 0) {
1124
+ count = enforceRange_default(getAllOptions.count, "unsigned long");
1125
+ }
1126
+ if (getAllOptions.direction !== void 0) {
1127
+ direction = getAllOptions.direction;
1128
+ }
1129
+ }
1130
+ return {
1131
+ query,
1132
+ count,
1133
+ direction
1134
+ };
1135
+ };
1136
+ var extractGetAllOptions_default = extractGetAllOptions;
1137
+
1138
+ // ../../node_modules/fake-indexeddb/build/esm/FDBIndex.js
1139
+ var confirmActiveTransaction = (index) => {
1140
+ if (index._rawIndex.deleted || index.objectStore._rawObjectStore.deleted) {
1141
+ throw new InvalidStateError();
1142
+ }
1143
+ if (index.objectStore.transaction._state !== "active") {
1144
+ throw new TransactionInactiveError();
1145
+ }
1146
+ };
1147
+ var FDBIndex = class {
1148
+ constructor(objectStore, rawIndex) {
1149
+ this._rawIndex = rawIndex;
1150
+ this._name = rawIndex.name;
1151
+ this.objectStore = objectStore;
1152
+ this.keyPath = getKeyPath(rawIndex.keyPath);
1153
+ this.multiEntry = rawIndex.multiEntry;
1154
+ this.unique = rawIndex.unique;
1155
+ }
1156
+ get name() {
1157
+ return this._name;
1158
+ }
1159
+ // https://w3c.github.io/IndexedDB/#dom-idbindex-name
1160
+ set name(name) {
1161
+ const transaction = this.objectStore.transaction;
1162
+ if (!transaction.db._runningVersionchangeTransaction) {
1163
+ throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError();
1164
+ }
1165
+ if (transaction._state !== "active") {
1166
+ throw new TransactionInactiveError();
1167
+ }
1168
+ if (this._rawIndex.deleted || this.objectStore._rawObjectStore.deleted) {
1169
+ throw new InvalidStateError();
1170
+ }
1171
+ name = String(name);
1172
+ if (name === this._name) {
1173
+ return;
1174
+ }
1175
+ if (this.objectStore.indexNames.contains(name)) {
1176
+ throw new ConstraintError();
1177
+ }
1178
+ const oldName = this._name;
1179
+ const oldIndexNames = [...this.objectStore.indexNames];
1180
+ this._name = name;
1181
+ this._rawIndex.name = name;
1182
+ this.objectStore._indexesCache.delete(oldName);
1183
+ this.objectStore._indexesCache.set(name, this);
1184
+ this.objectStore._rawObjectStore.rawIndexes.delete(oldName);
1185
+ this.objectStore._rawObjectStore.rawIndexes.set(name, this._rawIndex);
1186
+ this.objectStore.indexNames = new FakeDOMStringList_default(...Array.from(this.objectStore._rawObjectStore.rawIndexes.keys()).filter((indexName) => {
1187
+ const index = this.objectStore._rawObjectStore.rawIndexes.get(indexName);
1188
+ return index && !index.deleted;
1189
+ }).sort());
1190
+ if (!this.objectStore.transaction._createdIndexes.has(this._rawIndex)) {
1191
+ transaction._rollbackLog.push(() => {
1192
+ this._name = oldName;
1193
+ this._rawIndex.name = oldName;
1194
+ this.objectStore._indexesCache.delete(name);
1195
+ this.objectStore._indexesCache.set(oldName, this);
1196
+ this.objectStore._rawObjectStore.rawIndexes.delete(name);
1197
+ this.objectStore._rawObjectStore.rawIndexes.set(oldName, this._rawIndex);
1198
+ this.objectStore.indexNames = new FakeDOMStringList_default(...oldIndexNames);
1199
+ });
1200
+ }
1201
+ }
1202
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openCursor-IDBRequest-any-range-IDBCursorDirection-direction
1203
+ openCursor(range, direction) {
1204
+ confirmActiveTransaction(this);
1205
+ if (range === null) {
1206
+ range = void 0;
1207
+ }
1208
+ if (range !== void 0 && !(range instanceof FDBKeyRange_default)) {
1209
+ range = FDBKeyRange_default.only(valueToKey_default(range));
1210
+ }
1211
+ const request = new FDBRequest_default();
1212
+ request.source = this;
1213
+ request.transaction = this.objectStore.transaction;
1214
+ const cursor = new FDBCursorWithValue_default(this, range, direction, request);
1215
+ return this.objectStore.transaction._execRequestAsync({
1216
+ operation: cursor._iterate.bind(cursor),
1217
+ request,
1218
+ source: this
1219
+ });
1220
+ }
1221
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-openKeyCursor-IDBRequest-any-range-IDBCursorDirection-direction
1222
+ openKeyCursor(range, direction) {
1223
+ confirmActiveTransaction(this);
1224
+ if (range === null) {
1225
+ range = void 0;
1226
+ }
1227
+ if (range !== void 0 && !(range instanceof FDBKeyRange_default)) {
1228
+ range = FDBKeyRange_default.only(valueToKey_default(range));
1229
+ }
1230
+ const request = new FDBRequest_default();
1231
+ request.source = this;
1232
+ request.transaction = this.objectStore.transaction;
1233
+ const cursor = new FDBCursor_default(this, range, direction, request, true);
1234
+ return this.objectStore.transaction._execRequestAsync({
1235
+ operation: cursor._iterate.bind(cursor),
1236
+ request,
1237
+ source: this
1238
+ });
1239
+ }
1240
+ get(key) {
1241
+ confirmActiveTransaction(this);
1242
+ if (!(key instanceof FDBKeyRange_default)) {
1243
+ key = valueToKey_default(key);
1244
+ }
1245
+ return this.objectStore.transaction._execRequestAsync({
1246
+ operation: this._rawIndex.getValue.bind(this._rawIndex, key),
1247
+ source: this
1248
+ });
1249
+ }
1250
+ // http://w3c.github.io/IndexedDB/#dom-idbindex-getall
1251
+ getAll(queryOrOptions, count) {
1252
+ const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length);
1253
+ confirmActiveTransaction(this);
1254
+ const range = valueToKeyRange_default(options.query);
1255
+ return this.objectStore.transaction._execRequestAsync({
1256
+ operation: this._rawIndex.getAllValues.bind(this._rawIndex, range, options.count, options.direction),
1257
+ source: this
1258
+ });
1259
+ }
1260
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-getKey-IDBRequest-any-key
1261
+ getKey(key) {
1262
+ confirmActiveTransaction(this);
1263
+ if (!(key instanceof FDBKeyRange_default)) {
1264
+ key = valueToKey_default(key);
1265
+ }
1266
+ return this.objectStore.transaction._execRequestAsync({
1267
+ operation: this._rawIndex.getKey.bind(this._rawIndex, key),
1268
+ source: this
1269
+ });
1270
+ }
1271
+ // http://w3c.github.io/IndexedDB/#dom-idbindex-getallkeys
1272
+ getAllKeys(queryOrOptions, count) {
1273
+ const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length);
1274
+ confirmActiveTransaction(this);
1275
+ const range = valueToKeyRange_default(options.query);
1276
+ return this.objectStore.transaction._execRequestAsync({
1277
+ operation: this._rawIndex.getAllKeys.bind(this._rawIndex, range, options.count, options.direction),
1278
+ source: this
1279
+ });
1280
+ }
1281
+ // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords
1282
+ getAllRecords(options) {
1283
+ let query;
1284
+ let count;
1285
+ let direction;
1286
+ if (options !== void 0) {
1287
+ if (options.query !== void 0) {
1288
+ query = options.query;
1289
+ }
1290
+ if (options.count !== void 0) {
1291
+ count = enforceRange_default(options.count, "unsigned long");
1292
+ }
1293
+ if (options.direction !== void 0) {
1294
+ direction = options.direction;
1295
+ }
1296
+ }
1297
+ confirmActiveTransaction(this);
1298
+ const range = valueToKeyRange_default(query);
1299
+ return this.objectStore.transaction._execRequestAsync({
1300
+ operation: this._rawIndex.getAllRecords.bind(this._rawIndex, range, count, direction),
1301
+ source: this
1302
+ });
1303
+ }
1304
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBIndex-count-IDBRequest-any-key
1305
+ count(key) {
1306
+ confirmActiveTransaction(this);
1307
+ if (key === null) {
1308
+ key = void 0;
1309
+ }
1310
+ if (key !== void 0 && !(key instanceof FDBKeyRange_default)) {
1311
+ key = FDBKeyRange_default.only(valueToKey_default(key));
1312
+ }
1313
+ return this.objectStore.transaction._execRequestAsync({
1314
+ operation: () => {
1315
+ return this._rawIndex.count(key);
1316
+ },
1317
+ source: this
1318
+ });
1319
+ }
1320
+ get [Symbol.toStringTag]() {
1321
+ return "IDBIndex";
1322
+ }
1323
+ };
1324
+ var FDBIndex_default = FDBIndex;
1325
+
1326
+ // ../../node_modules/fake-indexeddb/build/esm/lib/canInjectKey.js
1327
+ var canInjectKey = (keyPath, value) => {
1328
+ if (Array.isArray(keyPath)) {
1329
+ throw new Error("The key paths used in this section are always strings and never sequences, since it is not possible to create a object store which has a key generator and also has a key path that is a sequence.");
1330
+ }
1331
+ const identifiers = keyPath.split(".");
1332
+ if (identifiers.length === 0) {
1333
+ throw new Error("Assert: identifiers is not empty");
1334
+ }
1335
+ identifiers.pop();
1336
+ for (const identifier of identifiers) {
1337
+ if (typeof value !== "object" && !Array.isArray(value)) {
1338
+ return false;
1339
+ }
1340
+ const hop = Object.hasOwn(value, identifier);
1341
+ if (!hop) {
1342
+ return true;
1343
+ }
1344
+ value = value[identifier];
1345
+ }
1346
+ return typeof value === "object" || Array.isArray(value);
1347
+ };
1348
+ var canInjectKey_default = canInjectKey;
1349
+
1350
+ // ../../node_modules/fake-indexeddb/build/esm/FDBRecord.js
1351
+ var FDBRecord = class {
1352
+ constructor(key, primaryKey, value) {
1353
+ this._key = key;
1354
+ this._primaryKey = primaryKey;
1355
+ this._value = value;
1356
+ }
1357
+ get key() {
1358
+ return this._key;
1359
+ }
1360
+ set key(_) {
1361
+ }
1362
+ get primaryKey() {
1363
+ return this._primaryKey;
1364
+ }
1365
+ set primaryKey(_) {
1366
+ }
1367
+ get value() {
1368
+ return this._value;
1369
+ }
1370
+ set value(_) {
1371
+ }
1372
+ get [Symbol.toStringTag]() {
1373
+ return "IDBRecord";
1374
+ }
1375
+ };
1376
+ var FDBRecord_default = FDBRecord;
1377
+
1378
+ // ../../node_modules/fake-indexeddb/build/esm/lib/binarySearchTree.js
1379
+ var MAX_TOMBSTONE_FACTOR = 2 / 3;
1380
+ var EVERYTHING_KEY_RANGE = new FDBKeyRange_default(void 0, void 0, false, false);
1381
+ var BinarySearchTree = class {
1382
+ _numTombstones = 0;
1383
+ _numNodes = 0;
1384
+ /**
1385
+ *
1386
+ * @param keysAreUnique - whether keys can be unique, and thus whether we cn skip checking `record.value` when
1387
+ * comparing. This is basically used to distinguish ObjectStores (where the value is the entire object, not used
1388
+ * as a key) from non-unique Indexes (where both the key and the value are meaningful keys used for sorting)
1389
+ */
1390
+ constructor(keysAreUnique) {
1391
+ this._keysAreUnique = !!keysAreUnique;
1392
+ }
1393
+ size() {
1394
+ return this._numNodes - this._numTombstones;
1395
+ }
1396
+ get(record) {
1397
+ return this._getByComparator(this._root, (otherRecord) => this._compare(record, otherRecord));
1398
+ }
1399
+ contains(record) {
1400
+ return !!this.get(record);
1401
+ }
1402
+ _compare(a, b) {
1403
+ const keyComparison = cmp_default(a.key, b.key);
1404
+ if (keyComparison !== 0) {
1405
+ return keyComparison;
1406
+ }
1407
+ return this._keysAreUnique ? 0 : cmp_default(a.value, b.value);
1408
+ }
1409
+ _getByComparator(node, comparator) {
1410
+ let current = node;
1411
+ while (current) {
1412
+ const comparison = comparator(current.record);
1413
+ if (comparison < 0) {
1414
+ current = current.left;
1415
+ } else if (comparison > 0) {
1416
+ current = current.right;
1417
+ } else {
1418
+ return current.record;
1419
+ }
1420
+ }
1421
+ }
1422
+ /**
1423
+ * Put a new record, and return the overwritten record if an overwrite occurred.
1424
+ * @param record
1425
+ * @param noOverwrite - throw a ConstraintError in case of overwrite
1426
+ */
1427
+ put(record, noOverwrite = false) {
1428
+ if (!this._root) {
1429
+ this._root = {
1430
+ record,
1431
+ left: void 0,
1432
+ right: void 0,
1433
+ parent: void 0,
1434
+ deleted: false,
1435
+ // the root is always black in a red-black tree
1436
+ red: false
1437
+ };
1438
+ this._numNodes++;
1439
+ return;
1440
+ }
1441
+ return this._put(this._root, record, noOverwrite);
1442
+ }
1443
+ _put(node, record, noOverwrite) {
1444
+ const comparison = this._compare(record, node.record);
1445
+ if (comparison < 0) {
1446
+ if (node.left) {
1447
+ return this._put(node.left, record, noOverwrite);
1448
+ } else {
1449
+ node.left = {
1450
+ record,
1451
+ left: void 0,
1452
+ right: void 0,
1453
+ parent: node,
1454
+ deleted: false,
1455
+ red: true
1456
+ };
1457
+ this._onNewNodeInserted(node.left);
1458
+ }
1459
+ } else if (comparison > 0) {
1460
+ if (node.right) {
1461
+ return this._put(node.right, record, noOverwrite);
1462
+ } else {
1463
+ node.right = {
1464
+ record,
1465
+ left: void 0,
1466
+ right: void 0,
1467
+ parent: node,
1468
+ deleted: false,
1469
+ red: true
1470
+ };
1471
+ this._onNewNodeInserted(node.right);
1472
+ }
1473
+ } else if (node.deleted) {
1474
+ node.deleted = false;
1475
+ node.record = record;
1476
+ this._numTombstones--;
1477
+ } else if (noOverwrite) {
1478
+ throw new ConstraintError();
1479
+ } else {
1480
+ const overwrittenRecord = node.record;
1481
+ node.record = record;
1482
+ return overwrittenRecord;
1483
+ }
1484
+ }
1485
+ delete(record) {
1486
+ if (!this._root) {
1487
+ return;
1488
+ }
1489
+ this._delete(this._root, record);
1490
+ if (this._numTombstones > this._numNodes * MAX_TOMBSTONE_FACTOR) {
1491
+ const records = [...this.getAllRecords()];
1492
+ this._root = this._rebuild(records, void 0, false);
1493
+ this._numNodes = records.length;
1494
+ this._numTombstones = 0;
1495
+ }
1496
+ }
1497
+ _delete(node, record) {
1498
+ if (!node) {
1499
+ return;
1500
+ }
1501
+ const comparison = this._compare(record, node.record);
1502
+ if (comparison < 0) {
1503
+ this._delete(node.left, record);
1504
+ } else if (comparison > 0) {
1505
+ this._delete(node.right, record);
1506
+ } else if (!node.deleted) {
1507
+ this._numTombstones++;
1508
+ node.deleted = true;
1509
+ }
1510
+ }
1511
+ *getAllRecords(descending = false) {
1512
+ yield* this.getRecords(EVERYTHING_KEY_RANGE, descending);
1513
+ }
1514
+ *getRecords(keyRange, descending = false) {
1515
+ yield* this._getRecordsForNode(this._root, keyRange, descending);
1516
+ }
1517
+ *_getRecordsForNode(node, keyRange, descending = false) {
1518
+ if (!node) {
1519
+ return;
1520
+ }
1521
+ yield* this._findRecords(node, keyRange, descending);
1522
+ }
1523
+ *_findRecords(node, keyRange, descending = false) {
1524
+ const {
1525
+ lower,
1526
+ upper,
1527
+ lowerOpen,
1528
+ upperOpen
1529
+ } = keyRange;
1530
+ const {
1531
+ record: {
1532
+ key
1533
+ }
1534
+ } = node;
1535
+ const lowerComparison = lower === void 0 ? -1 : cmp_default(lower, key);
1536
+ const upperComparison = upper === void 0 ? 1 : cmp_default(upper, key);
1537
+ const moreLeft = this._keysAreUnique ? lowerComparison < 0 : lowerComparison <= 0;
1538
+ const moreRight = this._keysAreUnique ? upperComparison > 0 : upperComparison >= 0;
1539
+ const moreStart = descending ? moreRight : moreLeft;
1540
+ const moreEnd = descending ? moreLeft : moreRight;
1541
+ const start = descending ? "right" : "left";
1542
+ const end = descending ? "left" : "right";
1543
+ const lowerMatches = lowerOpen ? lowerComparison < 0 : lowerComparison <= 0;
1544
+ const upperMatches = upperOpen ? upperComparison > 0 : upperComparison >= 0;
1545
+ if (moreStart && node[start]) {
1546
+ yield* this._findRecords(node[start], keyRange, descending);
1547
+ }
1548
+ if (lowerMatches && upperMatches && !node.deleted) {
1549
+ yield node.record;
1550
+ }
1551
+ if (moreEnd && node[end]) {
1552
+ yield* this._findRecords(node[end], keyRange, descending);
1553
+ }
1554
+ }
1555
+ _onNewNodeInserted(newNode) {
1556
+ this._numNodes++;
1557
+ this._rebalanceTree(newNode);
1558
+ }
1559
+ // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Insertion
1560
+ _rebalanceTree(node) {
1561
+ let parent = node.parent;
1562
+ do {
1563
+ if (!parent.red) {
1564
+ return;
1565
+ }
1566
+ const grandparent = parent.parent;
1567
+ if (!grandparent) {
1568
+ parent.red = false;
1569
+ return;
1570
+ }
1571
+ const parentIsRightChild = parent === grandparent.right;
1572
+ const uncle = parentIsRightChild ? grandparent.left : grandparent.right;
1573
+ if (!uncle || !uncle.red) {
1574
+ if (node === (parentIsRightChild ? parent.left : parent.right)) {
1575
+ this._rotateSubtree(parent, parentIsRightChild);
1576
+ node = parent;
1577
+ parent = parentIsRightChild ? grandparent.right : grandparent.left;
1578
+ }
1579
+ this._rotateSubtree(grandparent, !parentIsRightChild);
1580
+ parent.red = false;
1581
+ grandparent.red = true;
1582
+ return;
1583
+ }
1584
+ parent.red = false;
1585
+ uncle.red = false;
1586
+ grandparent.red = true;
1587
+ node = grandparent;
1588
+ } while (node.parent ? parent = node.parent : false);
1589
+ }
1590
+ // based on https://en.wikipedia.org/wiki/Red%E2%80%93black_tree#Implementation
1591
+ _rotateSubtree(node, right) {
1592
+ const parent = node.parent;
1593
+ const newRoot = right ? node.left : node.right;
1594
+ const newChild = right ? newRoot.right : newRoot.left;
1595
+ node[right ? "left" : "right"] = newChild;
1596
+ if (newChild) {
1597
+ newChild.parent = node;
1598
+ }
1599
+ newRoot[right ? "right" : "left"] = node;
1600
+ newRoot.parent = parent;
1601
+ node.parent = newRoot;
1602
+ if (parent) {
1603
+ parent[node === parent.right ? "right" : "left"] = newRoot;
1604
+ } else {
1605
+ this._root = newRoot;
1606
+ }
1607
+ return newRoot;
1608
+ }
1609
+ // rebuild the whole tree from scratch, used to avoid too many deletion tombstones accumulating
1610
+ _rebuild(records, parent, red) {
1611
+ const {
1612
+ length
1613
+ } = records;
1614
+ if (!length) {
1615
+ return void 0;
1616
+ }
1617
+ const mid = length >>> 1;
1618
+ const node = {
1619
+ record: records[mid],
1620
+ left: void 0,
1621
+ right: void 0,
1622
+ parent,
1623
+ deleted: false,
1624
+ red
1625
+ };
1626
+ const left = this._rebuild(records.slice(0, mid), node, !red);
1627
+ const right = this._rebuild(records.slice(mid + 1), node, !red);
1628
+ node.left = left;
1629
+ node.right = right;
1630
+ return node;
1631
+ }
1632
+ };
1633
+
1634
+ // ../../node_modules/fake-indexeddb/build/esm/lib/RecordStore.js
1635
+ var RecordStore = class {
1636
+ constructor(keysAreUnique) {
1637
+ this.keysAreUnique = keysAreUnique;
1638
+ this.records = new BinarySearchTree(this.keysAreUnique);
1639
+ }
1640
+ get(key) {
1641
+ const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key);
1642
+ return this.records.getRecords(range).next().value;
1643
+ }
1644
+ /**
1645
+ * Put a new record, and return the overwritten record if an overwrite occurred.
1646
+ * @param newRecord
1647
+ * @param noOverwrite - throw a ConstraintError in case of overwrite
1648
+ */
1649
+ put(newRecord, noOverwrite = false) {
1650
+ return this.records.put(newRecord, noOverwrite);
1651
+ }
1652
+ delete(key) {
1653
+ const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key);
1654
+ const deletedRecords = [...this.records.getRecords(range)];
1655
+ for (const record of deletedRecords) {
1656
+ this.records.delete(record);
1657
+ }
1658
+ return deletedRecords;
1659
+ }
1660
+ deleteByValue(key) {
1661
+ const range = key instanceof FDBKeyRange_default ? key : FDBKeyRange_default.only(key);
1662
+ const deletedRecords = [];
1663
+ for (const record of this.records.getAllRecords()) {
1664
+ if (range.includes(record.value)) {
1665
+ this.records.delete(record);
1666
+ deletedRecords.push(record);
1667
+ }
1668
+ }
1669
+ return deletedRecords;
1670
+ }
1671
+ clear() {
1672
+ const deletedRecords = [...this.records.getAllRecords()];
1673
+ this.records = new BinarySearchTree(this.keysAreUnique);
1674
+ return deletedRecords;
1675
+ }
1676
+ values(range, direction = "next") {
1677
+ const descending = direction === "prev" || direction === "prevunique";
1678
+ const records = range ? this.records.getRecords(range, descending) : this.records.getAllRecords(descending);
1679
+ return {
1680
+ [Symbol.iterator]: () => {
1681
+ const next = () => {
1682
+ return records.next();
1683
+ };
1684
+ if (direction === "next" || direction === "prev") {
1685
+ return {
1686
+ next
1687
+ };
1688
+ }
1689
+ if (direction === "nextunique") {
1690
+ let previousValue = void 0;
1691
+ return {
1692
+ next: () => {
1693
+ let current2 = next();
1694
+ while (!current2.done && previousValue !== void 0 && cmp_default(previousValue.key, current2.value.key) === 0) {
1695
+ current2 = next();
1696
+ }
1697
+ previousValue = current2.value;
1698
+ return current2;
1699
+ }
1700
+ };
1701
+ }
1702
+ let current = next();
1703
+ let nextResult = next();
1704
+ return {
1705
+ next: () => {
1706
+ while (!nextResult.done && cmp_default(current.value.key, nextResult.value.key) === 0) {
1707
+ current = nextResult;
1708
+ nextResult = next();
1709
+ }
1710
+ const result = current;
1711
+ current = nextResult;
1712
+ nextResult = next();
1713
+ return result;
1714
+ }
1715
+ };
1716
+ }
1717
+ };
1718
+ }
1719
+ size() {
1720
+ return this.records.size();
1721
+ }
1722
+ };
1723
+ var RecordStore_default = RecordStore;
1724
+
1725
+ // ../../node_modules/fake-indexeddb/build/esm/lib/Index.js
1726
+ var Index = class {
1727
+ deleted = false;
1728
+ // Initialized should be used to decide whether to throw an error or abort the versionchange transaction when there is a
1729
+ // constraint
1730
+ initialized = false;
1731
+ constructor(rawObjectStore, name, keyPath, multiEntry, unique) {
1732
+ this.rawObjectStore = rawObjectStore;
1733
+ this.name = name;
1734
+ this.keyPath = keyPath;
1735
+ this.multiEntry = multiEntry;
1736
+ this.unique = unique;
1737
+ this.records = new RecordStore_default(unique);
1738
+ }
1739
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-index
1740
+ getKey(key) {
1741
+ const record = this.records.get(key);
1742
+ return record !== void 0 ? record.value : void 0;
1743
+ }
1744
+ // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index
1745
+ getAllKeys(range, count, direction) {
1746
+ if (count === void 0 || count === 0) {
1747
+ count = Infinity;
1748
+ }
1749
+ const records = [];
1750
+ for (const record of this.records.values(range, direction)) {
1751
+ records.push(structuredClone(record.value));
1752
+ if (records.length >= count) {
1753
+ break;
1754
+ }
1755
+ }
1756
+ return records;
1757
+ }
1758
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#index-referenced-value-retrieval-operation
1759
+ getValue(key) {
1760
+ const record = this.records.get(key);
1761
+ return record !== void 0 ? this.rawObjectStore.getValue(record.value) : void 0;
1762
+ }
1763
+ // http://w3c.github.io/IndexedDB/#retrieve-multiple-referenced-values-from-an-index
1764
+ getAllValues(range, count, direction) {
1765
+ if (count === void 0 || count === 0) {
1766
+ count = Infinity;
1767
+ }
1768
+ const records = [];
1769
+ for (const record of this.records.values(range, direction)) {
1770
+ records.push(this.rawObjectStore.getValue(record.value));
1771
+ if (records.length >= count) {
1772
+ break;
1773
+ }
1774
+ }
1775
+ return records;
1776
+ }
1777
+ // https://www.w3.org/TR/IndexedDB/#dom-idbindex-getallrecords
1778
+ getAllRecords(range, count, direction) {
1779
+ if (count === void 0 || count === 0) {
1780
+ count = Infinity;
1781
+ }
1782
+ const records = [];
1783
+ for (const record of this.records.values(range, direction)) {
1784
+ records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(this.rawObjectStore.getKey(record.value)), this.rawObjectStore.getValue(record.value)));
1785
+ if (records.length >= count) {
1786
+ break;
1787
+ }
1788
+ }
1789
+ return records;
1790
+ }
1791
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store (step 7)
1792
+ storeRecord(newRecord) {
1793
+ let indexKey;
1794
+ try {
1795
+ indexKey = extractKey_default(this.keyPath, newRecord.value).key;
1796
+ } catch (err) {
1797
+ if (err.name === "DataError") {
1798
+ return;
1799
+ }
1800
+ throw err;
1801
+ }
1802
+ if (!this.multiEntry || !Array.isArray(indexKey)) {
1803
+ try {
1804
+ valueToKey_default(indexKey);
1805
+ } catch (e) {
1806
+ return;
1807
+ }
1808
+ } else {
1809
+ const keep = [];
1810
+ for (const part of indexKey) {
1811
+ if (keep.indexOf(part) < 0) {
1812
+ try {
1813
+ keep.push(valueToKey_default(part));
1814
+ } catch (err) {
1815
+ }
1816
+ }
1817
+ }
1818
+ indexKey = keep;
1819
+ }
1820
+ if (!this.multiEntry || !Array.isArray(indexKey)) {
1821
+ if (this.unique) {
1822
+ const existingRecord = this.records.get(indexKey);
1823
+ if (existingRecord) {
1824
+ throw new ConstraintError();
1825
+ }
1826
+ }
1827
+ } else {
1828
+ if (this.unique) {
1829
+ for (const individualIndexKey of indexKey) {
1830
+ const existingRecord = this.records.get(individualIndexKey);
1831
+ if (existingRecord) {
1832
+ throw new ConstraintError();
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1837
+ if (!this.multiEntry || !Array.isArray(indexKey)) {
1838
+ this.records.put({
1839
+ key: indexKey,
1840
+ value: newRecord.key
1841
+ });
1842
+ } else {
1843
+ for (const individualIndexKey of indexKey) {
1844
+ this.records.put({
1845
+ key: individualIndexKey,
1846
+ value: newRecord.key
1847
+ });
1848
+ }
1849
+ }
1850
+ }
1851
+ initialize(transaction) {
1852
+ if (this.initialized) {
1853
+ throw new Error("Index already initialized");
1854
+ }
1855
+ transaction._execRequestAsync({
1856
+ operation: () => {
1857
+ try {
1858
+ for (const record of this.rawObjectStore.records.values()) {
1859
+ this.storeRecord(record);
1860
+ }
1861
+ this.initialized = true;
1862
+ } catch (err) {
1863
+ transaction._abort(err.name);
1864
+ }
1865
+ },
1866
+ source: null
1867
+ });
1868
+ }
1869
+ count(range) {
1870
+ let count = 0;
1871
+ for (const record of this.records.values(range)) {
1872
+ count += 1;
1873
+ }
1874
+ return count;
1875
+ }
1876
+ };
1877
+ var Index_default = Index;
1878
+
1879
+ // ../../node_modules/fake-indexeddb/build/esm/lib/validateKeyPath.js
1880
+ var validateKeyPath = (keyPath, parent) => {
1881
+ if (keyPath !== void 0 && keyPath !== null && typeof keyPath !== "string" && keyPath.toString && (parent === "array" || !Array.isArray(keyPath))) {
1882
+ keyPath = keyPath.toString();
1883
+ }
1884
+ if (typeof keyPath === "string") {
1885
+ if (keyPath === "" && parent !== "string") {
1886
+ return;
1887
+ }
1888
+ try {
1889
+ const validIdentifierRegex = (
1890
+ // eslint-disable-next-line no-misleading-character-class
1891
+ /^(?:[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC])(?:[$0-9A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC])*$/
1892
+ );
1893
+ if (keyPath.length >= 1 && validIdentifierRegex.test(keyPath)) {
1894
+ return;
1895
+ }
1896
+ } catch (err) {
1897
+ throw new SyntaxError(err.message);
1898
+ }
1899
+ if (keyPath.indexOf(" ") >= 0) {
1900
+ throw new SyntaxError("The keypath argument contains an invalid key path (no spaces allowed).");
1901
+ }
1902
+ }
1903
+ if (Array.isArray(keyPath) && keyPath.length > 0) {
1904
+ if (parent) {
1905
+ throw new SyntaxError("The keypath argument contains an invalid key path (nested arrays).");
1906
+ }
1907
+ for (const part of keyPath) {
1908
+ validateKeyPath(part, "array");
1909
+ }
1910
+ return;
1911
+ } else if (typeof keyPath === "string" && keyPath.indexOf(".") >= 0) {
1912
+ keyPath = keyPath.split(".");
1913
+ for (const part of keyPath) {
1914
+ validateKeyPath(part, "string");
1915
+ }
1916
+ return;
1917
+ }
1918
+ throw new SyntaxError();
1919
+ };
1920
+ var validateKeyPath_default = validateKeyPath;
1921
+
1922
+ // ../../node_modules/fake-indexeddb/build/esm/FDBObjectStore.js
1923
+ var confirmActiveTransaction2 = (objectStore) => {
1924
+ if (objectStore._rawObjectStore.deleted) {
1925
+ throw new InvalidStateError();
1926
+ }
1927
+ if (objectStore.transaction._state !== "active") {
1928
+ throw new TransactionInactiveError();
1929
+ }
1930
+ };
1931
+ var buildRecordAddPut = (objectStore, value, key) => {
1932
+ confirmActiveTransaction2(objectStore);
1933
+ if (objectStore.transaction.mode === "readonly") {
1934
+ throw new ReadOnlyError();
1935
+ }
1936
+ if (objectStore.keyPath !== null) {
1937
+ if (key !== void 0) {
1938
+ throw new DataError();
1939
+ }
1940
+ }
1941
+ const clone = cloneValueForInsertion(value, objectStore.transaction);
1942
+ if (objectStore.keyPath !== null) {
1943
+ const tempKey = extractKey_default(objectStore.keyPath, clone);
1944
+ if (tempKey.type === "found") {
1945
+ valueToKey_default(tempKey.key);
1946
+ } else {
1947
+ if (!objectStore._rawObjectStore.keyGenerator) {
1948
+ throw new DataError();
1949
+ } else if (!canInjectKey_default(objectStore.keyPath, clone)) {
1950
+ throw new DataError();
1951
+ }
1952
+ }
1953
+ }
1954
+ if (objectStore.keyPath === null && objectStore._rawObjectStore.keyGenerator === null && key === void 0) {
1955
+ throw new DataError();
1956
+ }
1957
+ if (key !== void 0) {
1958
+ key = valueToKey_default(key);
1959
+ }
1960
+ return {
1961
+ key,
1962
+ value: clone
1963
+ };
1964
+ };
1965
+ var FDBObjectStore = class {
1966
+ _indexesCache = /* @__PURE__ */ new Map();
1967
+ constructor(transaction, rawObjectStore) {
1968
+ this._rawObjectStore = rawObjectStore;
1969
+ this._name = rawObjectStore.name;
1970
+ this.keyPath = getKeyPath(rawObjectStore.keyPath);
1971
+ this.autoIncrement = rawObjectStore.autoIncrement;
1972
+ this.transaction = transaction;
1973
+ this.indexNames = new FakeDOMStringList_default(...Array.from(rawObjectStore.rawIndexes.keys()).sort());
1974
+ }
1975
+ get name() {
1976
+ return this._name;
1977
+ }
1978
+ // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-name
1979
+ set name(name) {
1980
+ const transaction = this.transaction;
1981
+ if (!transaction.db._runningVersionchangeTransaction) {
1982
+ throw transaction._state === "active" ? new InvalidStateError() : new TransactionInactiveError();
1983
+ }
1984
+ confirmActiveTransaction2(this);
1985
+ name = String(name);
1986
+ if (name === this._name) {
1987
+ return;
1988
+ }
1989
+ if (this._rawObjectStore.rawDatabase.rawObjectStores.has(name)) {
1990
+ throw new ConstraintError();
1991
+ }
1992
+ const oldName = this._name;
1993
+ const oldObjectStoreNames = [...transaction.db.objectStoreNames];
1994
+ this._name = name;
1995
+ this._rawObjectStore.name = name;
1996
+ this.transaction._objectStoresCache.delete(oldName);
1997
+ this.transaction._objectStoresCache.set(name, this);
1998
+ this._rawObjectStore.rawDatabase.rawObjectStores.delete(oldName);
1999
+ this._rawObjectStore.rawDatabase.rawObjectStores.set(name, this._rawObjectStore);
2000
+ transaction.db.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._rawObjectStore.rawDatabase.rawObjectStores.keys()).filter((objectStoreName) => {
2001
+ const objectStore = this._rawObjectStore.rawDatabase.rawObjectStores.get(objectStoreName);
2002
+ return objectStore && !objectStore.deleted;
2003
+ }).sort());
2004
+ const oldScope = new Set(transaction._scope);
2005
+ const oldTransactionObjectStoreNames = [...transaction.objectStoreNames];
2006
+ this.transaction._scope.delete(oldName);
2007
+ transaction._scope.add(name);
2008
+ transaction.objectStoreNames = new FakeDOMStringList_default(...Array.from(transaction._scope).sort());
2009
+ if (!this.transaction._createdObjectStores.has(this._rawObjectStore)) {
2010
+ transaction._rollbackLog.push(() => {
2011
+ this._name = oldName;
2012
+ this._rawObjectStore.name = oldName;
2013
+ this.transaction._objectStoresCache.delete(name);
2014
+ this.transaction._objectStoresCache.set(oldName, this);
2015
+ this._rawObjectStore.rawDatabase.rawObjectStores.delete(name);
2016
+ this._rawObjectStore.rawDatabase.rawObjectStores.set(oldName, this._rawObjectStore);
2017
+ transaction.db.objectStoreNames = new FakeDOMStringList_default(...oldObjectStoreNames);
2018
+ transaction._scope = oldScope;
2019
+ transaction.objectStoreNames = new FakeDOMStringList_default(...oldTransactionObjectStoreNames);
2020
+ });
2021
+ }
2022
+ }
2023
+ put(value, key) {
2024
+ if (arguments.length === 0) {
2025
+ throw new TypeError();
2026
+ }
2027
+ const record = buildRecordAddPut(this, value, key);
2028
+ return this.transaction._execRequestAsync({
2029
+ operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, false, this.transaction._rollbackLog),
2030
+ source: this
2031
+ });
2032
+ }
2033
+ add(value, key) {
2034
+ if (arguments.length === 0) {
2035
+ throw new TypeError();
2036
+ }
2037
+ const record = buildRecordAddPut(this, value, key);
2038
+ return this.transaction._execRequestAsync({
2039
+ operation: this._rawObjectStore.storeRecord.bind(this._rawObjectStore, record, true, this.transaction._rollbackLog),
2040
+ source: this
2041
+ });
2042
+ }
2043
+ delete(key) {
2044
+ if (arguments.length === 0) {
2045
+ throw new TypeError();
2046
+ }
2047
+ confirmActiveTransaction2(this);
2048
+ if (this.transaction.mode === "readonly") {
2049
+ throw new ReadOnlyError();
2050
+ }
2051
+ if (!(key instanceof FDBKeyRange_default)) {
2052
+ key = valueToKey_default(key);
2053
+ }
2054
+ return this.transaction._execRequestAsync({
2055
+ operation: this._rawObjectStore.deleteRecord.bind(this._rawObjectStore, key, this.transaction._rollbackLog),
2056
+ source: this
2057
+ });
2058
+ }
2059
+ get(key) {
2060
+ if (arguments.length === 0) {
2061
+ throw new TypeError();
2062
+ }
2063
+ confirmActiveTransaction2(this);
2064
+ if (!(key instanceof FDBKeyRange_default)) {
2065
+ key = valueToKey_default(key);
2066
+ }
2067
+ return this.transaction._execRequestAsync({
2068
+ operation: this._rawObjectStore.getValue.bind(this._rawObjectStore, key),
2069
+ source: this
2070
+ });
2071
+ }
2072
+ // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getall
2073
+ getAll(queryOrOptions, count) {
2074
+ const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length);
2075
+ confirmActiveTransaction2(this);
2076
+ const range = valueToKeyRange_default(options.query);
2077
+ return this.transaction._execRequestAsync({
2078
+ operation: this._rawObjectStore.getAllValues.bind(this._rawObjectStore, range, options.count, options.direction),
2079
+ source: this
2080
+ });
2081
+ }
2082
+ // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getkey
2083
+ getKey(key) {
2084
+ if (arguments.length === 0) {
2085
+ throw new TypeError();
2086
+ }
2087
+ confirmActiveTransaction2(this);
2088
+ if (!(key instanceof FDBKeyRange_default)) {
2089
+ key = valueToKey_default(key);
2090
+ }
2091
+ return this.transaction._execRequestAsync({
2092
+ operation: this._rawObjectStore.getKey.bind(this._rawObjectStore, key),
2093
+ source: this
2094
+ });
2095
+ }
2096
+ // http://w3c.github.io/IndexedDB/#dom-idbobjectstore-getallkeys
2097
+ getAllKeys(queryOrOptions, count) {
2098
+ const options = extractGetAllOptions_default(queryOrOptions, count, arguments.length);
2099
+ confirmActiveTransaction2(this);
2100
+ const range = valueToKeyRange_default(options.query);
2101
+ return this.transaction._execRequestAsync({
2102
+ operation: this._rawObjectStore.getAllKeys.bind(this._rawObjectStore, range, options.count, options.direction),
2103
+ source: this
2104
+ });
2105
+ }
2106
+ // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords
2107
+ getAllRecords(options) {
2108
+ let query;
2109
+ let count;
2110
+ let direction;
2111
+ if (options !== void 0) {
2112
+ if (options.query !== void 0) {
2113
+ query = options.query;
2114
+ }
2115
+ if (options.count !== void 0) {
2116
+ count = enforceRange_default(options.count, "unsigned long");
2117
+ }
2118
+ if (options.direction !== void 0) {
2119
+ direction = options.direction;
2120
+ }
2121
+ }
2122
+ confirmActiveTransaction2(this);
2123
+ const range = valueToKeyRange_default(query);
2124
+ return this.transaction._execRequestAsync({
2125
+ operation: this._rawObjectStore.getAllRecords.bind(this._rawObjectStore, range, count, direction),
2126
+ source: this
2127
+ });
2128
+ }
2129
+ clear() {
2130
+ confirmActiveTransaction2(this);
2131
+ if (this.transaction.mode === "readonly") {
2132
+ throw new ReadOnlyError();
2133
+ }
2134
+ return this.transaction._execRequestAsync({
2135
+ operation: this._rawObjectStore.clear.bind(this._rawObjectStore, this.transaction._rollbackLog),
2136
+ source: this
2137
+ });
2138
+ }
2139
+ openCursor(range, direction) {
2140
+ confirmActiveTransaction2(this);
2141
+ if (range === null) {
2142
+ range = void 0;
2143
+ }
2144
+ if (range !== void 0 && !(range instanceof FDBKeyRange_default)) {
2145
+ range = FDBKeyRange_default.only(valueToKey_default(range));
2146
+ }
2147
+ const request = new FDBRequest_default();
2148
+ request.source = this;
2149
+ request.transaction = this.transaction;
2150
+ const cursor = new FDBCursorWithValue_default(this, range, direction, request);
2151
+ return this.transaction._execRequestAsync({
2152
+ operation: cursor._iterate.bind(cursor),
2153
+ request,
2154
+ source: this
2155
+ });
2156
+ }
2157
+ openKeyCursor(range, direction) {
2158
+ confirmActiveTransaction2(this);
2159
+ if (range === null) {
2160
+ range = void 0;
2161
+ }
2162
+ if (range !== void 0 && !(range instanceof FDBKeyRange_default)) {
2163
+ range = FDBKeyRange_default.only(valueToKey_default(range));
2164
+ }
2165
+ const request = new FDBRequest_default();
2166
+ request.source = this;
2167
+ request.transaction = this.transaction;
2168
+ const cursor = new FDBCursor_default(this, range, direction, request, true);
2169
+ return this.transaction._execRequestAsync({
2170
+ operation: cursor._iterate.bind(cursor),
2171
+ request,
2172
+ source: this
2173
+ });
2174
+ }
2175
+ // tslint:-next-line max-line-length
2176
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-createIndex-IDBIndex-DOMString-name-DOMString-sequence-DOMString--keyPath-IDBIndexParameters-optionalParameters
2177
+ createIndex(name, keyPath, optionalParameters = {}) {
2178
+ if (arguments.length < 2) {
2179
+ throw new TypeError();
2180
+ }
2181
+ const multiEntry = optionalParameters.multiEntry !== void 0 ? optionalParameters.multiEntry : false;
2182
+ const unique = optionalParameters.unique !== void 0 ? optionalParameters.unique : false;
2183
+ if (this.transaction.mode !== "versionchange") {
2184
+ throw new InvalidStateError();
2185
+ }
2186
+ confirmActiveTransaction2(this);
2187
+ if (this.indexNames.contains(name)) {
2188
+ throw new ConstraintError();
2189
+ }
2190
+ validateKeyPath_default(keyPath);
2191
+ if (Array.isArray(keyPath) && multiEntry) {
2192
+ throw new InvalidAccessError();
2193
+ }
2194
+ const indexNames = [...this.indexNames];
2195
+ const index = new Index_default(this._rawObjectStore, name, keyPath, multiEntry, unique);
2196
+ this.indexNames._push(name);
2197
+ this.indexNames._sort();
2198
+ this.transaction._createdIndexes.add(index);
2199
+ this._rawObjectStore.rawIndexes.set(name, index);
2200
+ index.initialize(this.transaction);
2201
+ this.transaction._rollbackLog.push(() => {
2202
+ index.deleted = true;
2203
+ this.indexNames = new FakeDOMStringList_default(...indexNames);
2204
+ this._rawObjectStore.rawIndexes.delete(index.name);
2205
+ });
2206
+ return new FDBIndex_default(this, index);
2207
+ }
2208
+ // https://w3c.github.io/IndexedDB/#dom-idbobjectstore-index
2209
+ index(name) {
2210
+ if (arguments.length === 0) {
2211
+ throw new TypeError();
2212
+ }
2213
+ if (this._rawObjectStore.deleted || this.transaction._state === "finished") {
2214
+ throw new InvalidStateError();
2215
+ }
2216
+ const index = this._indexesCache.get(name);
2217
+ if (index !== void 0) {
2218
+ return index;
2219
+ }
2220
+ const rawIndex = this._rawObjectStore.rawIndexes.get(name);
2221
+ if (!this.indexNames.contains(name) || rawIndex === void 0) {
2222
+ throw new NotFoundError();
2223
+ }
2224
+ const index2 = new FDBIndex_default(this, rawIndex);
2225
+ this._indexesCache.set(name, index2);
2226
+ return index2;
2227
+ }
2228
+ deleteIndex(name) {
2229
+ if (arguments.length === 0) {
2230
+ throw new TypeError();
2231
+ }
2232
+ if (this.transaction.mode !== "versionchange") {
2233
+ throw new InvalidStateError();
2234
+ }
2235
+ confirmActiveTransaction2(this);
2236
+ const rawIndex = this._rawObjectStore.rawIndexes.get(name);
2237
+ if (rawIndex === void 0) {
2238
+ throw new NotFoundError();
2239
+ }
2240
+ this.transaction._rollbackLog.push(() => {
2241
+ rawIndex.deleted = false;
2242
+ this._rawObjectStore.rawIndexes.set(rawIndex.name, rawIndex);
2243
+ this.indexNames._push(rawIndex.name);
2244
+ this.indexNames._sort();
2245
+ });
2246
+ this.indexNames = new FakeDOMStringList_default(...Array.from(this.indexNames).filter((indexName) => {
2247
+ return indexName !== name;
2248
+ }));
2249
+ rawIndex.deleted = true;
2250
+ this.transaction._execRequestAsync({
2251
+ operation: () => {
2252
+ const rawIndex2 = this._rawObjectStore.rawIndexes.get(name);
2253
+ if (rawIndex === rawIndex2) {
2254
+ this._rawObjectStore.rawIndexes.delete(name);
2255
+ }
2256
+ },
2257
+ source: this
2258
+ });
2259
+ }
2260
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBObjectStore-count-IDBRequest-any-key
2261
+ count(key) {
2262
+ confirmActiveTransaction2(this);
2263
+ if (key === null) {
2264
+ key = void 0;
2265
+ }
2266
+ if (key !== void 0 && !(key instanceof FDBKeyRange_default)) {
2267
+ key = FDBKeyRange_default.only(valueToKey_default(key));
2268
+ }
2269
+ return this.transaction._execRequestAsync({
2270
+ operation: () => {
2271
+ return this._rawObjectStore.count(key);
2272
+ },
2273
+ source: this
2274
+ });
2275
+ }
2276
+ get [Symbol.toStringTag]() {
2277
+ return "IDBObjectStore";
2278
+ }
2279
+ };
2280
+ var FDBObjectStore_default = FDBObjectStore;
2281
+
2282
+ // ../../node_modules/fake-indexeddb/build/esm/lib/FakeEvent.js
2283
+ var Event = class {
2284
+ eventPath = [];
2285
+ NONE = 0;
2286
+ CAPTURING_PHASE = 1;
2287
+ AT_TARGET = 2;
2288
+ BUBBLING_PHASE = 3;
2289
+ // Flags
2290
+ propagationStopped = false;
2291
+ immediatePropagationStopped = false;
2292
+ canceled = false;
2293
+ initialized = true;
2294
+ dispatched = false;
2295
+ target = null;
2296
+ currentTarget = null;
2297
+ eventPhase = 0;
2298
+ defaultPrevented = false;
2299
+ isTrusted = false;
2300
+ timeStamp = Date.now();
2301
+ constructor(type, eventInitDict = {}) {
2302
+ this.type = type;
2303
+ this.bubbles = eventInitDict.bubbles !== void 0 ? eventInitDict.bubbles : false;
2304
+ this.cancelable = eventInitDict.cancelable !== void 0 ? eventInitDict.cancelable : false;
2305
+ }
2306
+ preventDefault() {
2307
+ if (this.cancelable) {
2308
+ this.canceled = true;
2309
+ }
2310
+ }
2311
+ stopPropagation() {
2312
+ this.propagationStopped = true;
2313
+ }
2314
+ stopImmediatePropagation() {
2315
+ this.propagationStopped = true;
2316
+ this.immediatePropagationStopped = true;
2317
+ }
2318
+ };
2319
+ var FakeEvent_default = Event;
2320
+
2321
+ // ../../node_modules/fake-indexeddb/build/esm/lib/scheduling.js
2322
+ function getSetImmediateFromJsdom() {
2323
+ if (typeof navigator !== "undefined" && /jsdom/.test(navigator.userAgent)) {
2324
+ const outerRealmFunctionConstructor = Node.constructor;
2325
+ return new outerRealmFunctionConstructor("return setImmediate")();
2326
+ } else {
2327
+ return void 0;
2328
+ }
2329
+ }
2330
+ var schedulerPostTask = typeof scheduler !== "undefined" && ((fn) => scheduler.postTask(fn));
2331
+ var doSetTimeout = (fn) => setTimeout(fn, 0);
2332
+ var queueTask = (fn) => {
2333
+ const setImmediate = globalThis.setImmediate || getSetImmediateFromJsdom() || schedulerPostTask || doSetTimeout;
2334
+ setImmediate(fn);
2335
+ };
2336
+
2337
+ // ../../node_modules/fake-indexeddb/build/esm/FDBTransaction.js
2338
+ var prioritizedListenerTypes = ["error", "abort", "complete"];
2339
+ var FDBTransaction = class extends FakeEventTarget_default {
2340
+ _state = "active";
2341
+ _started = false;
2342
+ _rollbackLog = [];
2343
+ _objectStoresCache = /* @__PURE__ */ new Map();
2344
+ _openRequest = null;
2345
+ error = null;
2346
+ onabort = null;
2347
+ oncomplete = null;
2348
+ onerror = null;
2349
+ _prioritizedListeners = /* @__PURE__ */ new Map();
2350
+ _requests = [];
2351
+ _createdIndexes = /* @__PURE__ */ new Set();
2352
+ _createdObjectStores = /* @__PURE__ */ new Set();
2353
+ constructor(storeNames, mode, durability, db) {
2354
+ super();
2355
+ this._scope = new Set(storeNames);
2356
+ this.mode = mode;
2357
+ this.durability = durability;
2358
+ this.db = db;
2359
+ this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this._scope).sort());
2360
+ for (const type of prioritizedListenerTypes) {
2361
+ this.addEventListener(type, () => {
2362
+ this._prioritizedListeners.get(type)?.();
2363
+ });
2364
+ }
2365
+ }
2366
+ // https://w3c.github.io/IndexedDB/#abort-transaction
2367
+ _abort(errName) {
2368
+ for (const f of this._rollbackLog.reverse()) {
2369
+ f();
2370
+ }
2371
+ if (errName !== null) {
2372
+ const e = new DOMException(void 0, errName);
2373
+ this.error = e;
2374
+ }
2375
+ for (const {
2376
+ request
2377
+ } of this._requests) {
2378
+ if (request.readyState !== "done") {
2379
+ request.readyState = "done";
2380
+ if (request.source) {
2381
+ queueTask(() => {
2382
+ request.result = void 0;
2383
+ request.error = new AbortError();
2384
+ const event = new FakeEvent_default("error", {
2385
+ bubbles: true,
2386
+ cancelable: true
2387
+ });
2388
+ event.eventPath = [this.db, this];
2389
+ try {
2390
+ request.dispatchEvent(event);
2391
+ } catch (_err) {
2392
+ if (this._state === "active") {
2393
+ this._abort("AbortError");
2394
+ }
2395
+ }
2396
+ });
2397
+ }
2398
+ }
2399
+ }
2400
+ queueTask(() => {
2401
+ const isUpgradeTransaction = this.mode === "versionchange";
2402
+ if (isUpgradeTransaction) {
2403
+ this.db._rawDatabase.connections = this.db._rawDatabase.connections.filter((connection) => !connection._rawDatabase.transactions.includes(this));
2404
+ }
2405
+ const event = new FakeEvent_default("abort", {
2406
+ bubbles: true,
2407
+ cancelable: false
2408
+ });
2409
+ event.eventPath = [this.db];
2410
+ this.dispatchEvent(event);
2411
+ if (isUpgradeTransaction) {
2412
+ const request = this._openRequest;
2413
+ request.transaction = null;
2414
+ request.result = void 0;
2415
+ }
2416
+ });
2417
+ this._state = "finished";
2418
+ }
2419
+ abort() {
2420
+ if (this._state === "committing" || this._state === "finished") {
2421
+ throw new InvalidStateError();
2422
+ }
2423
+ this._state = "active";
2424
+ this._abort(null);
2425
+ }
2426
+ // http://w3c.github.io/IndexedDB/#dom-idbtransaction-objectstore
2427
+ objectStore(name) {
2428
+ if (this._state !== "active") {
2429
+ throw new InvalidStateError();
2430
+ }
2431
+ const objectStore = this._objectStoresCache.get(name);
2432
+ if (objectStore !== void 0) {
2433
+ return objectStore;
2434
+ }
2435
+ const rawObjectStore = this.db._rawDatabase.rawObjectStores.get(name);
2436
+ if (!this._scope.has(name) || rawObjectStore === void 0) {
2437
+ throw new NotFoundError();
2438
+ }
2439
+ const objectStore2 = new FDBObjectStore_default(this, rawObjectStore);
2440
+ this._objectStoresCache.set(name, objectStore2);
2441
+ return objectStore2;
2442
+ }
2443
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-asynchronously-executing-a-request
2444
+ _execRequestAsync(obj) {
2445
+ const source = obj.source;
2446
+ const operation = obj.operation;
2447
+ let request = Object.hasOwn(obj, "request") ? obj.request : null;
2448
+ if (this._state !== "active") {
2449
+ throw new TransactionInactiveError();
2450
+ }
2451
+ if (!request) {
2452
+ if (!source) {
2453
+ request = new FDBRequest_default();
2454
+ } else {
2455
+ request = new FDBRequest_default();
2456
+ request.source = source;
2457
+ request.transaction = source.transaction;
2458
+ }
2459
+ }
2460
+ this._requests.push({
2461
+ operation,
2462
+ request
2463
+ });
2464
+ return request;
2465
+ }
2466
+ _start() {
2467
+ this._started = true;
2468
+ let operation;
2469
+ let request;
2470
+ while (this._requests.length > 0) {
2471
+ const r = this._requests.shift();
2472
+ if (r && r.request.readyState !== "done") {
2473
+ request = r.request;
2474
+ operation = r.operation;
2475
+ break;
2476
+ }
2477
+ }
2478
+ if (request && operation) {
2479
+ if (!request.source) {
2480
+ operation();
2481
+ } else {
2482
+ let defaultAction;
2483
+ let event;
2484
+ try {
2485
+ const result = operation();
2486
+ request.readyState = "done";
2487
+ request.result = result;
2488
+ request.error = void 0;
2489
+ if (this._state === "inactive") {
2490
+ this._state = "active";
2491
+ }
2492
+ event = new FakeEvent_default("success", {
2493
+ bubbles: false,
2494
+ cancelable: false
2495
+ });
2496
+ } catch (err) {
2497
+ request.readyState = "done";
2498
+ request.result = void 0;
2499
+ request.error = err;
2500
+ if (this._state === "inactive") {
2501
+ this._state = "active";
2502
+ }
2503
+ event = new FakeEvent_default("error", {
2504
+ bubbles: true,
2505
+ cancelable: true
2506
+ });
2507
+ defaultAction = this._abort.bind(this, err.name);
2508
+ }
2509
+ try {
2510
+ event.eventPath = [this.db, this];
2511
+ request.dispatchEvent(event);
2512
+ } catch (_err) {
2513
+ if (this._state === "active") {
2514
+ this._abort("AbortError");
2515
+ defaultAction = void 0;
2516
+ }
2517
+ }
2518
+ if (!event.canceled) {
2519
+ if (defaultAction) {
2520
+ defaultAction();
2521
+ }
2522
+ }
2523
+ }
2524
+ queueTask(this._start.bind(this));
2525
+ return;
2526
+ }
2527
+ if (this._state !== "finished") {
2528
+ this._state = "finished";
2529
+ if (!this.error) {
2530
+ const event = new FakeEvent_default("complete");
2531
+ this.dispatchEvent(event);
2532
+ }
2533
+ }
2534
+ }
2535
+ commit() {
2536
+ if (this._state !== "active") {
2537
+ throw new InvalidStateError();
2538
+ }
2539
+ this._state = "committing";
2540
+ }
2541
+ get [Symbol.toStringTag]() {
2542
+ return "IDBTransaction";
2543
+ }
2544
+ };
2545
+ var FDBTransaction_default = FDBTransaction;
2546
+
2547
+ // ../../node_modules/fake-indexeddb/build/esm/lib/KeyGenerator.js
2548
+ var MAX_KEY = 9007199254740992;
2549
+ var KeyGenerator = class {
2550
+ // This is kind of wrong. Should start at 1 and increment only after record is saved
2551
+ num = 0;
2552
+ next() {
2553
+ if (this.num >= MAX_KEY) {
2554
+ throw new ConstraintError();
2555
+ }
2556
+ this.num += 1;
2557
+ return this.num;
2558
+ }
2559
+ // https://w3c.github.io/IndexedDB/#possibly-update-the-key-generator
2560
+ setIfLarger(num) {
2561
+ const value = Math.floor(Math.min(num, MAX_KEY)) - 1;
2562
+ if (value >= this.num) {
2563
+ this.num = value + 1;
2564
+ }
2565
+ }
2566
+ };
2567
+ var KeyGenerator_default = KeyGenerator;
2568
+
2569
+ // ../../node_modules/fake-indexeddb/build/esm/lib/ObjectStore.js
2570
+ var ObjectStore = class {
2571
+ deleted = false;
2572
+ records = new RecordStore_default(true);
2573
+ rawIndexes = /* @__PURE__ */ new Map();
2574
+ constructor(rawDatabase, name, keyPath, autoIncrement) {
2575
+ this.rawDatabase = rawDatabase;
2576
+ this.keyGenerator = autoIncrement === true ? new KeyGenerator_default() : null;
2577
+ this.deleted = false;
2578
+ this.name = name;
2579
+ this.keyPath = keyPath;
2580
+ this.autoIncrement = autoIncrement;
2581
+ }
2582
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store
2583
+ getKey(key) {
2584
+ const record = this.records.get(key);
2585
+ return record !== void 0 ? structuredClone(record.key) : void 0;
2586
+ }
2587
+ // http://w3c.github.io/IndexedDB/#retrieve-multiple-keys-from-an-object-store
2588
+ getAllKeys(range, count, direction) {
2589
+ if (count === void 0 || count === 0) {
2590
+ count = Infinity;
2591
+ }
2592
+ const records = [];
2593
+ for (const record of this.records.values(range, direction)) {
2594
+ records.push(structuredClone(record.key));
2595
+ if (records.length >= count) {
2596
+ break;
2597
+ }
2598
+ }
2599
+ return records;
2600
+ }
2601
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-retrieving-a-value-from-an-object-store
2602
+ getValue(key) {
2603
+ const record = this.records.get(key);
2604
+ return record !== void 0 ? structuredClone(record.value) : void 0;
2605
+ }
2606
+ // http://w3c.github.io/IndexedDB/#retrieve-multiple-values-from-an-object-store
2607
+ getAllValues(range, count, direction) {
2608
+ if (count === void 0 || count === 0) {
2609
+ count = Infinity;
2610
+ }
2611
+ const records = [];
2612
+ for (const record of this.records.values(range, direction)) {
2613
+ records.push(structuredClone(record.value));
2614
+ if (records.length >= count) {
2615
+ break;
2616
+ }
2617
+ }
2618
+ return records;
2619
+ }
2620
+ // https://www.w3.org/TR/IndexedDB/#dom-idbobjectstore-getallrecords
2621
+ getAllRecords(range, count, direction) {
2622
+ if (count === void 0 || count === 0) {
2623
+ count = Infinity;
2624
+ }
2625
+ const records = [];
2626
+ for (const record of this.records.values(range, direction)) {
2627
+ records.push(new FDBRecord_default(structuredClone(record.key), structuredClone(record.key), structuredClone(record.value)));
2628
+ if (records.length >= count) {
2629
+ break;
2630
+ }
2631
+ }
2632
+ return records;
2633
+ }
2634
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-storing-a-record-into-an-object-store
2635
+ storeRecord(newRecord, noOverwrite, rollbackLog) {
2636
+ if (this.keyPath !== null) {
2637
+ const key = extractKey_default(this.keyPath, newRecord.value).key;
2638
+ if (key !== void 0) {
2639
+ newRecord.key = key;
2640
+ }
2641
+ }
2642
+ const rollbackLogForThisOperation = [];
2643
+ if (this.keyGenerator !== null && newRecord.key === void 0) {
2644
+ let rolledBack2 = false;
2645
+ const keyGeneratorBefore = this.keyGenerator.num;
2646
+ const rollbackKeyGenerator = () => {
2647
+ if (rolledBack2) {
2648
+ return;
2649
+ }
2650
+ rolledBack2 = true;
2651
+ if (this.keyGenerator) {
2652
+ this.keyGenerator.num = keyGeneratorBefore;
2653
+ }
2654
+ };
2655
+ rollbackLogForThisOperation.push(rollbackKeyGenerator);
2656
+ if (rollbackLog) {
2657
+ rollbackLog.push(rollbackKeyGenerator);
2658
+ }
2659
+ newRecord.key = this.keyGenerator.next();
2660
+ if (this.keyPath !== null) {
2661
+ if (Array.isArray(this.keyPath)) {
2662
+ throw new Error("Cannot have an array key path in an object store with a key generator");
2663
+ }
2664
+ let remainingKeyPath = this.keyPath;
2665
+ let object = newRecord.value;
2666
+ let identifier;
2667
+ let i = 0;
2668
+ while (i >= 0) {
2669
+ if (typeof object !== "object") {
2670
+ throw new DataError();
2671
+ }
2672
+ i = remainingKeyPath.indexOf(".");
2673
+ if (i >= 0) {
2674
+ identifier = remainingKeyPath.slice(0, i);
2675
+ remainingKeyPath = remainingKeyPath.slice(i + 1);
2676
+ if (!Object.hasOwn(object, identifier)) {
2677
+ Object.defineProperty(object, identifier, {
2678
+ configurable: true,
2679
+ enumerable: true,
2680
+ writable: true,
2681
+ value: {}
2682
+ });
2683
+ }
2684
+ object = object[identifier];
2685
+ }
2686
+ }
2687
+ identifier = remainingKeyPath;
2688
+ Object.defineProperty(object, identifier, {
2689
+ configurable: true,
2690
+ enumerable: true,
2691
+ writable: true,
2692
+ value: newRecord.key
2693
+ });
2694
+ }
2695
+ } else if (this.keyGenerator !== null && typeof newRecord.key === "number") {
2696
+ this.keyGenerator.setIfLarger(newRecord.key);
2697
+ }
2698
+ const existingRecord = this.records.put(newRecord, noOverwrite);
2699
+ let rolledBack = false;
2700
+ const rollbackStoreRecord = () => {
2701
+ if (rolledBack) {
2702
+ return;
2703
+ }
2704
+ rolledBack = true;
2705
+ if (existingRecord) {
2706
+ this.storeRecord(existingRecord, false);
2707
+ } else {
2708
+ this.deleteRecord(newRecord.key);
2709
+ }
2710
+ };
2711
+ rollbackLogForThisOperation.push(rollbackStoreRecord);
2712
+ if (rollbackLog) {
2713
+ rollbackLog.push(rollbackStoreRecord);
2714
+ }
2715
+ if (existingRecord) {
2716
+ for (const rawIndex of this.rawIndexes.values()) {
2717
+ rawIndex.records.deleteByValue(newRecord.key);
2718
+ }
2719
+ }
2720
+ try {
2721
+ for (const rawIndex of this.rawIndexes.values()) {
2722
+ if (rawIndex.initialized) {
2723
+ rawIndex.storeRecord(newRecord);
2724
+ }
2725
+ }
2726
+ } catch (err) {
2727
+ if (err.name === "ConstraintError") {
2728
+ for (const rollback of rollbackLogForThisOperation) {
2729
+ rollback();
2730
+ }
2731
+ }
2732
+ throw err;
2733
+ }
2734
+ return newRecord.key;
2735
+ }
2736
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-records-from-an-object-store
2737
+ deleteRecord(key, rollbackLog) {
2738
+ const deletedRecords = this.records.delete(key);
2739
+ if (rollbackLog) {
2740
+ for (const record of deletedRecords) {
2741
+ rollbackLog.push(() => {
2742
+ this.storeRecord(record, true);
2743
+ });
2744
+ }
2745
+ }
2746
+ for (const rawIndex of this.rawIndexes.values()) {
2747
+ rawIndex.records.deleteByValue(key);
2748
+ }
2749
+ }
2750
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-clearing-an-object-store
2751
+ clear(rollbackLog) {
2752
+ const deletedRecords = this.records.clear();
2753
+ if (rollbackLog) {
2754
+ for (const record of deletedRecords) {
2755
+ rollbackLog.push(() => {
2756
+ this.storeRecord(record, true);
2757
+ });
2758
+ }
2759
+ }
2760
+ for (const rawIndex of this.rawIndexes.values()) {
2761
+ rawIndex.records.clear();
2762
+ }
2763
+ }
2764
+ count(range) {
2765
+ if (range === void 0 || range.lower === void 0 && range.upper === void 0) {
2766
+ return this.records.size();
2767
+ }
2768
+ let count = 0;
2769
+ for (const record of this.records.values(range)) {
2770
+ count += 1;
2771
+ }
2772
+ return count;
2773
+ }
2774
+ };
2775
+ var ObjectStore_default = ObjectStore;
2776
+
2777
+ // ../../node_modules/fake-indexeddb/build/esm/lib/closeConnection.js
2778
+ var closeConnection = (connection, forced = false) => {
2779
+ connection._closePending = true;
2780
+ const transactionsComplete = connection._rawDatabase.transactions.every((transaction) => {
2781
+ return transaction._state === "finished";
2782
+ });
2783
+ if (transactionsComplete) {
2784
+ connection._closed = true;
2785
+ connection._rawDatabase.connections = connection._rawDatabase.connections.filter((otherConnection) => {
2786
+ return connection !== otherConnection;
2787
+ });
2788
+ if (forced) {
2789
+ const event = new FakeEvent_default("close", {
2790
+ bubbles: false,
2791
+ cancelable: false
2792
+ });
2793
+ event.eventPath = [];
2794
+ connection.dispatchEvent(event);
2795
+ }
2796
+ } else {
2797
+ queueTask(() => {
2798
+ closeConnection(connection, forced);
2799
+ });
2800
+ }
2801
+ };
2802
+ var closeConnection_default = closeConnection;
2803
+
2804
+ // ../../node_modules/fake-indexeddb/build/esm/FDBDatabase.js
2805
+ var confirmActiveVersionchangeTransaction = (database) => {
2806
+ let transaction;
2807
+ if (database._runningVersionchangeTransaction) {
2808
+ transaction = database._rawDatabase.transactions.findLast((tx) => {
2809
+ return tx.mode === "versionchange";
2810
+ });
2811
+ }
2812
+ if (!transaction) {
2813
+ throw new InvalidStateError();
2814
+ }
2815
+ if (transaction._state !== "active") {
2816
+ throw new TransactionInactiveError();
2817
+ }
2818
+ return transaction;
2819
+ };
2820
+ var FDBDatabase = class extends FakeEventTarget_default {
2821
+ _closePending = false;
2822
+ _closed = false;
2823
+ _runningVersionchangeTransaction = false;
2824
+ constructor(rawDatabase) {
2825
+ super();
2826
+ this._rawDatabase = rawDatabase;
2827
+ this._rawDatabase.connections.push(this);
2828
+ this.name = rawDatabase.name;
2829
+ this.version = rawDatabase.version;
2830
+ this.objectStoreNames = new FakeDOMStringList_default(...Array.from(rawDatabase.rawObjectStores.keys()).sort());
2831
+ }
2832
+ // http://w3c.github.io/IndexedDB/#dom-idbdatabase-createobjectstore
2833
+ createObjectStore(name, options = {}) {
2834
+ if (name === void 0) {
2835
+ throw new TypeError();
2836
+ }
2837
+ const transaction = confirmActiveVersionchangeTransaction(this);
2838
+ const keyPath = options !== null && options.keyPath !== void 0 ? options.keyPath : null;
2839
+ const autoIncrement = options !== null && options.autoIncrement !== void 0 ? options.autoIncrement : false;
2840
+ if (keyPath !== null) {
2841
+ validateKeyPath_default(keyPath);
2842
+ }
2843
+ if (this._rawDatabase.rawObjectStores.has(name)) {
2844
+ throw new ConstraintError();
2845
+ }
2846
+ if (autoIncrement && (keyPath === "" || Array.isArray(keyPath))) {
2847
+ throw new InvalidAccessError();
2848
+ }
2849
+ const objectStoreNames = [...this.objectStoreNames];
2850
+ const transactionObjectStoreNames = [...transaction.objectStoreNames];
2851
+ const rawObjectStore = new ObjectStore_default(this._rawDatabase, name, keyPath, autoIncrement);
2852
+ this.objectStoreNames._push(name);
2853
+ this.objectStoreNames._sort();
2854
+ transaction._scope.add(name);
2855
+ transaction._createdObjectStores.add(rawObjectStore);
2856
+ this._rawDatabase.rawObjectStores.set(name, rawObjectStore);
2857
+ transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames);
2858
+ transaction._rollbackLog.push(() => {
2859
+ rawObjectStore.deleted = true;
2860
+ this.objectStoreNames = new FakeDOMStringList_default(...objectStoreNames);
2861
+ transaction.objectStoreNames = new FakeDOMStringList_default(...transactionObjectStoreNames);
2862
+ transaction._scope.delete(rawObjectStore.name);
2863
+ this._rawDatabase.rawObjectStores.delete(rawObjectStore.name);
2864
+ });
2865
+ return transaction.objectStore(name);
2866
+ }
2867
+ // https://www.w3.org/TR/IndexedDB/#dom-idbdatabase-deleteobjectstore
2868
+ deleteObjectStore(name) {
2869
+ if (name === void 0) {
2870
+ throw new TypeError();
2871
+ }
2872
+ const transaction = confirmActiveVersionchangeTransaction(this);
2873
+ const store2 = this._rawDatabase.rawObjectStores.get(name);
2874
+ if (store2 === void 0) {
2875
+ throw new NotFoundError();
2876
+ }
2877
+ this.objectStoreNames = new FakeDOMStringList_default(...Array.from(this.objectStoreNames).filter((objectStoreName) => {
2878
+ return objectStoreName !== name;
2879
+ }));
2880
+ transaction.objectStoreNames = new FakeDOMStringList_default(...this.objectStoreNames);
2881
+ const objectStore = transaction._objectStoresCache.get(name);
2882
+ let prevIndexNames;
2883
+ if (objectStore) {
2884
+ prevIndexNames = [...objectStore.indexNames];
2885
+ objectStore.indexNames = new FakeDOMStringList_default();
2886
+ }
2887
+ transaction._rollbackLog.push(() => {
2888
+ store2.deleted = false;
2889
+ this._rawDatabase.rawObjectStores.set(store2.name, store2);
2890
+ this.objectStoreNames._push(store2.name);
2891
+ transaction.objectStoreNames._push(store2.name);
2892
+ this.objectStoreNames._sort();
2893
+ if (objectStore && prevIndexNames) {
2894
+ objectStore.indexNames = new FakeDOMStringList_default(...prevIndexNames);
2895
+ }
2896
+ });
2897
+ store2.deleted = true;
2898
+ this._rawDatabase.rawObjectStores.delete(name);
2899
+ transaction._objectStoresCache.delete(name);
2900
+ }
2901
+ transaction(storeNames, mode, options) {
2902
+ mode = mode !== void 0 ? mode : "readonly";
2903
+ if (mode !== "readonly" && mode !== "readwrite" && mode !== "versionchange") {
2904
+ throw new TypeError("Invalid mode: " + mode);
2905
+ }
2906
+ const hasActiveVersionchange = this._rawDatabase.transactions.some((transaction) => {
2907
+ return transaction._state === "active" && transaction.mode === "versionchange" && transaction.db === this;
2908
+ });
2909
+ if (hasActiveVersionchange) {
2910
+ throw new InvalidStateError();
2911
+ }
2912
+ if (this._closePending) {
2913
+ throw new InvalidStateError();
2914
+ }
2915
+ if (!Array.isArray(storeNames)) {
2916
+ storeNames = [storeNames];
2917
+ }
2918
+ if (storeNames.length === 0 && mode !== "versionchange") {
2919
+ throw new InvalidAccessError();
2920
+ }
2921
+ for (const storeName of storeNames) {
2922
+ if (!this.objectStoreNames.contains(storeName)) {
2923
+ throw new NotFoundError("No objectStore named " + storeName + " in this database");
2924
+ }
2925
+ }
2926
+ const durability = options?.durability ?? "default";
2927
+ if (durability !== "default" && durability !== "strict" && durability !== "relaxed") {
2928
+ throw new TypeError(
2929
+ // based on Firefox's error message
2930
+ `'${durability}' (value of 'durability' member of IDBTransactionOptions) is not a valid value for enumeration IDBTransactionDurability`
2931
+ );
2932
+ }
2933
+ const tx = new FDBTransaction_default(storeNames, mode, durability, this);
2934
+ this._rawDatabase.transactions.push(tx);
2935
+ this._rawDatabase.processTransactions();
2936
+ return tx;
2937
+ }
2938
+ close() {
2939
+ closeConnection_default(this);
2940
+ }
2941
+ get [Symbol.toStringTag]() {
2942
+ return "IDBDatabase";
2943
+ }
2944
+ };
2945
+ var FDBDatabase_default = FDBDatabase;
2946
+
2947
+ // ../../node_modules/fake-indexeddb/build/esm/FDBOpenDBRequest.js
2948
+ var FDBOpenDBRequest = class extends FDBRequest_default {
2949
+ onupgradeneeded = null;
2950
+ onblocked = null;
2951
+ get [Symbol.toStringTag]() {
2952
+ return "IDBOpenDBRequest";
2953
+ }
2954
+ };
2955
+ var FDBOpenDBRequest_default = FDBOpenDBRequest;
2956
+
2957
+ // ../../node_modules/fake-indexeddb/build/esm/FDBVersionChangeEvent.js
2958
+ var FDBVersionChangeEvent = class extends FakeEvent_default {
2959
+ constructor(type, parameters = {}) {
2960
+ super(type);
2961
+ this.newVersion = parameters.newVersion !== void 0 ? parameters.newVersion : null;
2962
+ this.oldVersion = parameters.oldVersion !== void 0 ? parameters.oldVersion : 0;
2963
+ }
2964
+ get [Symbol.toStringTag]() {
2965
+ return "IDBVersionChangeEvent";
2966
+ }
2967
+ };
2968
+ var FDBVersionChangeEvent_default = FDBVersionChangeEvent;
2969
+
2970
+ // ../../node_modules/fake-indexeddb/build/esm/lib/intersection.js
2971
+ function intersection(set1, set2) {
2972
+ if ("intersection" in set1) {
2973
+ return set1.intersection(set2);
2974
+ }
2975
+ return new Set([...set1].filter((item) => set2.has(item)));
2976
+ }
2977
+
2978
+ // ../../node_modules/fake-indexeddb/build/esm/lib/Database.js
2979
+ var Database = class {
2980
+ transactions = [];
2981
+ rawObjectStores = /* @__PURE__ */ new Map();
2982
+ connections = [];
2983
+ constructor(name, version) {
2984
+ this.name = name;
2985
+ this.version = version;
2986
+ this.processTransactions = this.processTransactions.bind(this);
2987
+ }
2988
+ processTransactions() {
2989
+ queueTask(() => {
2990
+ const running = this.transactions.filter((transaction) => transaction._started && transaction._state !== "finished");
2991
+ const waiting = this.transactions.filter((transaction) => !transaction._started && transaction._state !== "finished");
2992
+ const next = waiting.find((transaction, i) => {
2993
+ const anyRunning = running.some((other) => !(transaction.mode === "readonly" && other.mode === "readonly") && intersection(other._scope, transaction._scope).size > 0);
2994
+ if (anyRunning) {
2995
+ return false;
2996
+ }
2997
+ const anyWaiting = waiting.slice(0, i).some((other) => intersection(other._scope, transaction._scope).size > 0);
2998
+ return !anyWaiting;
2999
+ });
3000
+ if (next) {
3001
+ next.addEventListener("complete", this.processTransactions);
3002
+ next.addEventListener("abort", this.processTransactions);
3003
+ next._start();
3004
+ }
3005
+ });
3006
+ }
3007
+ };
3008
+ var Database_default = Database;
3009
+
3010
+ // ../../node_modules/fake-indexeddb/build/esm/lib/validateRequiredArguments.js
3011
+ function validateRequiredArguments(numArguments, expectedNumArguments, methodName) {
3012
+ if (numArguments < expectedNumArguments) {
3013
+ throw new TypeError(`${methodName}: At least ${expectedNumArguments} ${expectedNumArguments === 1 ? "argument" : "arguments"} required, but only ${arguments.length} passed`);
3014
+ }
3015
+ }
3016
+
3017
+ // ../../node_modules/fake-indexeddb/build/esm/FDBFactory.js
3018
+ var runTaskInConnectionQueue = (connectionQueues, name, task) => {
3019
+ const queue = connectionQueues.get(name) ?? Promise.resolve();
3020
+ connectionQueues.set(name, queue.then(task));
3021
+ };
3022
+ var waitForOthersClosedDelete = (databases, name, openDatabases, cb) => {
3023
+ const anyOpen = openDatabases.some((openDatabase2) => {
3024
+ return !openDatabase2._closed && !openDatabase2._closePending;
3025
+ });
3026
+ if (anyOpen) {
3027
+ queueTask(() => waitForOthersClosedDelete(databases, name, openDatabases, cb));
3028
+ return;
3029
+ }
3030
+ databases.delete(name);
3031
+ cb(null);
3032
+ };
3033
+ var deleteDatabase = (databases, connectionQueues, name, request, cb) => {
3034
+ const deleteDBTask = () => {
3035
+ return new Promise((resolve) => {
3036
+ const db = databases.get(name);
3037
+ const oldVersion = db !== void 0 ? db.version : 0;
3038
+ const onComplete = (err) => {
3039
+ try {
3040
+ if (err) {
3041
+ cb(err);
3042
+ } else {
3043
+ cb(null, oldVersion);
3044
+ }
3045
+ } finally {
3046
+ resolve();
3047
+ }
3048
+ };
3049
+ try {
3050
+ const db2 = databases.get(name);
3051
+ if (db2 === void 0) {
3052
+ onComplete(null);
3053
+ return;
3054
+ }
3055
+ const openConnections = db2.connections.filter((connection) => {
3056
+ return !connection._closed;
3057
+ });
3058
+ for (const openDatabase2 of openConnections) {
3059
+ if (!openDatabase2._closePending) {
3060
+ queueTask(() => {
3061
+ const event = new FDBVersionChangeEvent_default("versionchange", {
3062
+ newVersion: null,
3063
+ oldVersion: db2.version
3064
+ });
3065
+ openDatabase2.dispatchEvent(event);
3066
+ });
3067
+ }
3068
+ }
3069
+ queueTask(() => {
3070
+ const anyOpen = openConnections.some((openDatabase3) => {
3071
+ return !openDatabase3._closed && !openDatabase3._closePending;
3072
+ });
3073
+ if (anyOpen) {
3074
+ queueTask(() => {
3075
+ const event = new FDBVersionChangeEvent_default("blocked", {
3076
+ newVersion: null,
3077
+ oldVersion: db2.version
3078
+ });
3079
+ request.dispatchEvent(event);
3080
+ });
3081
+ }
3082
+ waitForOthersClosedDelete(databases, name, openConnections, onComplete);
3083
+ });
3084
+ } catch (err) {
3085
+ onComplete(err);
3086
+ }
3087
+ });
3088
+ };
3089
+ runTaskInConnectionQueue(connectionQueues, name, deleteDBTask);
3090
+ };
3091
+ var runVersionchangeTransaction = (connection, version, request, cb) => {
3092
+ connection._runningVersionchangeTransaction = true;
3093
+ const oldVersion = connection._oldVersion = connection.version;
3094
+ const openConnections = connection._rawDatabase.connections.filter((otherDatabase) => {
3095
+ return connection !== otherDatabase;
3096
+ });
3097
+ for (const openDatabase2 of openConnections) {
3098
+ if (!openDatabase2._closed && !openDatabase2._closePending) {
3099
+ queueTask(() => {
3100
+ const event = new FDBVersionChangeEvent_default("versionchange", {
3101
+ newVersion: version,
3102
+ oldVersion
3103
+ });
3104
+ openDatabase2.dispatchEvent(event);
3105
+ });
3106
+ }
3107
+ }
3108
+ queueTask(() => {
3109
+ const anyOpen = openConnections.some((openDatabase3) => {
3110
+ return !openDatabase3._closed && !openDatabase3._closePending;
3111
+ });
3112
+ if (anyOpen) {
3113
+ queueTask(() => {
3114
+ const event = new FDBVersionChangeEvent_default("blocked", {
3115
+ newVersion: version,
3116
+ oldVersion
3117
+ });
3118
+ request.dispatchEvent(event);
3119
+ });
3120
+ }
3121
+ const waitForOthersClosed = () => {
3122
+ const anyOpen2 = openConnections.some((openDatabase2) => {
3123
+ return !openDatabase2._closed && !openDatabase2._closePending;
3124
+ });
3125
+ if (anyOpen2) {
3126
+ queueTask(waitForOthersClosed);
3127
+ return;
3128
+ }
3129
+ connection._rawDatabase.version = version;
3130
+ connection.version = version;
3131
+ const transaction = connection.transaction(Array.from(connection.objectStoreNames), "versionchange");
3132
+ transaction._openRequest = request;
3133
+ request.result = connection;
3134
+ request.readyState = "done";
3135
+ request.transaction = transaction;
3136
+ transaction._rollbackLog.push(() => {
3137
+ connection._rawDatabase.version = oldVersion;
3138
+ connection.version = oldVersion;
3139
+ });
3140
+ transaction._state = "active";
3141
+ const event = new FDBVersionChangeEvent_default("upgradeneeded", {
3142
+ newVersion: version,
3143
+ oldVersion
3144
+ });
3145
+ let didThrow = false;
3146
+ try {
3147
+ request.dispatchEvent(event);
3148
+ } catch (_err) {
3149
+ didThrow = true;
3150
+ }
3151
+ const concludeUpgrade = () => {
3152
+ if (transaction._state === "active") {
3153
+ transaction._state = "inactive";
3154
+ if (didThrow) {
3155
+ transaction._abort("AbortError");
3156
+ }
3157
+ }
3158
+ };
3159
+ if (didThrow) {
3160
+ concludeUpgrade();
3161
+ } else {
3162
+ queueTask(concludeUpgrade);
3163
+ }
3164
+ transaction._prioritizedListeners.set("error", () => {
3165
+ connection._runningVersionchangeTransaction = false;
3166
+ connection._oldVersion = void 0;
3167
+ });
3168
+ transaction._prioritizedListeners.set("abort", () => {
3169
+ connection._runningVersionchangeTransaction = false;
3170
+ connection._oldVersion = void 0;
3171
+ queueTask(() => {
3172
+ request.transaction = null;
3173
+ cb(new AbortError());
3174
+ });
3175
+ });
3176
+ transaction._prioritizedListeners.set("complete", () => {
3177
+ connection._runningVersionchangeTransaction = false;
3178
+ connection._oldVersion = void 0;
3179
+ queueTask(() => {
3180
+ request.transaction = null;
3181
+ if (connection._closePending) {
3182
+ cb(new AbortError());
3183
+ } else {
3184
+ cb(null);
3185
+ }
3186
+ });
3187
+ });
3188
+ };
3189
+ waitForOthersClosed();
3190
+ });
3191
+ };
3192
+ var openDatabase = (databases, connectionQueues, name, version, request, cb) => {
3193
+ const openDBTask = () => {
3194
+ return new Promise((resolve) => {
3195
+ const onComplete = (err) => {
3196
+ try {
3197
+ if (err) {
3198
+ cb(err);
3199
+ } else {
3200
+ cb(null, connection);
3201
+ }
3202
+ } finally {
3203
+ resolve();
3204
+ }
3205
+ };
3206
+ let db = databases.get(name);
3207
+ if (db === void 0) {
3208
+ db = new Database_default(name, 0);
3209
+ databases.set(name, db);
3210
+ }
3211
+ if (version === void 0) {
3212
+ version = db.version !== 0 ? db.version : 1;
3213
+ }
3214
+ if (db.version > version) {
3215
+ return onComplete(new VersionError());
3216
+ }
3217
+ const connection = new FDBDatabase_default(db);
3218
+ if (db.version < version) {
3219
+ runVersionchangeTransaction(connection, version, request, (err) => {
3220
+ onComplete(err);
3221
+ });
3222
+ } else {
3223
+ onComplete(null);
3224
+ }
3225
+ });
3226
+ };
3227
+ runTaskInConnectionQueue(connectionQueues, name, openDBTask);
3228
+ };
3229
+ var FDBFactory = class {
3230
+ _databases = /* @__PURE__ */ new Map();
3231
+ // https://w3c.github.io/IndexedDB/#connection-queue
3232
+ _connectionQueues = /* @__PURE__ */ new Map();
3233
+ // promise chain as lightweight FIFO task queue
3234
+ // https://w3c.github.io/IndexedDB/#dom-idbfactory-cmp
3235
+ cmp(first, second) {
3236
+ validateRequiredArguments(arguments.length, 2, "IDBFactory.cmp");
3237
+ return cmp_default(first, second);
24
3238
  }
25
- }
26
- function writeSecureFile(filePath, data) {
27
- ensureConfigDir();
28
- fs__default.default.writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n", { mode: 384 });
29
- }
30
- function readJsonFile(filePath) {
31
- try {
32
- const content = fs__default.default.readFileSync(filePath, "utf-8");
33
- return JSON.parse(content);
34
- } catch {
35
- return null;
3239
+ // https://w3c.github.io/IndexedDB/#dom-idbfactory-deletedatabase
3240
+ deleteDatabase(name) {
3241
+ validateRequiredArguments(arguments.length, 1, "IDBFactory.deleteDatabase");
3242
+ const request = new FDBOpenDBRequest_default();
3243
+ request.source = null;
3244
+ queueTask(() => {
3245
+ deleteDatabase(this._databases, this._connectionQueues, name, request, (err, oldVersion) => {
3246
+ if (err) {
3247
+ request.error = new DOMException(err.message, err.name);
3248
+ request.readyState = "done";
3249
+ const event = new FakeEvent_default("error", {
3250
+ bubbles: true,
3251
+ cancelable: true
3252
+ });
3253
+ event.eventPath = [];
3254
+ request.dispatchEvent(event);
3255
+ return;
3256
+ }
3257
+ request.result = void 0;
3258
+ request.readyState = "done";
3259
+ const event2 = new FDBVersionChangeEvent_default("success", {
3260
+ newVersion: null,
3261
+ oldVersion
3262
+ });
3263
+ request.dispatchEvent(event2);
3264
+ });
3265
+ });
3266
+ return request;
36
3267
  }
37
- }
38
- function getConfig() {
39
- return readJsonFile(CONFIG_FILE);
40
- }
41
- function saveConfig(config) {
42
- writeSecureFile(CONFIG_FILE, config);
43
- }
44
- function updateConfig(updates) {
45
- const existing = getConfig() || {};
46
- saveConfig({ ...existing, ...updates });
47
- }
48
- function requireConfig() {
49
- const config = getConfig();
50
- if (!config?.baseUrl) {
51
- console.error("Not configured. Run: arbi config set-url <url>");
52
- process.exit(1);
3268
+ // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version
3269
+ open(name, version) {
3270
+ validateRequiredArguments(arguments.length, 1, "IDBFactory.open");
3271
+ if (arguments.length > 1 && version !== void 0) {
3272
+ version = enforceRange_default(version, "MAX_SAFE_INTEGER");
3273
+ }
3274
+ if (version === 0) {
3275
+ throw new TypeError("Database version cannot be 0");
3276
+ }
3277
+ const request = new FDBOpenDBRequest_default();
3278
+ request.source = null;
3279
+ queueTask(() => {
3280
+ openDatabase(this._databases, this._connectionQueues, name, version, request, (err, connection) => {
3281
+ if (err) {
3282
+ request.result = void 0;
3283
+ request.readyState = "done";
3284
+ request.error = new DOMException(err.message, err.name);
3285
+ const event = new FakeEvent_default("error", {
3286
+ bubbles: true,
3287
+ cancelable: true
3288
+ });
3289
+ event.eventPath = [];
3290
+ request.dispatchEvent(event);
3291
+ return;
3292
+ }
3293
+ request.result = connection;
3294
+ request.readyState = "done";
3295
+ const event2 = new FakeEvent_default("success");
3296
+ event2.eventPath = [];
3297
+ request.dispatchEvent(event2);
3298
+ });
3299
+ });
3300
+ return request;
53
3301
  }
54
- return config;
55
- }
56
- function getCredentials() {
57
- return readJsonFile(CREDENTIALS_FILE);
58
- }
59
- function saveCredentials(creds) {
60
- writeSecureFile(CREDENTIALS_FILE, creds);
61
- }
62
- function deleteCredentials() {
63
- try {
64
- fs__default.default.unlinkSync(CREDENTIALS_FILE);
65
- } catch {
3302
+ // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases
3303
+ databases() {
3304
+ return Promise.resolve(Array.from(this._databases.entries(), ([name, database]) => {
3305
+ const activeVersionChangeConnection = database.connections.find((connection) => connection._runningVersionchangeTransaction);
3306
+ const version = activeVersionChangeConnection ? activeVersionChangeConnection._oldVersion : database.version;
3307
+ return {
3308
+ name,
3309
+ version
3310
+ };
3311
+ }).filter(({
3312
+ version
3313
+ }) => {
3314
+ return version > 0;
3315
+ }));
66
3316
  }
67
- }
68
- function requireCredentials() {
69
- const creds = getCredentials();
70
- if (!creds) {
71
- console.error("Not logged in. Run: arbi login");
72
- process.exit(1);
3317
+ get [Symbol.toStringTag]() {
3318
+ return "IDBFactory";
73
3319
  }
74
- return creds;
75
- }
76
- var SESSION_FILE = path__default.default.join(CONFIG_DIR, "session.json");
77
- var DEFAULT_SESSION = {
78
- lastMessageExtId: null
79
3320
  };
80
- function getChatSession() {
81
- return readJsonFile(SESSION_FILE) || { ...DEFAULT_SESSION };
82
- }
83
- function saveChatSession(session) {
84
- writeSecureFile(SESSION_FILE, session);
85
- }
86
- function updateChatSession(updates) {
87
- const existing = getChatSession();
88
- saveChatSession({ ...existing, ...updates });
89
- }
90
- function clearChatSession() {
91
- saveChatSession({ ...DEFAULT_SESSION });
92
- }
3321
+ var FDBFactory_default = FDBFactory;
93
3322
 
94
- // src/commands/config-cmd.ts
95
- function registerConfigCommand(program2) {
96
- const config = program2.command("config").description("Manage CLI configuration");
97
- config.command("set-url <url>").description("Set the ARBI server URL").action((url) => {
98
- try {
99
- const parsed = new URL(url);
100
- const deploymentDomain = parsed.hostname;
101
- updateConfig({ baseUrl: url.replace(/\/+$/, ""), deploymentDomain });
102
- console.log(`Server URL: ${url}`);
103
- console.log(`Domain: ${deploymentDomain}`);
104
- } catch {
105
- console.error(`Invalid URL: ${url}`);
106
- process.exit(1);
107
- }
108
- });
109
- }
3323
+ // ../../node_modules/fake-indexeddb/build/esm/fakeIndexedDB.js
3324
+ var fakeIndexedDB = new FDBFactory_default();
3325
+ var fakeIndexedDB_default = fakeIndexedDB;
3326
+
3327
+ // ../../node_modules/fake-indexeddb/auto/index.mjs
3328
+ var globalVar = typeof window !== "undefined" ? window : typeof WorkerGlobalScope !== "undefined" ? self : typeof global !== "undefined" ? global : Function("return this;")();
3329
+ var createPropertyDescriptor = (value) => {
3330
+ return {
3331
+ value,
3332
+ enumerable: false,
3333
+ configurable: true,
3334
+ writable: true
3335
+ };
3336
+ };
3337
+ Object.defineProperties(globalVar, {
3338
+ indexedDB: createPropertyDescriptor(fakeIndexedDB_default),
3339
+ IDBCursor: createPropertyDescriptor(FDBCursor_default),
3340
+ IDBCursorWithValue: createPropertyDescriptor(FDBCursorWithValue_default),
3341
+ IDBDatabase: createPropertyDescriptor(FDBDatabase_default),
3342
+ IDBFactory: createPropertyDescriptor(FDBFactory_default),
3343
+ IDBIndex: createPropertyDescriptor(FDBIndex_default),
3344
+ IDBKeyRange: createPropertyDescriptor(FDBKeyRange_default),
3345
+ IDBObjectStore: createPropertyDescriptor(FDBObjectStore_default),
3346
+ IDBOpenDBRequest: createPropertyDescriptor(FDBOpenDBRequest_default),
3347
+ IDBRecord: createPropertyDescriptor(FDBRecord_default),
3348
+ IDBRequest: createPropertyDescriptor(FDBRequest_default),
3349
+ IDBTransaction: createPropertyDescriptor(FDBTransaction_default),
3350
+ IDBVersionChangeEvent: createPropertyDescriptor(FDBVersionChangeEvent_default)
3351
+ });
110
3352
  async function promptSelect(message, choices) {
111
3353
  return prompts.select({ message, choices });
112
3354
  }
@@ -159,8 +3401,8 @@ function registerLoginCommand(program2) {
159
3401
  signingPrivateKeyBase64: arbi.crypto.bytesToBase64(result.signingPrivateKey),
160
3402
  serverSessionKeyBase64: arbi.crypto.bytesToBase64(result.serverSessionKey)
161
3403
  });
162
- const { data: workspaces } = await arbi.fetch.GET("/api/user/workspaces");
163
- const wsList = workspaces || [];
3404
+ const { data: workspaces2 } = await arbi.fetch.GET("/api/user/workspaces");
3405
+ const wsList = workspaces2 || [];
164
3406
  console.log(`Logged in as ${email}`);
165
3407
  if (wsList.length === 0) {
166
3408
  console.log("No workspaces found.");
@@ -287,8 +3529,8 @@ Registered successfully as ${email}`);
287
3529
  signingPrivateKeyBase64: arbi.crypto.bytesToBase64(loginResult.signingPrivateKey),
288
3530
  serverSessionKeyBase64: arbi.crypto.bytesToBase64(loginResult.serverSessionKey)
289
3531
  });
290
- const { data: workspaces } = await arbi.fetch.GET("/api/user/workspaces");
291
- const wsList = workspaces || [];
3532
+ const { data: workspaces2 } = await arbi.fetch.GET("/api/user/workspaces");
3533
+ const wsList = workspaces2 || [];
292
3534
  console.log(`Logged in as ${email}`);
293
3535
  if (wsList.length === 1) {
294
3536
  updateConfig({ selectedWorkspaceId: wsList[0].external_id });
@@ -391,53 +3633,6 @@ function registerStatusCommand(program2) {
391
3633
  }
392
3634
  });
393
3635
  }
394
- async function createAuthenticatedClient() {
395
- const config = requireConfig();
396
- const creds = requireCredentials();
397
- const arbi = sdk.createArbiClient({
398
- baseUrl: config.baseUrl,
399
- deploymentDomain: config.deploymentDomain,
400
- credentials: "omit"
401
- });
402
- await arbi.crypto.initSodium();
403
- const signingPrivateKey = sdk.base64ToBytes(creds.signingPrivateKeyBase64);
404
- const loginResult = await arbi.auth.loginWithKey({
405
- email: creds.email,
406
- signingPrivateKey
407
- });
408
- saveCredentials({
409
- ...creds,
410
- serverSessionKeyBase64: arbi.crypto.bytesToBase64(loginResult.serverSessionKey)
411
- });
412
- return { arbi, loginResult };
413
- }
414
- async function selectWorkspace(arbi, workspaceId, wrappedKey, serverSessionKey) {
415
- const creds = requireCredentials();
416
- const signingPrivateKey = sdk.base64ToBytes(creds.signingPrivateKeyBase64);
417
- const ed25519PublicKey = signingPrivateKey.slice(32, 64);
418
- const encryptionKeyPair = sdk.deriveEncryptionKeypairFromSigning({
419
- publicKey: ed25519PublicKey,
420
- secretKey: signingPrivateKey
421
- });
422
- const workspaceKey = sdk.sealedBoxDecrypt(wrappedKey, encryptionKeyPair.secretKey);
423
- const header = await sdk.createWorkspaceKeyHeader(workspaceKey, serverSessionKey);
424
- arbi.session.setSelectedWorkspace(workspaceId);
425
- arbi.session.setCachedWorkspaceHeader(workspaceId, header);
426
- }
427
- async function selectWorkspaceById(arbi, workspaceId, serverSessionKey) {
428
- const { data: workspaces, error } = await arbi.fetch.GET("/api/user/workspaces");
429
- if (error || !workspaces) {
430
- throw new Error("Failed to fetch workspaces");
431
- }
432
- const ws = workspaces.find((w) => w.external_id === workspaceId);
433
- if (!ws || !ws.wrapped_key) {
434
- throw new Error(`Workspace ${workspaceId} not found or has no encryption key`);
435
- }
436
- await selectWorkspace(arbi, ws.external_id, ws.wrapped_key, serverSessionKey);
437
- return { external_id: ws.external_id, name: ws.name, wrapped_key: ws.wrapped_key };
438
- }
439
-
440
- // src/helpers.ts
441
3636
  function runAction(fn) {
442
3637
  return async () => {
443
3638
  try {
@@ -449,40 +3644,27 @@ function runAction(fn) {
449
3644
  }
450
3645
  };
451
3646
  }
452
- function requireData(result, message) {
453
- if (result.error || !result.data) {
454
- console.error(message);
455
- process.exit(1);
456
- }
457
- return result.data;
458
- }
459
- function requireOk(result, message) {
460
- if (result.error) {
461
- console.error(message);
462
- process.exit(1);
463
- }
464
- }
465
3647
  async function resolveAuth() {
466
- const config = requireConfig();
467
- const { arbi, loginResult } = await createAuthenticatedClient();
468
- return { arbi, loginResult, config };
3648
+ try {
3649
+ return await core.resolveAuth(store);
3650
+ } catch (err) {
3651
+ if (err instanceof core.ArbiError) {
3652
+ console.error(err.message);
3653
+ process.exit(1);
3654
+ }
3655
+ throw err;
3656
+ }
469
3657
  }
470
3658
  async function resolveWorkspace(workspaceOpt) {
471
- const config = requireConfig();
472
- const workspaceId = workspaceOpt || config.selectedWorkspaceId;
473
- if (!workspaceId) {
474
- console.error("No workspace selected. Run: arbi workspace select <id>");
475
- process.exit(1);
476
- }
477
- const { arbi, loginResult } = await createAuthenticatedClient();
478
- await selectWorkspaceById(arbi, workspaceId, loginResult.serverSessionKey);
479
- const accessToken = arbi.session.getState().accessToken;
480
- const workspaceKeyHeader = arbi.session.getWorkspaceKeyHeader();
481
- if (!accessToken || !workspaceKeyHeader) {
482
- console.error("Authentication error \u2014 missing token or workspace key");
483
- process.exit(1);
3659
+ try {
3660
+ return await core.resolveWorkspace(store, workspaceOpt);
3661
+ } catch (err) {
3662
+ if (err instanceof core.ArbiError) {
3663
+ console.error(err.message);
3664
+ process.exit(1);
3665
+ }
3666
+ throw err;
484
3667
  }
485
- return { arbi, loginResult, config, workspaceId, accessToken, workspaceKeyHeader };
486
3668
  }
487
3669
  function printTable(columns, rows) {
488
3670
  console.log(columns.map((c) => c.header.padEnd(c.width)).join(""));
@@ -509,10 +3691,7 @@ function registerWorkspacesCommand(program2) {
509
3691
  program2.command("workspaces").description("List workspaces").action(
510
3692
  runAction(async () => {
511
3693
  const { arbi } = await resolveAuth();
512
- const data = requireData(
513
- await arbi.fetch.GET("/api/user/workspaces"),
514
- "Failed to fetch workspaces"
515
- );
3694
+ const data = await core.workspaces.listWorkspaces(arbi);
516
3695
  if (data.length === 0) {
517
3696
  console.log("No workspaces found.");
518
3697
  return;
@@ -540,10 +3719,7 @@ function registerWorkspacesCommand(program2) {
540
3719
  workspace.command("select [id]").description("Select active workspace (interactive picker if no ID given)").action(
541
3720
  (id) => runAction(async () => {
542
3721
  const { arbi } = await resolveAuth();
543
- const data = requireData(
544
- await arbi.fetch.GET("/api/user/workspaces"),
545
- "Failed to fetch workspaces"
546
- );
3722
+ const data = await core.workspaces.listWorkspaces(arbi);
547
3723
  if (data.length === 0) {
548
3724
  console.log("No workspaces found.");
549
3725
  return;
@@ -577,11 +3753,11 @@ function registerWorkspacesCommand(program2) {
577
3753
  workspace.command("create <name>").description("Create a new workspace").option("-d, --description <text>", "Workspace description").option("--public", "Make workspace public", false).action(
578
3754
  (name, opts) => runAction(async () => {
579
3755
  const { arbi } = await resolveAuth();
580
- const data = requireData(
581
- await arbi.fetch.POST("/api/workspace/create_protected", {
582
- body: { name, description: opts.description ?? null, is_public: opts.public ?? false }
583
- }),
584
- "Failed to create workspace"
3756
+ const data = await core.workspaces.createWorkspace(
3757
+ arbi,
3758
+ name,
3759
+ opts.description,
3760
+ opts.public ?? false
585
3761
  );
586
3762
  console.log(`Created: ${data.name} (${data.external_id})`);
587
3763
  })()
@@ -589,12 +3765,7 @@ function registerWorkspacesCommand(program2) {
589
3765
  workspace.command("delete <id>").description("Delete a workspace").action(
590
3766
  (id) => runAction(async () => {
591
3767
  const { arbi } = await resolveAuth();
592
- const data = requireData(
593
- await arbi.fetch.DELETE("/api/workspace/{workspace_ext_id}", {
594
- params: { path: { workspace_ext_id: id } }
595
- }),
596
- "Failed to delete workspace"
597
- );
3768
+ const data = await core.workspaces.deleteWorkspace(arbi, id);
598
3769
  console.log(data?.detail ?? `Deleted workspace ${id}`);
599
3770
  })()
600
3771
  );
@@ -602,25 +3773,14 @@ function registerWorkspacesCommand(program2) {
602
3773
  (id, json) => runAction(async () => {
603
3774
  const body = parseJsonArg(json, `arbi workspace update wrk-123 '{"name": "New Name"}'`);
604
3775
  const { arbi } = await resolveWorkspace(id);
605
- const data = requireData(
606
- await arbi.fetch.PATCH("/api/workspace/{workspace_ext_id}", {
607
- params: { path: { workspace_ext_id: id } },
608
- body
609
- }),
610
- "Failed to update workspace"
611
- );
3776
+ const data = await core.workspaces.updateWorkspace(arbi, id, body);
612
3777
  console.log(`Updated: ${data.name} (${data.external_id})`);
613
3778
  })()
614
3779
  );
615
3780
  workspace.command("users").description("List users in the active workspace").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").action(
616
3781
  (opts) => runAction(async () => {
617
3782
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
618
- const data = requireData(
619
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/users", {
620
- params: { path: { workspace_ext_id: workspaceId } }
621
- }),
622
- "Failed to fetch workspace users"
623
- );
3783
+ const data = await core.workspaces.listWorkspaceUsers(arbi, workspaceId);
624
3784
  if (data.length === 0) {
625
3785
  console.log("No users found.");
626
3786
  return;
@@ -657,38 +3817,25 @@ function registerWorkspacesCommand(program2) {
657
3817
  (emails, opts) => runAction(async () => {
658
3818
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
659
3819
  const role = opts.role ?? "collaborator";
660
- const data = requireData(
661
- await arbi.fetch.POST("/api/workspace/{workspace_ext_id}/users", {
662
- params: { path: { workspace_ext_id: workspaceId } },
663
- body: { emails, role }
664
- }),
665
- "Failed to add users"
666
- );
3820
+ const data = await core.workspaces.addWorkspaceUsers(arbi, workspaceId, emails, role);
667
3821
  for (const u of data) console.log(`Added: ${u.user.email} as ${u.role}`);
668
3822
  })()
669
3823
  );
670
3824
  workspace.command("remove-user <user-ids...>").description("Remove users from the active workspace").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").action(
671
3825
  (userIds, opts) => runAction(async () => {
672
3826
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
673
- requireOk(
674
- await arbi.fetch.DELETE("/api/workspace/{workspace_ext_id}/users", {
675
- params: { path: { workspace_ext_id: workspaceId } },
676
- body: { users: userIds.map((id) => ({ user_ext_id: id })) }
677
- }),
678
- "Failed to remove users"
679
- );
3827
+ await core.workspaces.removeWorkspaceUsers(arbi, workspaceId, userIds);
680
3828
  console.log(`Removed ${userIds.length} user(s).`);
681
3829
  })()
682
3830
  );
683
3831
  workspace.command("set-role <role> <user-ids...>").description("Update user roles (owner, collaborator, guest)").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").action(
684
3832
  (role, userIds, opts) => runAction(async () => {
685
3833
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
686
- const data = requireData(
687
- await arbi.fetch.PATCH("/api/workspace/{workspace_ext_id}/users", {
688
- params: { path: { workspace_ext_id: workspaceId } },
689
- body: { user_ext_ids: userIds, role }
690
- }),
691
- "Failed to update roles"
3834
+ const data = await core.workspaces.setUserRole(
3835
+ arbi,
3836
+ workspaceId,
3837
+ userIds,
3838
+ role
692
3839
  );
693
3840
  for (const u of data) console.log(`Updated: ${u.user.email} \u2192 ${u.role}`);
694
3841
  })()
@@ -696,19 +3843,11 @@ function registerWorkspacesCommand(program2) {
696
3843
  workspace.command("copy <target-workspace-id> <doc-ids...>").description("Copy documents to another workspace").option("-w, --workspace <id>", "Source workspace ID (defaults to selected workspace)").action(
697
3844
  (targetId, docIds, opts) => runAction(async () => {
698
3845
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
699
- const data = requireData(
700
- await arbi.fetch.POST("/api/workspace/{workspace_ext_id}/copy", {
701
- params: { path: { workspace_ext_id: workspaceId } },
702
- body: { target_workspace_ext_id: targetId, items: docIds }
703
- }),
704
- "Failed to copy documents"
705
- );
3846
+ const data = await core.workspaces.copyDocuments(arbi, workspaceId, targetId, docIds);
706
3847
  console.log(`${data.detail} (${data.documents_copied} document(s) copied)`);
707
3848
  })()
708
3849
  );
709
3850
  }
710
-
711
- // src/commands/docs.ts
712
3851
  function formatSize(bytes) {
713
3852
  if (!bytes) return "-";
714
3853
  if (bytes < 1024) return `${bytes} B`;
@@ -716,12 +3855,7 @@ function formatSize(bytes) {
716
3855
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
717
3856
  }
718
3857
  async function fetchDocChoices(arbi, workspaceId) {
719
- const data = requireData(
720
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/documents", {
721
- params: { path: { workspace_ext_id: workspaceId } }
722
- }),
723
- "Failed to fetch documents"
724
- );
3858
+ const data = await core.documents.listDocuments(arbi, workspaceId);
725
3859
  if (data.length === 0) {
726
3860
  console.log("No documents found.");
727
3861
  process.exit(0);
@@ -736,12 +3870,7 @@ function registerDocsCommand(program2) {
736
3870
  program2.command("docs").description("List documents in the active workspace").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").action(
737
3871
  (opts) => runAction(async () => {
738
3872
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
739
- const data = requireData(
740
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/documents", {
741
- params: { path: { workspace_ext_id: workspaceId } }
742
- }),
743
- "Failed to fetch documents"
744
- );
3873
+ const data = await core.documents.listDocuments(arbi, workspaceId);
745
3874
  if (data.length === 0) {
746
3875
  console.log("No documents found.");
747
3876
  return;
@@ -768,10 +3897,7 @@ function registerDocsCommand(program2) {
768
3897
  if (selected.length === 0) return;
769
3898
  docIds = selected;
770
3899
  }
771
- const data = requireData(
772
- await arbi.fetch.GET("/api/document/", { params: { query: { external_ids: docIds } } }),
773
- "Failed to fetch documents"
774
- );
3900
+ const data = await core.documents.getDocuments(arbi, docIds);
775
3901
  console.log(JSON.stringify(data, null, 2));
776
3902
  })()
777
3903
  );
@@ -785,10 +3911,7 @@ function registerDocsCommand(program2) {
785
3911
  if (selected.length === 0) return;
786
3912
  docIds = selected;
787
3913
  }
788
- requireOk(
789
- await arbi.fetch.DELETE("/api/document/", { body: { external_ids: docIds } }),
790
- "Failed to delete documents"
791
- );
3914
+ await core.documents.deleteDocuments(arbi, docIds);
792
3915
  console.log(`Deleted ${docIds.length} document(s).`);
793
3916
  })()
794
3917
  );
@@ -796,12 +3919,9 @@ function registerDocsCommand(program2) {
796
3919
  (json) => runAction(async () => {
797
3920
  if (json) {
798
3921
  const parsed = parseJsonArg(json, `arbi doc update '[{"external_id": "doc-123", "shared": true}]'`);
799
- const body = Array.isArray(parsed) ? { documents: parsed } : parsed;
3922
+ const docs = Array.isArray(parsed) ? parsed : parsed.documents;
800
3923
  const { arbi } = await resolveWorkspace();
801
- const data = requireData(
802
- await arbi.fetch.PATCH("/api/document/", { body }),
803
- "Failed to update documents"
804
- );
3924
+ const data = await core.documents.updateDocuments(arbi, docs);
805
3925
  console.log(`Updated ${data.length} document(s).`);
806
3926
  } else {
807
3927
  const { arbi, workspaceId } = await resolveWorkspace();
@@ -825,12 +3945,9 @@ function registerDocsCommand(program2) {
825
3945
  } else {
826
3946
  value = await promptInput(`${field.charAt(0).toUpperCase() + field.slice(1)}`);
827
3947
  }
828
- const data = requireData(
829
- await arbi.fetch.PATCH("/api/document/", {
830
- body: { documents: [{ external_id: docId, [field]: value }] }
831
- }),
832
- "Failed to update document"
833
- );
3948
+ const data = await core.documents.updateDocuments(arbi, [
3949
+ { external_id: docId, [field]: value }
3950
+ ]);
834
3951
  console.log(`Updated ${data.length} document(s).`);
835
3952
  }
836
3953
  })()
@@ -838,14 +3955,7 @@ function registerDocsCommand(program2) {
838
3955
  doc.command("upload-url <urls...>").description("Upload documents from URLs").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").option("--shared", "Make documents shared", false).action(
839
3956
  (urls, opts) => runAction(async () => {
840
3957
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
841
- const data = requireData(
842
- await arbi.fetch.POST("/api/document/upload-url", {
843
- params: {
844
- query: { urls, workspace_ext_id: workspaceId, shared: opts.shared ?? false }
845
- }
846
- }),
847
- "Failed to upload from URLs"
848
- );
3958
+ const data = await core.documents.uploadUrl(arbi, urls, workspaceId, opts.shared ?? false);
849
3959
  console.log(`Uploaded: ${data.doc_ext_ids.join(", ")}`);
850
3960
  if (data.duplicates && data.duplicates.length > 0) {
851
3961
  console.log(`Duplicates: ${data.duplicates.join(", ")}`);
@@ -854,7 +3964,7 @@ function registerDocsCommand(program2) {
854
3964
  );
855
3965
  doc.command("parsed [doc-id] [stage]").description("Get parsed document content (stage: marker, subchunk, final)").action(
856
3966
  (docId, stage) => runAction(async () => {
857
- const { arbi, config, accessToken, workspaceKeyHeader, workspaceId } = await resolveWorkspace();
3967
+ const { arbi, accessToken, workspaceKeyHeader, workspaceId, config } = await resolveWorkspace();
858
3968
  if (!docId) {
859
3969
  const choices = await fetchDocChoices(arbi, workspaceId);
860
3970
  docId = await promptSearch("Select document", choices);
@@ -870,67 +3980,17 @@ function registerDocsCommand(program2) {
870
3980
  console.error(`Invalid stage: ${stage}. Must be one of: ${validStages.join(", ")}`);
871
3981
  process.exit(1);
872
3982
  }
873
- const res = await fetch(`${config.baseUrl}/api/document/${docId}/parsed-${stage}`, {
874
- headers: { Authorization: `Bearer ${accessToken}`, "workspace-key": workspaceKeyHeader }
875
- });
876
- if (!res.ok) {
877
- const body = await res.text().catch(() => "");
878
- console.error(`Failed: ${res.status} ${body}`);
879
- process.exit(1);
880
- }
881
- console.log(JSON.stringify(await res.json(), null, 2));
3983
+ const data = await core.documents.getParsedContent(
3984
+ config.baseUrl,
3985
+ accessToken,
3986
+ workspaceKeyHeader,
3987
+ docId,
3988
+ stage
3989
+ );
3990
+ console.log(JSON.stringify(data, null, 2));
882
3991
  })()
883
3992
  );
884
3993
  }
885
- var AUTH_TIMEOUT_MS = 1e4;
886
- function connectWebSocket(options) {
887
- const { baseUrl, accessToken, onMessage, onClose } = options;
888
- const url = sdk.buildWebSocketUrl(baseUrl);
889
- return new Promise((resolve, reject) => {
890
- const ws = new WebSocket(url);
891
- let authenticated = false;
892
- const timeout = setTimeout(() => {
893
- if (!authenticated) {
894
- ws.close();
895
- reject(new Error("WebSocket auth timed out"));
896
- }
897
- }, AUTH_TIMEOUT_MS);
898
- ws.addEventListener("open", () => {
899
- ws.send(sdk.createAuthMessage(accessToken));
900
- });
901
- ws.addEventListener("message", (event) => {
902
- const data = typeof event.data === "string" ? event.data : String(event.data);
903
- const msg = sdk.parseServerMessage(data);
904
- if (!msg) return;
905
- if (!authenticated) {
906
- if (sdk.isMessageType(msg, "auth_result")) {
907
- clearTimeout(timeout);
908
- if (msg.success) {
909
- authenticated = true;
910
- resolve({ close: () => ws.close() });
911
- } else {
912
- ws.close();
913
- reject(new Error(`WebSocket auth failed: ${msg.reason || "unknown"}`));
914
- }
915
- }
916
- return;
917
- }
918
- onMessage(msg);
919
- });
920
- ws.addEventListener("close", (event) => {
921
- clearTimeout(timeout);
922
- if (!authenticated) {
923
- reject(new Error(`WebSocket closed before auth (code ${event.code})`));
924
- return;
925
- }
926
- onClose?.(event.code, event.reason);
927
- });
928
- ws.addEventListener("error", () => {
929
- });
930
- });
931
- }
932
-
933
- // src/commands/upload.ts
934
3994
  function registerUploadCommand(program2) {
935
3995
  program2.command("upload <files...>").description("Upload documents to the active workspace").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").option("-W, --watch", "Watch document processing progress after upload").action(
936
3996
  (files, opts) => runAction(async () => {
@@ -946,26 +4006,15 @@ function registerUploadCommand(program2) {
946
4006
  const uploadedDocs = /* @__PURE__ */ new Map();
947
4007
  for (const filePath of files) {
948
4008
  const fileBuffer = fs__default.default.readFileSync(filePath);
949
- const fileName = path__default.default.basename(filePath);
950
- const formData = new FormData();
951
- formData.append("files", new Blob([fileBuffer]), fileName);
952
- const res = await fetch(
953
- `${config.baseUrl}/api/document/upload?workspace_ext_id=${workspaceId}`,
954
- {
955
- method: "POST",
956
- headers: {
957
- Authorization: `Bearer ${accessToken}`,
958
- "workspace-key": workspaceKeyHeader
959
- },
960
- body: formData
961
- }
4009
+ const fileName = path2__default.default.basename(filePath);
4010
+ const result = await core.documents.uploadFile(
4011
+ config.baseUrl,
4012
+ accessToken,
4013
+ workspaceKeyHeader,
4014
+ workspaceId,
4015
+ new Blob([fileBuffer]),
4016
+ fileName
962
4017
  );
963
- if (!res.ok) {
964
- const body = await res.text().catch(() => "");
965
- console.error(`Upload failed for ${fileName}: ${res.status} ${body}`);
966
- process.exit(1);
967
- }
968
- const result = await res.json();
969
4018
  console.log(`Uploaded: ${fileName} (${result.doc_ext_ids.join(", ")})`);
970
4019
  if (result.duplicates && result.duplicates.length > 0) {
971
4020
  console.log(` Duplicates: ${result.duplicates.join(", ")}`);
@@ -976,7 +4025,7 @@ function registerUploadCommand(program2) {
976
4025
  const pending = new Set(uploadedDocs.keys());
977
4026
  console.log(`
978
4027
  Watching ${pending.size} document(s)...`);
979
- const conn = await connectWebSocket({
4028
+ const conn = await core.connectWebSocket({
980
4029
  baseUrl: config.baseUrl,
981
4030
  accessToken,
982
4031
  onMessage: (msg) => {
@@ -1009,12 +4058,7 @@ function registerDownloadCommand(program2) {
1009
4058
  (docId, opts) => runAction(async () => {
1010
4059
  const { arbi, config, accessToken, workspaceKeyHeader, workspaceId } = await resolveWorkspace(opts.workspace);
1011
4060
  if (!docId) {
1012
- const data = requireData(
1013
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/documents", {
1014
- params: { path: { workspace_ext_id: workspaceId } }
1015
- }),
1016
- "Failed to fetch documents"
1017
- );
4061
+ const data = await core.documents.listDocuments(arbi, workspaceId);
1018
4062
  if (data.length === 0) {
1019
4063
  console.log("No documents found.");
1020
4064
  return;
@@ -1026,155 +4070,60 @@ function registerDownloadCommand(program2) {
1026
4070
  }));
1027
4071
  docId = await promptSearch("Select document to download", choices);
1028
4072
  }
1029
- const res = await fetch(`${config.baseUrl}/api/document/${docId}/download`, {
1030
- headers: { Authorization: `Bearer ${accessToken}`, "workspace-key": workspaceKeyHeader }
1031
- });
1032
- if (!res.ok) {
1033
- const body = await res.text().catch(() => "");
1034
- console.error(`Download failed: ${res.status} ${body}`);
1035
- process.exit(1);
1036
- }
4073
+ const res = await core.documents.downloadDocument(
4074
+ config.baseUrl,
4075
+ accessToken,
4076
+ workspaceKeyHeader,
4077
+ docId
4078
+ );
1037
4079
  let filename = `${docId}`;
1038
4080
  const disposition = res.headers.get("content-disposition");
1039
4081
  if (disposition) {
1040
4082
  const match = disposition.match(/filename[*]?=(?:UTF-8''|"?)([^";]+)/i);
1041
4083
  if (match) filename = decodeURIComponent(match[1].replace(/"/g, ""));
1042
4084
  }
1043
- const outputPath = opts.output || path__default.default.join(process.cwd(), filename);
4085
+ const outputPath = opts.output || path2__default.default.join(process.cwd(), filename);
1044
4086
  const buffer = Buffer.from(await res.arrayBuffer());
1045
4087
  fs__default.default.writeFileSync(outputPath, buffer);
1046
4088
  console.log(
1047
- `Downloaded: ${path__default.default.basename(outputPath)} (${(buffer.length / (1024 * 1024)).toFixed(1)} MB)`
4089
+ `Downloaded: ${path2__default.default.basename(outputPath)} (${(buffer.length / (1024 * 1024)).toFixed(1)} MB)`
1048
4090
  );
1049
4091
  })()
1050
4092
  );
1051
4093
  }
1052
-
1053
- // src/commands/ask.ts
1054
- function parseSSEEvents(chunk, buffer) {
1055
- const combined = buffer + chunk;
1056
- const events = [];
1057
- const parts = combined.split("\n\n");
1058
- const remaining = parts.pop() || "";
1059
- for (const part of parts) {
1060
- if (!part.trim()) continue;
1061
- let eventType = "";
1062
- let eventData = "";
1063
- for (const line of part.split("\n")) {
1064
- if (line.startsWith("event: ")) eventType = line.slice(7).trim();
1065
- else if (line.startsWith("data: ")) eventData = line.slice(6);
1066
- }
1067
- if (eventType && eventData) events.push({ event: eventType, data: eventData });
1068
- }
1069
- return { events, remaining };
1070
- }
1071
4094
  function registerAskCommand(program2) {
1072
4095
  program2.command("ask <question>").description("Ask the RAG assistant a question").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").option("-c, --config <id>", "Config ext_id to use (e.g. cfg-xxx)").option("-n, --new", "Start a new conversation (ignore previous context)").option("-v, --verbose", "Show agent steps and tool calls").action(
1073
4096
  (question, opts) => runAction(async () => {
1074
- const { arbi, config, accessToken, workspaceKeyHeader, workspaceId } = await resolveWorkspace(opts.workspace);
4097
+ const { arbi, accessToken, workspaceKeyHeader, workspaceId, config } = await resolveWorkspace(opts.workspace);
1075
4098
  const session = getChatSession();
1076
4099
  if (opts.new) {
1077
4100
  clearChatSession();
1078
4101
  session.lastMessageExtId = null;
1079
4102
  }
1080
- const docs = requireData(
1081
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/documents", {
1082
- params: { path: { workspace_ext_id: workspaceId } }
1083
- }),
1084
- "Failed to fetch workspace documents"
1085
- );
4103
+ const docs = await core.documents.listDocuments(arbi, workspaceId);
1086
4104
  const docIds = docs.map((d) => d.external_id);
1087
- const body = {
1088
- content: question,
1089
- workspace_ext_id: workspaceId,
1090
- tools: {
1091
- retrieval_chunk: {
1092
- name: "retrieval_chunk",
1093
- description: "retrieval chunk",
1094
- tool_args: { doc_ext_ids: docIds },
1095
- tool_responses: {}
1096
- },
1097
- retrieval_full_context: {
1098
- name: "retrieval_full_context",
1099
- description: "retrieval full_context",
1100
- tool_args: { doc_ext_ids: [] },
1101
- tool_responses: {}
1102
- }
1103
- }
1104
- };
1105
- if (session.lastMessageExtId) {
1106
- body.parent_message_ext_id = session.lastMessageExtId;
1107
- }
1108
- if (opts.config) {
1109
- body.config_ext_id = opts.config;
1110
- }
1111
- const res = await fetch(`${config.baseUrl}/api/assistant/query`, {
1112
- method: "POST",
1113
- headers: {
1114
- Authorization: `Bearer ${accessToken}`,
1115
- "workspace-key": workspaceKeyHeader,
1116
- "Content-Type": "application/json"
1117
- },
1118
- body: JSON.stringify(body)
4105
+ const res = await core.assistant.queryAssistant({
4106
+ baseUrl: config.baseUrl,
4107
+ accessToken,
4108
+ workspaceKeyHeader,
4109
+ workspaceId,
4110
+ question,
4111
+ docIds,
4112
+ parentMessageExtId: session.lastMessageExtId,
4113
+ configExtId: opts.config
1119
4114
  });
1120
- if (!res.ok) {
1121
- if (res.status === 503)
1122
- console.error(
1123
- "The selected LLM is not responding. Please retry or select another model."
1124
- );
1125
- else if (res.status === 401) console.error("Token has expired. Please run: arbi login");
1126
- else console.error(`Query failed: ${res.status} ${await res.text().catch(() => "")}`);
1127
- process.exit(1);
1128
- }
1129
- if (!res.body) {
1130
- console.error("No response body");
1131
- process.exit(1);
1132
- }
1133
- const reader = res.body.getReader();
1134
- const decoder = new TextDecoder("utf-8");
1135
- let sseBuffer = "";
1136
- let assistantMessageExtId = null;
1137
- const processEvents = (events) => {
1138
- for (const { event, data } of events) {
1139
- try {
1140
- if (event === "stream_start") {
1141
- const parsed = JSON.parse(data);
1142
- if (parsed.assistant_message_ext_id) {
1143
- assistantMessageExtId = parsed.assistant_message_ext_id;
1144
- }
1145
- } else if (event === "agent_step") {
1146
- if (opts.verbose) {
1147
- const parsed = JSON.parse(data);
1148
- const focus = parsed.focus || parsed.status || "";
1149
- console.error(`
4115
+ const { assistantMessageExtId } = await core.streamSSE(res, {
4116
+ onToken: (content) => process.stdout.write(content),
4117
+ onAgentStep: (data) => {
4118
+ if (opts.verbose) {
4119
+ const focus = data.focus || data.status || "";
4120
+ console.error(`
1150
4121
  [agent] ${focus}`);
1151
- }
1152
- } else if (event === "token") {
1153
- const parsed = JSON.parse(data);
1154
- if (parsed.content) process.stdout.write(parsed.content);
1155
- } else if (event === "error") {
1156
- const parsed = JSON.parse(data);
1157
- console.error(`
1158
- Error: ${parsed.message || "Unknown streaming error"}`);
1159
- }
1160
- } catch {
1161
4122
  }
1162
- }
1163
- };
1164
- while (true) {
1165
- const { done, value } = await reader.read();
1166
- if (done) break;
1167
- const { events, remaining } = parseSSEEvents(
1168
- decoder.decode(value, { stream: true }),
1169
- sseBuffer
1170
- );
1171
- sseBuffer = remaining;
1172
- processEvents(events);
1173
- }
1174
- if (sseBuffer.trim()) {
1175
- const { events } = parseSSEEvents(sseBuffer + "\n\n", "");
1176
- processEvents(events);
1177
- }
4123
+ },
4124
+ onError: (message) => console.error(`
4125
+ Error: ${message}`)
4126
+ });
1178
4127
  process.stdout.write("\n");
1179
4128
  if (assistantMessageExtId) {
1180
4129
  updateChatSession({ lastMessageExtId: assistantMessageExtId });
@@ -1190,7 +4139,7 @@ function registerWatchCommand(program2) {
1190
4139
  (opts) => runAction(async () => {
1191
4140
  const { config, accessToken, workspaceId } = await resolveWorkspace(opts.workspace);
1192
4141
  console.log(`Watching workspace ${workspaceId}... (Ctrl+C to stop)`);
1193
- await connectWebSocket({
4142
+ await core.connectWebSocket({
1194
4143
  baseUrl: config.baseUrl,
1195
4144
  accessToken,
1196
4145
  onMessage: (msg) => {
@@ -1216,17 +4165,12 @@ Connection closed (code ${code}${reason ? ": " + reason : ""})`);
1216
4165
  })()
1217
4166
  );
1218
4167
  }
1219
-
1220
- // src/commands/contacts.ts
1221
4168
  function registerContactsCommand(program2) {
1222
4169
  const contacts = program2.command("contacts").description("Manage contacts");
1223
4170
  contacts.command("list").description("List all contacts").action(
1224
4171
  runAction(async () => {
1225
4172
  const { arbi } = await resolveAuth();
1226
- const data = requireData(
1227
- await arbi.fetch.GET("/api/user/contacts"),
1228
- "Failed to fetch contacts"
1229
- );
4173
+ const data = await core.contacts.listContacts(arbi);
1230
4174
  if (data.length === 0) {
1231
4175
  console.log("No contacts found.");
1232
4176
  return;
@@ -1257,10 +4201,7 @@ function registerContactsCommand(program2) {
1257
4201
  emails = input2.split(",").map((e) => e.trim()).filter(Boolean);
1258
4202
  if (emails.length === 0) return;
1259
4203
  }
1260
- const data = requireData(
1261
- await arbi.fetch.POST("/api/user/contacts", { body: { emails } }),
1262
- "Failed to add contacts"
1263
- );
4204
+ const data = await core.contacts.addContacts(arbi, emails);
1264
4205
  for (const c of data) {
1265
4206
  console.log(`Added: ${c.email} (${c.external_id}) \u2014 ${c.status}`);
1266
4207
  }
@@ -1271,10 +4212,7 @@ function registerContactsCommand(program2) {
1271
4212
  const { arbi } = await resolveAuth();
1272
4213
  let contactIds = ids && ids.length > 0 ? ids : void 0;
1273
4214
  if (!contactIds) {
1274
- const data = requireData(
1275
- await arbi.fetch.GET("/api/user/contacts"),
1276
- "Failed to fetch contacts"
1277
- );
4215
+ const data = await core.contacts.listContacts(arbi);
1278
4216
  if (data.length === 0) {
1279
4217
  console.log("No contacts found.");
1280
4218
  return;
@@ -1292,10 +4230,7 @@ function registerContactsCommand(program2) {
1292
4230
  );
1293
4231
  if (contactIds.length === 0) return;
1294
4232
  }
1295
- requireOk(
1296
- await arbi.fetch.DELETE("/api/user/contacts", { body: { contact_ids: contactIds } }),
1297
- "Failed to remove contacts"
1298
- );
4233
+ await core.contacts.removeContacts(arbi, contactIds);
1299
4234
  console.log(`Removed ${contactIds.length} contact(s).`);
1300
4235
  })()
1301
4236
  );
@@ -1303,17 +4238,12 @@ function registerContactsCommand(program2) {
1303
4238
  await contacts.commands.find((c) => c.name() === "list").parseAsync([], { from: "user" });
1304
4239
  });
1305
4240
  }
1306
-
1307
- // src/commands/dm.ts
1308
4241
  function registerDmCommand(program2) {
1309
4242
  const dm = program2.command("dm").description("Direct messages");
1310
4243
  dm.command("list").description("List all DMs and notifications").action(
1311
4244
  runAction(async () => {
1312
4245
  const { arbi } = await resolveAuth();
1313
- const data = requireData(
1314
- await arbi.fetch.GET("/api/notifications/"),
1315
- "Failed to fetch messages"
1316
- );
4246
+ const data = await core.dm.listDMs(arbi);
1317
4247
  if (data.length === 0) {
1318
4248
  console.log("No messages found.");
1319
4249
  return;
@@ -1343,10 +4273,7 @@ function registerDmCommand(program2) {
1343
4273
  (recipient, content) => runAction(async () => {
1344
4274
  const { arbi } = await resolveAuth();
1345
4275
  if (!recipient) {
1346
- const contacts = requireData(
1347
- await arbi.fetch.GET("/api/user/contacts"),
1348
- "Failed to fetch contacts"
1349
- );
4276
+ const contacts = await core.contacts.listContacts(arbi);
1350
4277
  if (contacts.length === 0) {
1351
4278
  console.error("No contacts found. Add contacts first: arbi contacts add <email>");
1352
4279
  process.exit(1);
@@ -1369,10 +4296,7 @@ function registerDmCommand(program2) {
1369
4296
  }
1370
4297
  let recipientExtId = recipient;
1371
4298
  if (recipient.includes("@")) {
1372
- const contacts = requireData(
1373
- await arbi.fetch.GET("/api/user/contacts"),
1374
- "Failed to fetch contacts"
1375
- );
4299
+ const contacts = await core.contacts.listContacts(arbi);
1376
4300
  const match = contacts.find((c) => c.email === recipient);
1377
4301
  if (!match) {
1378
4302
  console.error(`No contact found with email: ${recipient}`);
@@ -1381,12 +4305,7 @@ function registerDmCommand(program2) {
1381
4305
  }
1382
4306
  recipientExtId = match.user?.external_id ?? match.external_id;
1383
4307
  }
1384
- const data = requireData(
1385
- await arbi.fetch.POST("/api/notifications/", {
1386
- body: { messages: [{ recipient_ext_id: recipientExtId, content }] }
1387
- }),
1388
- "Failed to send message"
1389
- );
4308
+ const data = await core.dm.sendDM(arbi, [{ recipient_ext_id: recipientExtId, content }]);
1390
4309
  for (const n of data) {
1391
4310
  console.log(`Sent: ${n.external_id} \u2192 ${n.recipient.email}`);
1392
4311
  }
@@ -1397,10 +4316,7 @@ function registerDmCommand(program2) {
1397
4316
  const { arbi } = await resolveAuth();
1398
4317
  let msgIds = ids && ids.length > 0 ? ids : void 0;
1399
4318
  if (!msgIds) {
1400
- const data2 = requireData(
1401
- await arbi.fetch.GET("/api/notifications/"),
1402
- "Failed to fetch messages"
1403
- );
4319
+ const data2 = await core.dm.listDMs(arbi);
1404
4320
  const unread = data2.filter((m) => !m.read);
1405
4321
  if (unread.length === 0) {
1406
4322
  console.log("No unread messages.");
@@ -1419,12 +4335,7 @@ function registerDmCommand(program2) {
1419
4335
  );
1420
4336
  if (msgIds.length === 0) return;
1421
4337
  }
1422
- const data = requireData(
1423
- await arbi.fetch.PATCH("/api/notifications/", {
1424
- body: { updates: msgIds.map((id) => ({ external_id: id, read: true })) }
1425
- }),
1426
- "Failed to update messages"
1427
- );
4338
+ const data = await core.dm.markRead(arbi, msgIds);
1428
4339
  console.log(`Marked ${data.length} message(s) as read.`);
1429
4340
  })()
1430
4341
  );
@@ -1433,10 +4344,7 @@ function registerDmCommand(program2) {
1433
4344
  const { arbi } = await resolveAuth();
1434
4345
  let msgIds = ids && ids.length > 0 ? ids : void 0;
1435
4346
  if (!msgIds) {
1436
- const data = requireData(
1437
- await arbi.fetch.GET("/api/notifications/"),
1438
- "Failed to fetch messages"
1439
- );
4347
+ const data = await core.dm.listDMs(arbi);
1440
4348
  if (data.length === 0) {
1441
4349
  console.log("No messages found.");
1442
4350
  return;
@@ -1454,10 +4362,7 @@ function registerDmCommand(program2) {
1454
4362
  );
1455
4363
  if (msgIds.length === 0) return;
1456
4364
  }
1457
- requireOk(
1458
- await arbi.fetch.DELETE("/api/notifications/", { body: { external_ids: msgIds } }),
1459
- "Failed to delete messages"
1460
- );
4365
+ await core.dm.deleteDMs(arbi, msgIds);
1461
4366
  console.log(`Deleted ${msgIds.length} message(s).`);
1462
4367
  })()
1463
4368
  );
@@ -1465,15 +4370,8 @@ function registerDmCommand(program2) {
1465
4370
  await dm.commands.find((c) => c.name() === "list").parseAsync([], { from: "user" });
1466
4371
  });
1467
4372
  }
1468
-
1469
- // src/commands/tags.ts
1470
4373
  async function fetchTagChoices(arbi, workspaceId) {
1471
- const data = requireData(
1472
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/tags", {
1473
- params: { path: { workspace_ext_id: workspaceId } }
1474
- }),
1475
- "Failed to fetch tags"
1476
- );
4374
+ const data = await core.tags.listTags(arbi, workspaceId);
1477
4375
  if (data.length === 0) {
1478
4376
  console.log("No tags found.");
1479
4377
  process.exit(0);
@@ -1492,12 +4390,7 @@ function registerTagsCommand(program2) {
1492
4390
  tags.command("list").description("List tags in the active workspace").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").action(
1493
4391
  (opts) => runAction(async () => {
1494
4392
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
1495
- const data = requireData(
1496
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/tags", {
1497
- params: { path: { workspace_ext_id: workspaceId } }
1498
- }),
1499
- "Failed to fetch tags"
1500
- );
4393
+ const data = await core.tags.listTags(arbi, workspaceId);
1501
4394
  if (data.length === 0) {
1502
4395
  console.log("No tags found.");
1503
4396
  return;
@@ -1541,18 +4434,13 @@ function registerTagsCommand(program2) {
1541
4434
  ]);
1542
4435
  const instruction = interactive ? opts.instruction ?? (await promptInput("Instruction (optional)", false) || null) : opts.instruction ?? null;
1543
4436
  const shared = interactive ? opts.shared || await promptConfirm("Shared?", false) : opts.shared ?? false;
1544
- const data = requireData(
1545
- await arbi.fetch.POST("/api/tag/", {
1546
- body: {
1547
- name,
1548
- workspace_ext_id: workspaceId,
1549
- tag_type: { type: tagType, options: [] },
1550
- instruction,
1551
- shared
1552
- }
1553
- }),
1554
- "Failed to create tag"
1555
- );
4437
+ const data = await core.tags.createTag(arbi, {
4438
+ name,
4439
+ workspaceId,
4440
+ tagType: { type: tagType, options: [] },
4441
+ instruction,
4442
+ shared
4443
+ });
1556
4444
  console.log(`Created: ${data.name} (${data.external_id})`);
1557
4445
  })()
1558
4446
  );
@@ -1563,12 +4451,7 @@ function registerTagsCommand(program2) {
1563
4451
  const { choices } = await fetchTagChoices(arbi, workspaceId);
1564
4452
  id = await promptSelect("Select tag to delete", choices);
1565
4453
  }
1566
- const data = requireData(
1567
- await arbi.fetch.DELETE("/api/tag/{tag_ext_id}", {
1568
- params: { path: { tag_ext_id: id } }
1569
- }),
1570
- "Failed to delete tag"
1571
- );
4454
+ const data = await core.tags.deleteTag(arbi, id);
1572
4455
  console.log(data?.detail ?? `Deleted tag ${id}`);
1573
4456
  })()
1574
4457
  );
@@ -1594,13 +4477,7 @@ function registerTagsCommand(program2) {
1594
4477
  body = { [field]: await promptInput(field.charAt(0).toUpperCase() + field.slice(1)) };
1595
4478
  }
1596
4479
  }
1597
- const data = requireData(
1598
- await arbi.fetch.PATCH("/api/tag/{tag_ext_id}", {
1599
- params: { path: { tag_ext_id: id } },
1600
- body
1601
- }),
1602
- "Failed to update tag"
1603
- );
4480
+ const data = await core.tags.updateTag(arbi, id, body);
1604
4481
  console.log(`Updated: ${data.name} (${data.external_id})`);
1605
4482
  })()
1606
4483
  );
@@ -1608,15 +4485,8 @@ function registerTagsCommand(program2) {
1608
4485
  await cmd.commands.find((c) => c.name() === "list").parseAsync([], { from: "user" });
1609
4486
  });
1610
4487
  }
1611
-
1612
- // src/commands/doctags.ts
1613
4488
  async function pickTag(arbi, workspaceId, message = "Select tag") {
1614
- const data = requireData(
1615
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/tags", {
1616
- params: { path: { workspace_ext_id: workspaceId } }
1617
- }),
1618
- "Failed to fetch tags"
1619
- );
4489
+ const data = await core.tags.listTags(arbi, workspaceId);
1620
4490
  if (data.length === 0) {
1621
4491
  console.log("No tags found.");
1622
4492
  process.exit(0);
@@ -1631,12 +4501,7 @@ async function pickTag(arbi, workspaceId, message = "Select tag") {
1631
4501
  );
1632
4502
  }
1633
4503
  async function pickDocs(arbi, workspaceId, message = "Select documents") {
1634
- const data = requireData(
1635
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/documents", {
1636
- params: { path: { workspace_ext_id: workspaceId } }
1637
- }),
1638
- "Failed to fetch documents"
1639
- );
4504
+ const data = await core.documents.listDocuments(arbi, workspaceId);
1640
4505
  if (data.length === 0) {
1641
4506
  console.log("No documents found.");
1642
4507
  process.exit(0);
@@ -1650,52 +4515,37 @@ async function pickDocs(arbi, workspaceId, message = "Select documents") {
1650
4515
  );
1651
4516
  }
1652
4517
  function registerDoctagsCommand(program2) {
1653
- const doctags = program2.command("doctags").description("Manage document tags (doctags)");
1654
- doctags.command("create [tag-id] [doc-ids...]").description("Assign a tag to documents (interactive pickers if no args)").option("-n, --note <text>", "Note for the doctag").action(
4518
+ const doctagsCmd = program2.command("doctags").description("Manage document tags (doctags)");
4519
+ doctagsCmd.command("create [tag-id] [doc-ids...]").description("Assign a tag to documents (interactive pickers if no args)").option("-n, --note <text>", "Note for the doctag").action(
1655
4520
  (tagId, docIds, opts) => runAction(async () => {
1656
4521
  const { arbi, workspaceId } = await resolveWorkspace();
1657
4522
  if (!tagId) tagId = await pickTag(arbi, workspaceId, "Select tag to assign");
1658
4523
  if (!docIds || docIds.length === 0)
1659
4524
  docIds = await pickDocs(arbi, workspaceId, "Select documents to tag");
1660
4525
  if (docIds.length === 0) return;
1661
- const data = requireData(
1662
- await arbi.fetch.POST("/api/document/doctag", {
1663
- body: { tag_ext_id: tagId, doc_ext_ids: docIds, note: opts?.note ?? null }
1664
- }),
1665
- "Failed to create doctags"
1666
- );
4526
+ const data = await core.doctags.assignDocTags(arbi, tagId, docIds, opts?.note);
1667
4527
  console.log(`Created ${data.length} doctag(s) for tag ${tagId}.`);
1668
4528
  })()
1669
4529
  );
1670
- doctags.command("delete [tag-id] [doc-ids...]").description("Remove a tag from documents (interactive pickers if no args)").action(
4530
+ doctagsCmd.command("delete [tag-id] [doc-ids...]").description("Remove a tag from documents (interactive pickers if no args)").action(
1671
4531
  (tagId, docIds) => runAction(async () => {
1672
4532
  const { arbi, workspaceId } = await resolveWorkspace();
1673
4533
  if (!tagId) tagId = await pickTag(arbi, workspaceId, "Select tag to remove");
1674
4534
  if (!docIds || docIds.length === 0)
1675
4535
  docIds = await pickDocs(arbi, workspaceId, "Select documents to untag");
1676
4536
  if (docIds.length === 0) return;
1677
- requireOk(
1678
- await arbi.fetch.DELETE("/api/document/doctag", {
1679
- body: { tag_ext_id: tagId, doc_ext_ids: docIds }
1680
- }),
1681
- "Failed to delete doctags"
1682
- );
4537
+ await core.doctags.removeDocTags(arbi, tagId, docIds);
1683
4538
  console.log(`Removed tag ${tagId} from ${docIds.length} document(s).`);
1684
4539
  })()
1685
4540
  );
1686
- doctags.command("generate").description("AI-generate doctags (interactive pickers if no flags)").option("--tags <ids>", "Comma-separated tag IDs").option("--docs <ids>", "Comma-separated document IDs").action(
4541
+ doctagsCmd.command("generate").description("AI-generate doctags (interactive pickers if no flags)").option("--tags <ids>", "Comma-separated tag IDs").option("--docs <ids>", "Comma-separated document IDs").action(
1687
4542
  (opts) => runAction(async () => {
1688
4543
  const { arbi, workspaceId } = await resolveWorkspace();
1689
4544
  let tagIds;
1690
4545
  if (opts.tags) {
1691
4546
  tagIds = opts.tags.split(",").map((s) => s.trim());
1692
4547
  } else {
1693
- const data2 = requireData(
1694
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/tags", {
1695
- params: { path: { workspace_ext_id: workspaceId } }
1696
- }),
1697
- "Failed to fetch tags"
1698
- );
4548
+ const data2 = await core.tags.listTags(arbi, workspaceId);
1699
4549
  if (data2.length === 0) {
1700
4550
  console.log("No tags found.");
1701
4551
  return;
@@ -1716,27 +4566,15 @@ function registerDoctagsCommand(program2) {
1716
4566
  docIds = await pickDocs(arbi, workspaceId, "Select documents for AI tagging");
1717
4567
  if (docIds.length === 0) return;
1718
4568
  }
1719
- const data = requireData(
1720
- await arbi.fetch.POST("/api/document/doctag/generate", {
1721
- body: { tag_ext_ids: tagIds, doc_ext_ids: docIds }
1722
- }),
1723
- "Failed to generate doctags"
1724
- );
4569
+ const data = await core.doctags.generateDocTags(arbi, tagIds, docIds);
1725
4570
  console.log(
1726
4571
  `Generating doctags for ${data.doc_ext_ids.length} doc(s) with ${data.tag_ext_ids.length} tag(s).`
1727
4572
  );
1728
4573
  })()
1729
4574
  );
1730
4575
  }
1731
-
1732
- // src/commands/conversations.ts
1733
4576
  async function pickConversation(arbi, workspaceId, message = "Select conversation") {
1734
- const data = requireData(
1735
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/conversations", {
1736
- params: { path: { workspace_ext_id: workspaceId } }
1737
- }),
1738
- "Failed to fetch conversations"
1739
- );
4577
+ const data = await core.conversations.listConversations(arbi, workspaceId);
1740
4578
  if (data.length === 0) {
1741
4579
  console.log("No conversations found.");
1742
4580
  process.exit(0);
@@ -1755,12 +4593,7 @@ function registerConversationsCommand(program2) {
1755
4593
  conv.command("list").description("List conversations in the active workspace").option("-w, --workspace <id>", "Workspace ID (defaults to selected workspace)").action(
1756
4594
  (opts) => runAction(async () => {
1757
4595
  const { arbi, workspaceId } = await resolveWorkspace(opts.workspace);
1758
- const data = requireData(
1759
- await arbi.fetch.GET("/api/workspace/{workspace_ext_id}/conversations", {
1760
- params: { path: { workspace_ext_id: workspaceId } }
1761
- }),
1762
- "Failed to fetch conversations"
1763
- );
4596
+ const data = await core.conversations.listConversations(arbi, workspaceId);
1764
4597
  if (data.length === 0) {
1765
4598
  console.log("No conversations found.");
1766
4599
  return;
@@ -1780,12 +4613,7 @@ function registerConversationsCommand(program2) {
1780
4613
  (conversationId) => runAction(async () => {
1781
4614
  const { arbi, workspaceId } = await resolveWorkspace();
1782
4615
  if (!conversationId) conversationId = await pickConversation(arbi, workspaceId);
1783
- const data = requireData(
1784
- await arbi.fetch.GET("/api/conversation/{conversation_ext_id}/threads", {
1785
- params: { path: { conversation_ext_id: conversationId } }
1786
- }),
1787
- "Failed to fetch threads"
1788
- );
4616
+ const data = await core.conversations.getConversationThreads(arbi, conversationId);
1789
4617
  console.log(JSON.stringify(data, null, 2));
1790
4618
  })()
1791
4619
  );
@@ -1798,12 +4626,7 @@ function registerConversationsCommand(program2) {
1798
4626
  workspaceId,
1799
4627
  "Select conversation to delete"
1800
4628
  );
1801
- const data = requireData(
1802
- await arbi.fetch.DELETE("/api/conversation/{conversation_ext_id}", {
1803
- params: { path: { conversation_ext_id: conversationId } }
1804
- }),
1805
- "Failed to delete conversation"
1806
- );
4629
+ const data = await core.conversations.deleteConversation(arbi, conversationId);
1807
4630
  console.log(data?.detail ?? `Deleted conversation ${conversationId}`);
1808
4631
  })()
1809
4632
  );
@@ -1812,12 +4635,7 @@ function registerConversationsCommand(program2) {
1812
4635
  const { arbi, workspaceId } = await resolveWorkspace();
1813
4636
  if (!conversationId)
1814
4637
  conversationId = await pickConversation(arbi, workspaceId, "Select conversation to share");
1815
- const data = requireData(
1816
- await arbi.fetch.POST("/api/conversation/{conversation_ext_id}/share", {
1817
- params: { path: { conversation_ext_id: conversationId } }
1818
- }),
1819
- "Failed to share conversation"
1820
- );
4638
+ const data = await core.conversations.shareConversation(arbi, conversationId);
1821
4639
  console.log(data?.detail ?? `Shared conversation ${conversationId}`);
1822
4640
  })()
1823
4641
  );
@@ -1826,13 +4644,7 @@ function registerConversationsCommand(program2) {
1826
4644
  const { arbi, workspaceId } = await resolveWorkspace();
1827
4645
  if (!conversationId) conversationId = await pickConversation(arbi, workspaceId);
1828
4646
  if (!title) title = await promptInput("New title");
1829
- const data = requireData(
1830
- await arbi.fetch.PATCH("/api/conversation/{conversation_ext_id}/title", {
1831
- params: { path: { conversation_ext_id: conversationId } },
1832
- body: { title }
1833
- }),
1834
- "Failed to update title"
1835
- );
4647
+ const data = await core.conversations.updateConversationTitle(arbi, conversationId, title);
1836
4648
  console.log(data?.detail ?? `Updated title to: ${title}`);
1837
4649
  })()
1838
4650
  );
@@ -1841,13 +4653,7 @@ function registerConversationsCommand(program2) {
1841
4653
  const { arbi, workspaceId } = await resolveWorkspace();
1842
4654
  if (!conversationId) conversationId = await pickConversation(arbi, workspaceId);
1843
4655
  if (!userId) userId = await promptInput("User ext_id or email");
1844
- const data = requireData(
1845
- await arbi.fetch.POST("/api/conversation/{conversation_ext_id}/user", {
1846
- params: { path: { conversation_ext_id: conversationId } },
1847
- body: { user_ext_id: userId }
1848
- }),
1849
- "Failed to add user to conversation"
1850
- );
4656
+ const data = await core.conversations.addConversationUser(arbi, conversationId, userId);
1851
4657
  console.log(data?.detail ?? `Added user ${userId} to conversation`);
1852
4658
  })()
1853
4659
  );
@@ -1856,37 +4662,21 @@ function registerConversationsCommand(program2) {
1856
4662
  const { arbi, workspaceId } = await resolveWorkspace();
1857
4663
  if (!conversationId) conversationId = await pickConversation(arbi, workspaceId);
1858
4664
  if (!userId) userId = await promptInput("User ext_id");
1859
- const data = requireData(
1860
- await arbi.fetch.DELETE("/api/conversation/{conversation_ext_id}/user", {
1861
- params: { path: { conversation_ext_id: conversationId } },
1862
- body: { user_ext_id: userId }
1863
- }),
1864
- "Failed to remove user from conversation"
1865
- );
4665
+ const data = await core.conversations.removeConversationUser(arbi, conversationId, userId);
1866
4666
  console.log(data?.detail ?? `Removed user ${userId} from conversation`);
1867
4667
  })()
1868
4668
  );
1869
4669
  conv.command("message <message-id>").description("Get message details").action(
1870
4670
  (messageId) => runAction(async () => {
1871
4671
  const { arbi } = await resolveWorkspace();
1872
- const data = requireData(
1873
- await arbi.fetch.GET("/api/conversation/message/{message_ext_id}", {
1874
- params: { path: { message_ext_id: messageId } }
1875
- }),
1876
- "Failed to fetch message"
1877
- );
4672
+ const data = await core.conversations.getMessage(arbi, messageId);
1878
4673
  console.log(JSON.stringify(data, null, 2));
1879
4674
  })()
1880
4675
  );
1881
4676
  conv.command("delete-message <message-id>").description("Delete a message and its descendants").action(
1882
4677
  (messageId) => runAction(async () => {
1883
4678
  const { arbi } = await resolveAuth();
1884
- const data = requireData(
1885
- await arbi.fetch.DELETE("/api/conversation/message/{message_ext_id}", {
1886
- params: { path: { message_ext_id: messageId } }
1887
- }),
1888
- "Failed to delete message"
1889
- );
4679
+ const data = await core.conversations.deleteMessage(arbi, messageId);
1890
4680
  console.log(data?.detail ?? `Deleted message ${messageId}`);
1891
4681
  })()
1892
4682
  );
@@ -1894,17 +4684,12 @@ function registerConversationsCommand(program2) {
1894
4684
  await cmd.commands.find((c) => c.name() === "list").parseAsync([], { from: "user" });
1895
4685
  });
1896
4686
  }
1897
-
1898
- // src/commands/settings.ts
1899
4687
  function registerSettingsCommand(program2) {
1900
4688
  const settings = program2.command("settings").description("Manage user settings");
1901
4689
  settings.command("get").description("Show current user settings").action(
1902
4690
  runAction(async () => {
1903
4691
  const { arbi } = await resolveAuth();
1904
- const data = requireData(
1905
- await arbi.fetch.GET("/api/user/settings"),
1906
- "Failed to fetch settings"
1907
- );
4692
+ const data = await core.settings.getSettings(arbi);
1908
4693
  console.log(JSON.stringify(data, null, 2));
1909
4694
  })
1910
4695
  );
@@ -1912,10 +4697,7 @@ function registerSettingsCommand(program2) {
1912
4697
  (json) => runAction(async () => {
1913
4698
  const body = parseJsonArg(json, `arbi settings set '{"hide_online_status": true}'`);
1914
4699
  const { arbi } = await resolveAuth();
1915
- requireOk(
1916
- await arbi.fetch.PATCH("/api/user/settings", { body }),
1917
- "Failed to update settings"
1918
- );
4700
+ await core.settings.updateSettings(arbi, body);
1919
4701
  console.log("Settings updated.");
1920
4702
  })()
1921
4703
  );
@@ -1923,8 +4705,6 @@ function registerSettingsCommand(program2) {
1923
4705
  await settings.commands.find((c) => c.name() === "get").parseAsync([], { from: "user" });
1924
4706
  });
1925
4707
  }
1926
-
1927
- // src/commands/agentconfig.ts
1928
4708
  var MODEL_SECTIONS = [
1929
4709
  "Agents",
1930
4710
  "QueryLLM",
@@ -1935,10 +4715,7 @@ var MODEL_SECTIONS = [
1935
4715
  "ArtifactLLM"
1936
4716
  ];
1937
4717
  async function pickConfig(arbi, message = "Select configuration") {
1938
- const data = requireData(
1939
- await arbi.fetch.GET("/api/configs/versions"),
1940
- "Failed to fetch config versions"
1941
- );
4718
+ const data = await core.agentconfig.listConfigs(arbi);
1942
4719
  if (data.versions.length === 0) {
1943
4720
  console.log("No saved configurations found.");
1944
4721
  process.exit(0);
@@ -1953,7 +4730,7 @@ async function pickConfig(arbi, message = "Select configuration") {
1953
4730
  );
1954
4731
  }
1955
4732
  async function fetchModels(arbi) {
1956
- const data = requireData(await arbi.fetch.GET("/api/health/models"), "Failed to fetch models");
4733
+ const data = await core.agentconfig.getModels(arbi);
1957
4734
  return data.models.map((m) => ({
1958
4735
  name: `${m.model_name} (${m.provider ?? m.api_type})`,
1959
4736
  value: m.model_name,
@@ -2075,10 +4852,7 @@ function registerAgentconfigCommand(program2) {
2075
4852
  ac.command("list").description("List saved configuration versions").action(
2076
4853
  runAction(async () => {
2077
4854
  const { arbi } = await resolveAuth();
2078
- const data = requireData(
2079
- await arbi.fetch.GET("/api/configs/versions"),
2080
- "Failed to fetch config versions"
2081
- );
4855
+ const data = await core.agentconfig.listConfigs(arbi);
2082
4856
  if (data.versions.length === 0) {
2083
4857
  console.log("No saved configurations.");
2084
4858
  return;
@@ -2109,12 +4883,7 @@ function registerAgentconfigCommand(program2) {
2109
4883
  configId = await pickConfig(arbi);
2110
4884
  }
2111
4885
  }
2112
- const data = requireData(
2113
- await arbi.fetch.GET("/api/configs/{config_ext_id}", {
2114
- params: { path: { config_ext_id: configId } }
2115
- }),
2116
- "Failed to fetch configuration"
2117
- );
4886
+ const data = await core.agentconfig.getConfig(arbi, configId);
2118
4887
  console.log(JSON.stringify(data, null, 2));
2119
4888
  })()
2120
4889
  );
@@ -2133,10 +4902,7 @@ function registerAgentconfigCommand(program2) {
2133
4902
  }
2134
4903
  if (opts?.tag) body.tag_ext_id = opts.tag;
2135
4904
  if (opts?.message) body.parent_message_ext_id = opts.message;
2136
- const data = requireData(
2137
- await arbi.fetch.POST("/api/configs/", { body }),
2138
- "Failed to save configuration"
2139
- );
4905
+ const data = await core.agentconfig.saveConfig(arbi, body);
2140
4906
  console.log(`Saved: ${data.title || "(untitled)"} (${data.external_id})`);
2141
4907
  })()
2142
4908
  );
@@ -2144,22 +4910,14 @@ function registerAgentconfigCommand(program2) {
2144
4910
  (configId) => runAction(async () => {
2145
4911
  const { arbi } = await resolveAuth();
2146
4912
  if (!configId) configId = await pickConfig(arbi, "Select configuration to delete");
2147
- const data = requireData(
2148
- await arbi.fetch.DELETE("/api/configs/{config_ext_id}", {
2149
- params: { path: { config_ext_id: configId } }
2150
- }),
2151
- "Failed to delete configuration"
2152
- );
4913
+ const data = await core.agentconfig.deleteConfig(arbi, configId);
2153
4914
  console.log(data.detail);
2154
4915
  })()
2155
4916
  );
2156
4917
  ac.command("schema").description("Show JSON schema for all configuration models").action(
2157
4918
  runAction(async () => {
2158
4919
  const { arbi } = await resolveAuth();
2159
- const data = requireData(
2160
- await arbi.fetch.GET("/api/configs/schema"),
2161
- "Failed to fetch config schema"
2162
- );
4920
+ const data = await core.agentconfig.getSchema(arbi);
2163
4921
  console.log(JSON.stringify(data, null, 2));
2164
4922
  })
2165
4923
  );
@@ -2167,16 +4925,11 @@ function registerAgentconfigCommand(program2) {
2167
4925
  await ac.commands.find((c) => c.name() === "list").parseAsync([], { from: "user" });
2168
4926
  });
2169
4927
  }
2170
-
2171
- // src/commands/health.ts
2172
4928
  function registerHealthCommand(program2) {
2173
4929
  program2.command("health").description("Show server health status").action(
2174
4930
  runAction(async () => {
2175
4931
  const { arbi } = await resolveAuth();
2176
- const data = requireData(
2177
- await arbi.fetch.GET("/api/health/"),
2178
- "Failed to fetch health status"
2179
- );
4932
+ const data = await core.health.getHealth(arbi);
2180
4933
  console.log(`Status: ${data.status}`);
2181
4934
  if (data.backend_git_hash) console.log(`Backend: ${data.backend_git_hash}`);
2182
4935
  if (data.frontend_docker_version) console.log(`Frontend: ${data.frontend_docker_version}`);
@@ -2198,10 +4951,7 @@ Models (${data.models_health.application}):`);
2198
4951
  program2.command("models").description("List available AI models").action(
2199
4952
  runAction(async () => {
2200
4953
  const { arbi } = await resolveAuth();
2201
- const data = requireData(
2202
- await arbi.fetch.GET("/api/health/models"),
2203
- "Failed to fetch models"
2204
- );
4954
+ const data = await core.health.getHealthModels(arbi);
2205
4955
  if (data.models.length === 0) {
2206
4956
  console.log("No models available.");
2207
4957
  return;
@@ -2217,6 +4967,43 @@ Models (${data.models_health.application}):`);
2217
4967
  })
2218
4968
  );
2219
4969
  }
4970
+ function findTuiEntryPoint() {
4971
+ const require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
4972
+ try {
4973
+ return require2.resolve("@arbidocs/tui");
4974
+ } catch {
4975
+ }
4976
+ try {
4977
+ const resolved = child_process.execFileSync("which", ["arbi-tui"], { encoding: "utf-8" }).trim();
4978
+ if (resolved) return resolved;
4979
+ } catch {
4980
+ }
4981
+ return null;
4982
+ }
4983
+ function registerTuiCommand(program2) {
4984
+ program2.command("tui").description("Launch interactive terminal UI").option("-w, --workspace <id>", "Workspace ID to use").allowUnknownOption(true).action((opts, cmd) => {
4985
+ const args = [];
4986
+ if (opts.workspace) {
4987
+ args.push("-w", opts.workspace);
4988
+ }
4989
+ args.push(...cmd.args);
4990
+ const entryPoint = findTuiEntryPoint();
4991
+ if (entryPoint) {
4992
+ const child = child_process.spawn(process.execPath, [entryPoint, ...args], {
4993
+ stdio: "inherit",
4994
+ env: process.env
4995
+ });
4996
+ child.on("exit", (code) => process.exit(code ?? 0));
4997
+ } else {
4998
+ console.log("arbi-tui not installed locally. Launching via npx...\n");
4999
+ const child = child_process.spawn("npx", ["--yes", "@arbidocs/tui", ...args], {
5000
+ stdio: "inherit",
5001
+ env: process.env
5002
+ });
5003
+ child.on("exit", (code) => process.exit(code ?? 0));
5004
+ }
5005
+ });
5006
+ }
2220
5007
 
2221
5008
  // src/index.ts
2222
5009
  console.debug = () => {
@@ -2247,6 +5034,7 @@ registerConversationsCommand(program);
2247
5034
  registerSettingsCommand(program);
2248
5035
  registerAgentconfigCommand(program);
2249
5036
  registerHealthCommand(program);
5037
+ registerTuiCommand(program);
2250
5038
  program.parse();
2251
5039
  //# sourceMappingURL=index.cjs.map
2252
5040
  //# sourceMappingURL=index.cjs.map