@keepkit/core 0.28.8 → 0.28.10

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.
@@ -1,3 +1,7 @@
1
+ import {
2
+ validateKeepItem
3
+ } from "./chunk-5W4QSJHV.js";
4
+
1
5
  // src/features/items/types.ts
2
6
  var KeepSyncAuthError = class extends Error {
3
7
  constructor(status, options) {
@@ -39,6 +43,12 @@ var KeepStorageParseError = class extends KeepStorageError {
39
43
  this.name = "KeepStorageParseError";
40
44
  }
41
45
  };
46
+ var KeepStorageSerializationError = class extends KeepStorageError {
47
+ constructor(options) {
48
+ super("KeepKit cannot store this value without losing data in JSON.", options);
49
+ this.name = "KeepStorageSerializationError";
50
+ }
51
+ };
42
52
  function normalizeKeepTags(tags) {
43
53
  if (!tags) return void 0;
44
54
  const normalized = [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];
@@ -110,6 +120,7 @@ var ScopedStorageAdapter = class {
110
120
  constructor(base, scope) {
111
121
  this.base = base;
112
122
  this.scope = scope;
123
+ if (base.recovery && isSameKeepScope(base.scope, scope)) this.recovery = base.recovery;
113
124
  const scopeKey = getKeepScopeKey(scope);
114
125
  this.storageKey = base.storageKey ? base.storageKey.endsWith(scopeKey) && scopeKey ? base.storageKey : `${base.storageKey}${scopeKey}` : void 0;
115
126
  if (base.getCollections && base.setCollection && base.removeCollection) {
@@ -120,8 +131,14 @@ var ScopedStorageAdapter = class {
120
131
  const collections = await getCollections();
121
132
  return this.scope ? collections.filter((collection) => isSameKeepScope(collection.scope, this.scope)) : collections;
122
133
  };
123
- this.setCollection = (collection) => setCollection({ ...collection, ...this.scope ? { scope: this.scope } : {} });
124
- this.removeCollection = (id) => removeCollection(id, this.scope);
134
+ this.setCollection = async (collection) => {
135
+ this.assertWritableScope();
136
+ await setCollection({ ...collection, ...this.scope ? { scope: this.scope } : {} });
137
+ };
138
+ this.removeCollection = async (id) => {
139
+ this.assertWritableScope();
140
+ await removeCollection(id, this.scope);
141
+ };
125
142
  }
126
143
  if (base.getCollectionMemberships && base.setCollectionMembership && base.removeCollectionMembership) {
127
144
  const getMemberships = base.getCollectionMemberships.bind(base);
@@ -131,8 +148,14 @@ var ScopedStorageAdapter = class {
131
148
  const memberships = await getMemberships();
132
149
  return this.scope ? memberships.filter((membership) => isSameKeepScope(membership.scope, this.scope)) : memberships;
133
150
  };
134
- this.setCollectionMembership = (membership) => setMembership({ ...membership, ...this.scope ? { scope: this.scope } : {} });
135
- this.removeCollectionMembership = (collectionId, itemId) => removeMembership(collectionId, itemId, this.scope);
151
+ this.setCollectionMembership = async (membership) => {
152
+ this.assertWritableScope();
153
+ await setMembership({ ...membership, ...this.scope ? { scope: this.scope } : {} });
154
+ };
155
+ this.removeCollectionMembership = async (collectionId, itemId) => {
156
+ this.assertWritableScope();
157
+ await removeMembership(collectionId, itemId, this.scope);
158
+ };
136
159
  }
137
160
  }
138
161
  async getAll() {
@@ -143,43 +166,31 @@ var ScopedStorageAdapter = class {
143
166
  await this.setMany([item]);
144
167
  }
145
168
  async setMany(items) {
146
- const current = await this.base.getAll();
169
+ this.assertWritableScope();
147
170
  const scoped = items.map((item) => ({ ...item, ...this.scope ? { scope: this.scope } : {} }));
148
- const ids = new Set(scoped.map((item) => item.id));
149
- const next = current.filter((item) => !ids.has(item.id) || !isSameKeepScope(item.scope, this.scope));
150
- await writeAll(this.base, [...next, ...scoped], this.scope);
171
+ if (this.base.setMany) await this.base.setMany(scoped);
172
+ else for (const item of scoped) await this.base.set(item);
151
173
  }
152
174
  async remove(id) {
153
- const current = await this.base.getAll();
154
- await writeAll(
155
- this.base,
156
- current.filter((item) => item.id !== id || !isSameKeepScope(item.scope, this.scope)),
157
- this.scope
158
- );
175
+ this.assertWritableScope();
176
+ await this.base.remove(id, this.scope);
159
177
  await this.removeMembershipsForItems([id]);
160
178
  }
161
179
  async removeMany(ids) {
162
- const idSet = new Set(ids);
163
- const current = await this.base.getAll();
164
- await writeAll(
165
- this.base,
166
- current.filter((item) => !idSet.has(item.id) || !isSameKeepScope(item.scope, this.scope)),
167
- this.scope
168
- );
169
- await this.removeMembershipsForItems([...idSet]);
180
+ this.assertWritableScope();
181
+ const uniqueIds = [...new Set(ids)];
182
+ if (this.base.removeMany) await this.base.removeMany(uniqueIds, this.scope);
183
+ else for (const id of uniqueIds) await this.base.remove(id, this.scope);
184
+ await this.removeMembershipsForItems(uniqueIds);
170
185
  }
171
186
  async clear() {
172
- const current = await this.base.getAll();
173
- const removedIds = current.filter((item) => isSameKeepScope(item.scope, this.scope)).map((item) => item.id);
174
- await writeAll(
175
- this.base,
176
- current.filter((item) => !isSameKeepScope(item.scope, this.scope)),
177
- this.scope
178
- );
179
- if (removedIds.length > 0) await this.removeMembershipsForItems(removedIds);
187
+ this.assertWritableScope();
188
+ const removedIds = (await this.getAll()).map((item) => item.id);
189
+ await this.removeMany(removedIds);
180
190
  await this.clearMembershipsForScope();
181
191
  }
182
192
  async merge(items) {
193
+ this.assertWritableScope();
183
194
  const scopedItems = items.map((item) => ({ ...item, ...this.scope ? { scope: this.scope } : {} }));
184
195
  const merged = mergeKeepItemLists(await this.getAll(), scopedItems);
185
196
  await this.setMany(merged);
@@ -188,6 +199,10 @@ var ScopedStorageAdapter = class {
188
199
  subscribe(listener) {
189
200
  return this.base.subscribe?.(listener) ?? (() => void 0);
190
201
  }
202
+ assertWritableScope() {
203
+ if (this.base.scope && this.scope && !isSameKeepScope(this.base.scope, this.scope))
204
+ throw new Error("Cannot write through an adapter bound to a different storage scope.");
205
+ }
191
206
  async removeMembershipsForItems(ids) {
192
207
  if (!this.base.getCollectionMemberships || !this.base.removeCollectionMembership || ids.length === 0) return;
193
208
  const removedIds = new Set(ids);
@@ -241,22 +256,1216 @@ var ScopedSyncQueueAdapter = class {
241
256
  await this.base.remove(operationIds);
242
257
  }
243
258
  };
244
- async function writeAll(base, items, scope) {
245
- const existing = await base.getAll();
246
- const desiredItems = new Set(items.filter((item) => isSameKeepScope(item.scope, scope)).map(itemStorageKey2));
247
- const removedIds = existing.filter((item) => isSameKeepScope(item.scope, scope) && !desiredItems.has(itemStorageKey2(item))).map((item) => item.id);
248
- if (removedIds.length > 0) {
249
- if (base.removeMany) await base.removeMany(removedIds, scope);
250
- else await Promise.all(removedIds.map((id) => base.remove(id, scope)));
251
- }
252
- if (base.setMany) {
253
- await base.setMany(items);
259
+
260
+ // src/features/persistence/serialization.ts
261
+ var optionalFields = /* @__PURE__ */ new Set([
262
+ "scope",
263
+ "userId",
264
+ "tenantId",
265
+ "order",
266
+ "archived",
267
+ "pinned",
268
+ "lastOpenedAt",
269
+ "collectionId",
270
+ "targetType",
271
+ "note",
272
+ "tags",
273
+ "schemaVersion",
274
+ "revision",
275
+ "metaUpdatedAt",
276
+ "status",
277
+ "statusReason",
278
+ "updatedAt",
279
+ "snapshot",
280
+ "archives",
281
+ "backups",
282
+ "scopes",
283
+ "initialized",
284
+ "capturedAt",
285
+ "issue",
286
+ "item",
287
+ "collection",
288
+ "membership",
289
+ "entity",
290
+ "baseRevision",
291
+ "attempts"
292
+ ]);
293
+ function serializeKeepStorage(value, options) {
294
+ const ancestors = /* @__PURE__ */ new Set();
295
+ const visit = (entry, inMeta) => {
296
+ if (entry === null || typeof entry === "string" || typeof entry === "boolean") return entry;
297
+ if (typeof entry === "number" && Number.isFinite(entry)) return entry;
298
+ if (typeof entry !== "object" || entry === null) throw new Error("The value cannot be represented in JSON.");
299
+ if (ancestors.has(entry)) throw new Error("Circular references cannot be represented in JSON.");
300
+ ancestors.add(entry);
301
+ try {
302
+ if (Array.isArray(entry)) {
303
+ const result2 = [];
304
+ for (let index = 0; index < entry.length; index += 1) {
305
+ const descriptor = Object.getOwnPropertyDescriptor(entry, index);
306
+ if (!descriptor) throw new Error("Sparse arrays cannot be represented in JSON.");
307
+ if (!("value" in descriptor)) throw new Error("Accessors cannot be represented in JSON.");
308
+ result2.push(visit(descriptor.value, inMeta));
309
+ }
310
+ if (Reflect.ownKeys(entry).some(
311
+ (key) => typeof key !== "string" || key !== "length" && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= entry.length)
312
+ ))
313
+ throw new Error("Extra array properties cannot be represented in JSON.");
314
+ return result2;
315
+ }
316
+ const prototype = Object.getPrototypeOf(entry);
317
+ if (prototype !== Object.prototype && prototype !== null)
318
+ throw new Error("Only plain JSON objects are supported.");
319
+ if (Reflect.ownKeys(entry).some((key) => typeof key === "symbol"))
320
+ throw new Error("Symbol keys are unsupported.");
321
+ if (Object.getOwnPropertyNames(entry).some((key) => !Object.getOwnPropertyDescriptor(entry, key)?.enumerable))
322
+ throw new Error("Non-enumerable properties cannot be represented in JSON.");
323
+ const result = {};
324
+ for (const key of Object.keys(entry).sort()) {
325
+ const descriptor = Object.getOwnPropertyDescriptor(entry, key);
326
+ if (!descriptor || !("value" in descriptor)) throw new Error("Accessors cannot be represented in JSON.");
327
+ const field = descriptor.value;
328
+ if (field === void 0 && !inMeta && optionalFields.has(key)) continue;
329
+ Object.defineProperty(result, key, { value: visit(field, inMeta || key === "meta"), enumerable: true });
330
+ }
331
+ return result;
332
+ } finally {
333
+ ancestors.delete(entry);
334
+ }
335
+ };
336
+ try {
337
+ return JSON.stringify(visit(value, false));
338
+ } catch (cause) {
339
+ throw new KeepStorageSerializationError({ ...options, cause });
340
+ }
341
+ }
342
+
343
+ // src/features/persistence/migration.ts
344
+ async function mergeKeepItems(localItems, target) {
345
+ if (target.merge) return target.merge(localItems);
346
+ const merged = mergeKeepItemLists(await target.getAll(), localItems);
347
+ await Promise.all(merged.map((item) => target.set(item)));
348
+ return merged;
349
+ }
350
+ async function migrateKeepItems(source, target) {
351
+ const localItems = await source.getAll();
352
+ const merged = await mergeKeepItems(localItems, target);
353
+ await source.clear();
354
+ return merged;
355
+ }
356
+ async function migrateLegacyCollectionMemberships(storage) {
357
+ if (!storage.getCollectionMemberships || !storage.setCollectionMembership) {
358
+ throw new TypeError("The storage adapter does not support collection memberships.");
359
+ }
360
+ const [items, memberships, collections] = await Promise.all([
361
+ storage.getAll(),
362
+ storage.getCollectionMemberships(),
363
+ storage.getCollections?.() ?? Promise.resolve([])
364
+ ]);
365
+ const existing = new Set(memberships.map(membershipKey));
366
+ const collectionIds = new Set(collections.map((collection) => collectionKey(collection.id, collection.scope)));
367
+ const missingCollectionIds = /* @__PURE__ */ new Set();
368
+ let migrated = 0;
369
+ let skipped = 0;
370
+ for (const item of items) {
371
+ if (!item.collectionId) continue;
372
+ const membership = {
373
+ collectionId: item.collectionId,
374
+ itemId: item.id,
375
+ order: item.order ?? 0,
376
+ ...item.scope ? { scope: item.scope } : {}
377
+ };
378
+ const key = membershipKey(membership);
379
+ if (!collectionIds.has(collectionKey(item.collectionId, item.scope))) {
380
+ missingCollectionIds.add(item.collectionId);
381
+ }
382
+ if (existing.has(key)) {
383
+ skipped += 1;
384
+ const { collectionId: _legacyCollectionId2, ...migratedItem2 } = item;
385
+ await storage.set(migratedItem2);
386
+ continue;
387
+ }
388
+ await storage.setCollectionMembership(membership);
389
+ existing.add(key);
390
+ migrated += 1;
391
+ const { collectionId: _legacyCollectionId, ...migratedItem } = item;
392
+ await storage.set(migratedItem);
393
+ }
394
+ return { migrated, skipped, missingCollectionIds: [...missingCollectionIds] };
395
+ }
396
+ function membershipKey(membership) {
397
+ return `${membership.scope?.tenantId ?? ""}\0${membership.scope?.userId ?? ""}\0${membership.collectionId}\0${membership.itemId}`;
398
+ }
399
+ function collectionKey(collectionId, scope) {
400
+ return `${scope?.tenantId ?? ""}\0${scope?.userId ?? ""}\0${collectionId}`;
401
+ }
402
+
403
+ // src/features/persistence/backup.ts
404
+ var KEEP_BACKUP_FORMAT = "keepkit";
405
+ var KEEP_BACKUP_VERSION = 2;
406
+ var KeepBackupParseError = class extends Error {
407
+ constructor(message, options) {
408
+ super(message);
409
+ this.name = "KeepBackupParseError";
410
+ if (options?.cause !== void 0) this.cause = options.cause;
411
+ }
412
+ };
413
+ var KeepBackupImportError = class extends Error {
414
+ constructor(message, options) {
415
+ super(message);
416
+ this.name = "KeepBackupImportError";
417
+ this.mode = options.mode;
418
+ this.imported = options.imported;
419
+ this.failed = options.failed;
420
+ this.applied = options.applied ?? { items: options.imported, collections: 0, memberships: 0 };
421
+ this.failedStage = options.failedStage ?? "items";
422
+ if (options.cause !== void 0) this.cause = options.cause;
423
+ }
424
+ };
425
+ async function exportItems(adapter) {
426
+ const items = await adapter.getAll();
427
+ const collections = await adapter.getCollections?.() ?? [];
428
+ const memberships = await adapter.getCollectionMemberships?.() ?? [];
429
+ const backup = {
430
+ format: KEEP_BACKUP_FORMAT,
431
+ version: KEEP_BACKUP_VERSION,
432
+ exportedAt: Date.now(),
433
+ items,
434
+ collections,
435
+ memberships,
436
+ scopes: collectScopes(items, collections, memberships, adapter.scope ? [adapter.scope] : [])
437
+ };
438
+ const serialized = serializeKeepStorage(backup, { operation: "getAll", storageKey: adapter.storageKey });
439
+ const json = JSON.parse(serialized);
440
+ return JSON.stringify(json, null, 2);
441
+ }
442
+ async function importItems(adapter, data, options = {}) {
443
+ const backup = parseBackup(data);
444
+ const mode = options.mode ?? "merge";
445
+ const scopes = collectScopes(backup.items, backup.collections, backup.memberships, backup.scopes);
446
+ if (adapter.scope && scopes.some((scope) => !sameScope(scope, adapter.scope))) {
447
+ throw new KeepBackupImportError("The backup contains data outside the active storage scope.", {
448
+ mode,
449
+ imported: 0,
450
+ failed: backup.items.length + backup.collections.length + backup.memberships.length,
451
+ applied: { items: 0, collections: 0, memberships: 0 },
452
+ failedStage: "validation"
453
+ });
454
+ }
455
+ if (backup.collections.length > 0 && (!adapter.getCollections || !adapter.setCollection || !adapter.removeCollection) || backup.memberships.length > 0 && (!adapter.getCollectionMemberships || !adapter.setCollectionMembership || !adapter.removeCollectionMembership)) {
456
+ throw new KeepBackupImportError("The storage adapter cannot restore collection data from this backup.", {
457
+ mode,
458
+ imported: 0,
459
+ failed: backup.items.length + backup.collections.length + backup.memberships.length,
460
+ applied: { items: 0, collections: 0, memberships: 0 },
461
+ failedStage: "validation"
462
+ });
463
+ }
464
+ const validItems = [];
465
+ let failed = 0;
466
+ for (const item of backup.items) {
467
+ if (!options.schema) {
468
+ validItems.push(item);
469
+ continue;
470
+ }
471
+ try {
472
+ validItems.push(await validateKeepItem(item, options.schema));
473
+ } catch (cause) {
474
+ options.onInvalidItem?.(cause, item);
475
+ if ((options.invalidItemPolicy ?? "error") === "drop") {
476
+ failed += 1;
477
+ continue;
478
+ }
479
+ throw cause;
480
+ }
481
+ }
482
+ const applied = { items: 0, collections: 0, memberships: 0 };
483
+ const missingCollectionIds = backup.version === 1 ? [...new Set(backup.items.flatMap((item) => item.collectionId ? [item.collectionId] : []))] : [];
484
+ try {
485
+ if (mode === "replace") {
486
+ await adapter.clear();
487
+ await restoreCollections(adapter, [], "replace", "backup", applied);
488
+ await restoreMemberships(adapter, [], "replace", applied);
489
+ }
490
+ } catch (cause) {
491
+ throw new KeepBackupImportError("KeepKit could not clear the data being replaced.", {
492
+ mode,
493
+ imported: applied.items,
494
+ failed: validItems.length + failed,
495
+ applied,
496
+ failedStage: "clear",
497
+ cause
498
+ });
499
+ }
500
+ for (const item of validItems) {
501
+ try {
502
+ if (mode === "merge") await mergeKeepItems([item], adapter);
503
+ else await adapter.set(item);
504
+ applied.items += 1;
505
+ } catch (cause) {
506
+ throw new KeepBackupImportError(`KeepKit could not restore item ${item.id}.`, {
507
+ mode,
508
+ imported: applied.items,
509
+ failed: validItems.length + failed - applied.items,
510
+ applied,
511
+ failedStage: "items",
512
+ cause
513
+ });
514
+ }
515
+ }
516
+ try {
517
+ await restoreCollections(adapter, backup.collections, mode, options.collectionNameConflict ?? "backup", applied);
518
+ } catch (cause) {
519
+ throw new KeepBackupImportError("KeepKit could not restore collection definitions.", {
520
+ mode,
521
+ imported: applied.items,
522
+ failed: validItems.length + failed - applied.items,
523
+ applied,
524
+ failedStage: "collections",
525
+ cause
526
+ });
527
+ }
528
+ try {
529
+ await restoreMemberships(adapter, backup.memberships, mode, applied);
530
+ } catch (cause) {
531
+ throw new KeepBackupImportError("KeepKit could not restore collection memberships.", {
532
+ mode,
533
+ imported: applied.items,
534
+ failed: validItems.length + failed - applied.items,
535
+ applied,
536
+ failedStage: "memberships",
537
+ cause
538
+ });
539
+ }
540
+ let items;
541
+ try {
542
+ items = await adapter.getAll();
543
+ } catch (cause) {
544
+ throw new KeepBackupImportError("KeepKit restored the backup but could not read the resulting items.", {
545
+ mode,
546
+ imported: applied.items,
547
+ failed,
548
+ applied,
549
+ failedStage: "items",
550
+ cause
551
+ });
552
+ }
553
+ return {
554
+ mode,
555
+ imported: applied.items,
556
+ failed,
557
+ total: items.length,
558
+ items,
559
+ applied,
560
+ missingCollectionIds,
561
+ includedData: backup.version === 1 ? ["items"] : ["items", "collections", "memberships"],
562
+ scopes
563
+ };
564
+ }
565
+ function parseBackup(data) {
566
+ let value = data;
567
+ if (typeof data === "string") {
568
+ try {
569
+ value = JSON.parse(data);
570
+ } catch (cause) {
571
+ throw new KeepBackupParseError("KeepKit backup is not valid JSON.", { cause });
572
+ }
573
+ }
574
+ if (!isRecord(value)) throw new KeepBackupParseError("KeepKit backup must be an object.");
575
+ if (value.format !== KEEP_BACKUP_FORMAT || value.version !== 1 && value.version !== KEEP_BACKUP_VERSION) {
576
+ throw new KeepBackupParseError("KeepKit backup format or version is unsupported.");
577
+ }
578
+ if (typeof value.exportedAt !== "number" || !Number.isFinite(value.exportedAt)) {
579
+ throw new KeepBackupParseError("KeepKit backup has an invalid export timestamp.");
580
+ }
581
+ if (!Array.isArray(value.items) || !value.items.every(isKeepItem)) {
582
+ throw new KeepBackupParseError("KeepKit backup contains invalid items.");
583
+ }
584
+ if (value.version === 1) {
585
+ return {
586
+ format: KEEP_BACKUP_FORMAT,
587
+ version: 1,
588
+ exportedAt: value.exportedAt,
589
+ items: value.items,
590
+ collections: [],
591
+ memberships: [],
592
+ scopes: []
593
+ };
594
+ }
595
+ if (!Array.isArray(value.collections) || !value.collections.every(isKeepCollectionDefinition) || !Array.isArray(value.memberships) || !value.memberships.every(isKeepCollectionMembership)) {
596
+ throw new KeepBackupParseError("KeepKit backup contains invalid collection data.");
597
+ }
598
+ if (value.scopes !== void 0 && (!Array.isArray(value.scopes) || !value.scopes.every(isSyncScope2))) {
599
+ throw new KeepBackupParseError("KeepKit backup contains invalid scope data.");
600
+ }
601
+ return value;
602
+ }
603
+ function collectScopes(items, collections, memberships, declaredScopes = []) {
604
+ const scopes = [
605
+ ...declaredScopes,
606
+ ...[...items, ...collections, ...memberships].flatMap((record) => record.scope ? [record.scope] : [])
607
+ ].filter((scope, index, all) => all.findIndex((entry) => sameScope(entry, scope)) === index);
608
+ return scopes.map((scope) => ({ ...scope }));
609
+ }
610
+ function sameScope(left, right) {
611
+ return left.userId === right?.userId && left.tenantId === right?.tenantId;
612
+ }
613
+ function isSyncScope2(value) {
614
+ return isRecord(value) && (value.userId === void 0 || typeof value.userId === "string") && (value.tenantId === void 0 || typeof value.tenantId === "string");
615
+ }
616
+ async function restoreCollections(adapter, collections, mode, conflict, applied) {
617
+ if (!adapter.getCollections || !adapter.setCollection || !adapter.removeCollection) return;
618
+ const existing = await adapter.getCollections();
619
+ if (mode === "replace") {
620
+ for (const collection of existing) await adapter.removeCollection(collection.id, collection.scope);
621
+ }
622
+ for (const collection of collections) {
623
+ const current = existing.find(
624
+ (entry) => entry.id === collection.id && sameScope(entry.scope ?? {}, collection.scope)
625
+ );
626
+ const value = mode === "merge" && conflict === "existing" && current ? { ...collection, name: current.name } : collection;
627
+ await adapter.setCollection(value);
628
+ applied.collections += 1;
629
+ }
630
+ }
631
+ async function restoreMemberships(adapter, memberships, mode, applied) {
632
+ if (!adapter.getCollectionMemberships || !adapter.setCollectionMembership || !adapter.removeCollectionMembership)
254
633
  return;
634
+ if (mode === "replace") {
635
+ const current = await adapter.getCollectionMemberships();
636
+ for (const membership of current) {
637
+ await adapter.removeCollectionMembership(membership.collectionId, membership.itemId, membership.scope);
638
+ }
639
+ }
640
+ for (const membership of memberships) {
641
+ await adapter.setCollectionMembership(membership);
642
+ applied.memberships += 1;
255
643
  }
256
- for (const item of items) await base.set(item);
257
644
  }
258
- function itemStorageKey2(item) {
259
- return JSON.stringify([item.scope?.tenantId ?? null, item.scope?.userId ?? null, item.id]);
645
+
646
+ // src/features/persistence/write-lock.ts
647
+ var writeQueues = /* @__PURE__ */ new Map();
648
+ function withLocalStorageWriteLock(key, operation, lockUnavailableError) {
649
+ const lockName = `keepkit:local-storage:${key}`;
650
+ if (typeof navigator !== "undefined" && navigator.locks) {
651
+ return navigator.locks.request(lockName, operation);
652
+ }
653
+ if (typeof window !== "undefined") return Promise.reject(lockUnavailableError);
654
+ const previous = writeQueues.get(lockName) ?? Promise.resolve();
655
+ const next = previous.catch(() => void 0).then(operation);
656
+ writeQueues.set(lockName, next);
657
+ return next.finally(() => {
658
+ if (writeQueues.get(lockName) === next) writeQueues.delete(lockName);
659
+ });
660
+ }
661
+
662
+ // src/storage/recovery-journal.ts
663
+ var RecoveryLockUnavailableError = class extends KeepStorageAccessError {
664
+ };
665
+ var LocalStorageRecoveryJournal = class {
666
+ constructor(key, storage, lockKey = key) {
667
+ this.key = key;
668
+ this.storage = storage;
669
+ this.lockKey = lockKey;
670
+ }
671
+ async read() {
672
+ let raw;
673
+ try {
674
+ raw = this.storage?.getItem(this.key) ?? null;
675
+ } catch (cause) {
676
+ throw new KeepStorageAccessError({ operation: "getAll", storageKey: this.key, cause });
677
+ }
678
+ if (raw === null) return void 0;
679
+ try {
680
+ return parseRecoveryState(JSON.parse(raw), this.key);
681
+ } catch (cause) {
682
+ if (cause instanceof KeepStorageParseError) throw cause;
683
+ throw new KeepStorageParseError({ operation: "getAll", storageKey: this.key, cause });
684
+ }
685
+ }
686
+ async write(state) {
687
+ if (!this.storage) throw new KeepStorageAccessError({ operation: "set", storageKey: this.key });
688
+ const serialized = serializeKeepStorage(state, { operation: "set", storageKey: this.key });
689
+ try {
690
+ this.storage.setItem(this.key, serialized);
691
+ } catch (cause) {
692
+ if (isRecord(cause) && (cause.name === "QuotaExceededError" || cause.code === 22)) {
693
+ throw new KeepStorageQuotaError({ operation: "set", storageKey: this.key, cause });
694
+ }
695
+ throw new KeepStorageAccessError({ operation: "set", storageKey: this.key, cause });
696
+ }
697
+ }
698
+ runExclusive(operation) {
699
+ return withLocalStorageWriteLock(
700
+ this.lockKey,
701
+ async () => {
702
+ if (typeof window !== "undefined") await nextStorageTask();
703
+ try {
704
+ return await operation();
705
+ } finally {
706
+ if (typeof window !== "undefined") await nextStorageTask();
707
+ }
708
+ },
709
+ new RecoveryLockUnavailableError({ operation: "set", storageKey: this.key })
710
+ );
711
+ }
712
+ subscribe(listener) {
713
+ if (typeof window === "undefined") return () => void 0;
714
+ const onStorage = (event) => {
715
+ if (event.key === null || event.key === this.key) listener();
716
+ };
717
+ window.addEventListener("storage", onStorage);
718
+ return () => window.removeEventListener("storage", onStorage);
719
+ }
720
+ };
721
+ function nextStorageTask() {
722
+ return new Promise((resolve) => setTimeout(resolve, 0));
723
+ }
724
+ var RecoveryJournalController = class {
725
+ constructor(options) {
726
+ this.options = options;
727
+ this.hasJournal = false;
728
+ this.listeners = /* @__PURE__ */ new Set();
729
+ this.state = {
730
+ source: options.primary ? "primary" : "fallback",
731
+ pendingOperations: 0,
732
+ snapshotStale: true,
733
+ repairSupported: true
734
+ };
735
+ }
736
+ getState() {
737
+ return { ...this.state };
738
+ }
739
+ subscribe(listener) {
740
+ this.listeners.add(listener);
741
+ this.unsubscribeExternal ?? (this.unsubscribeExternal = this.options.journal.subscribe?.(() => {
742
+ void this.refreshExternalState();
743
+ }));
744
+ return () => {
745
+ this.listeners.delete(listener);
746
+ if (this.listeners.size === 0) {
747
+ this.unsubscribeExternal?.();
748
+ this.unsubscribeExternal = void 0;
749
+ }
750
+ };
751
+ }
752
+ subscribeJournalChanges(listener) {
753
+ return this.options.journal.subscribe?.(listener) ?? (() => void 0);
754
+ }
755
+ async refreshExternalState() {
756
+ try {
757
+ const loaded = await this.options.journal.read();
758
+ if (!loaded) return;
759
+ const state = parseRecoveryState(loaded);
760
+ const next = state.version === 2 ? state : { version: 2, operations: state.operations, initialized: true };
761
+ this.validateScope(next);
762
+ this.hasJournal = true;
763
+ const pending = next.operations.length > 0;
764
+ this.state = {
765
+ source: pending || !this.options.primary ? "fallback" : "primary",
766
+ pendingOperations: next.operations.length,
767
+ snapshotStale: pending || !next.snapshot,
768
+ capturedAt: next.snapshot?.capturedAt,
769
+ repairSupported: true
770
+ };
771
+ } catch (issue) {
772
+ this.state = { ...this.state, snapshotStale: true, issue };
773
+ }
774
+ for (const listener of this.listeners) {
775
+ try {
776
+ listener();
777
+ } catch {
778
+ }
779
+ }
780
+ }
781
+ readItems() {
782
+ return this.read(
783
+ (adapter) => adapter.getAll(),
784
+ overlayItems,
785
+ (snapshot) => snapshot.items
786
+ );
787
+ }
788
+ readCollections() {
789
+ return this.read(
790
+ (adapter) => adapter.getCollections?.() ?? Promise.resolve([]),
791
+ overlayCollections,
792
+ (snapshot) => snapshot.collections
793
+ );
794
+ }
795
+ readMemberships() {
796
+ return this.read(
797
+ (adapter) => adapter.getCollectionMemberships?.() ?? Promise.resolve([]),
798
+ overlayMemberships,
799
+ (snapshot) => snapshot.memberships
800
+ );
801
+ }
802
+ write(operation, execute = (adapter) => applyRecoveryOperation(adapter, operation)) {
803
+ return this.run(async (state, locked, notify) => {
804
+ const { ready } = await this.preparePrimaryWrite(state, locked, notify);
805
+ if (ready && this.options.primary) {
806
+ let committed = false;
807
+ try {
808
+ await execute(this.options.primary);
809
+ committed = true;
810
+ } catch (cause) {
811
+ if (!this.options.shouldFallback(cause)) throw cause;
812
+ this.setSource("fallback", cause, notify);
813
+ }
814
+ if (committed) {
815
+ const canMirror = await this.refresh(state, locked, notify);
816
+ if (canMirror) await this.mirror(operation, execute, notify);
817
+ this.setSource("primary", void 0, notify);
818
+ return;
819
+ }
820
+ }
821
+ await this.commitFallback(state, operation, locked, notify);
822
+ });
823
+ }
824
+ merge(items) {
825
+ return this.run(async (state, locked, notify) => {
826
+ const { ready } = await this.preparePrimaryWrite(state, locked, notify);
827
+ const primary = this.options.primary;
828
+ if (ready && primary) {
829
+ let merged2;
830
+ try {
831
+ const candidate = primary.merge ? await primary.merge(items) : mergeKeepItemLists(await primary.getAll(), items);
832
+ if (!primary.merge) await persistKeepItems(primary, candidate);
833
+ merged2 = candidate;
834
+ } catch (cause) {
835
+ if (!this.options.shouldFallback(cause)) throw cause;
836
+ this.setSource("fallback", cause, notify);
837
+ }
838
+ if (merged2) {
839
+ const canMirror = await this.refresh(state, locked, notify);
840
+ if (canMirror) await this.mirror({ type: "setItems", items: merged2 }, void 0, notify);
841
+ this.setSource("primary", void 0, notify);
842
+ return merged2;
843
+ }
844
+ }
845
+ const current = state.snapshot?.items ?? await this.options.fallback.getAll();
846
+ const merged = mergeKeepItemLists(overlayItems(current, state.operations), items);
847
+ await this.commitFallback(state, { type: "setItems", items: merged }, locked, notify);
848
+ return merged;
849
+ });
850
+ }
851
+ inspect(options = {}) {
852
+ return this.run((state) => this.inspection(state, options.selections ?? {}));
853
+ }
854
+ apply(options) {
855
+ return this.run(async (state, locked, notify) => {
856
+ if (!locked) throw new RecoveryLockUnavailableError({ operation: "set" });
857
+ if (state.operations.length > 0)
858
+ throw new Error("Recovery is pending. Retry the saved operations before submitting another repair.");
859
+ const inspection = await this.inspection(state, options.selections);
860
+ if (inspection.token !== options.token)
861
+ throw new Error("Recovery data changed. Inspect it again before applying.");
862
+ if (inspection.issues.length > 0) throw new Error("Resolve recovery conflicts and dependencies before applying.");
863
+ if (inspection.operations.length === 0) return { status: "applied", pendingOperations: 0 };
864
+ const next = this.normalized({
865
+ ...state,
866
+ operations: [...state.operations, ...inspection.operations],
867
+ backups: [...state.backups ?? [], ...inspection.backups],
868
+ initialized: true
869
+ });
870
+ await this.options.journal.write(next);
871
+ Object.assign(state, next);
872
+ this.hasJournal = true;
873
+ this.updateState(state, notify);
874
+ const result = await this.recover(state, locked, notify);
875
+ return { status: result.ready ? "applied" : "pending", pendingOperations: state.operations.length };
876
+ });
877
+ }
878
+ retry() {
879
+ return this.run(async (state, locked, notify) => {
880
+ if (!locked) throw new RecoveryLockUnavailableError({ operation: "set" });
881
+ const result = await this.recover(state, locked, notify);
882
+ if (result.ready) await this.refresh(state, locked, notify);
883
+ return { status: result.ready ? "applied" : "pending", pendingOperations: state.operations.length };
884
+ });
885
+ }
886
+ read(read, overlay, fromSnapshot) {
887
+ return this.run(async (state, locked, notify) => {
888
+ const result = await this.recover(state, locked, notify);
889
+ if (result.ready && this.options.primary) {
890
+ if (result.snapshot) return fromSnapshot(result.snapshot);
891
+ try {
892
+ const snapshot = await this.capture(this.options.primary);
893
+ const migration = await this.bootstrap(state, snapshot, locked, notify);
894
+ if (!migration.ready) return overlay(fromSnapshot(state.snapshot ?? snapshot), state.operations);
895
+ const current = migration.snapshot ?? snapshot;
896
+ await this.refresh(state, locked, notify, current);
897
+ this.setSource("primary", void 0, notify);
898
+ return fromSnapshot(current);
899
+ } catch (cause) {
900
+ this.degraded(cause, notify);
901
+ try {
902
+ const value = await read(this.options.primary);
903
+ this.setSource("primary", void 0, notify);
904
+ return value;
905
+ } catch (readCause) {
906
+ if (!this.options.shouldFallback(readCause)) throw readCause;
907
+ this.setSource("fallback", readCause, notify);
908
+ }
909
+ }
910
+ }
911
+ const base = state.snapshot ? fromSnapshot(state.snapshot) : await read(this.options.fallback);
912
+ return overlay(base, state.operations);
913
+ });
914
+ }
915
+ async run(operation) {
916
+ const notifications = [];
917
+ const execute = async (locked) => {
918
+ const loaded = await this.options.journal.read();
919
+ this.hasJournal = loaded !== void 0;
920
+ const parsed = loaded ? parseRecoveryState(loaded) : void 0;
921
+ const state = parsed?.version === 2 ? parsed : { version: 2, operations: parsed?.operations ?? [], initialized: parsed !== void 0 };
922
+ this.validateScope(state);
923
+ this.updateState(state, (notification) => notifications.push(notification));
924
+ return operation(state, locked, (notification) => notifications.push(notification));
925
+ };
926
+ try {
927
+ try {
928
+ return await this.options.journal.runExclusive(() => execute(true));
929
+ } catch (cause) {
930
+ if (!(cause instanceof RecoveryLockUnavailableError)) throw cause;
931
+ return await execute(false);
932
+ }
933
+ } finally {
934
+ for (const notification of notifications) {
935
+ try {
936
+ notification();
937
+ } catch {
938
+ }
939
+ }
940
+ }
941
+ }
942
+ async capture(adapter) {
943
+ const snapshot = {
944
+ items: await adapter.getAll(),
945
+ collections: await adapter.getCollections?.() ?? [],
946
+ memberships: await adapter.getCollectionMemberships?.() ?? [],
947
+ capabilities: {
948
+ collections: Boolean(adapter.getCollections),
949
+ memberships: Boolean(adapter.getCollectionMemberships)
950
+ },
951
+ capturedAt: Date.now()
952
+ };
953
+ this.validateSnapshotScope(snapshot);
954
+ return snapshot;
955
+ }
956
+ async bootstrap(state, snapshot, locked, notify) {
957
+ if (state.initialized || !this.options.migrateFallbackOnEmpty || !this.options.primary || !locked)
958
+ return { ready: true, snapshot };
959
+ const legacy = await this.capture(this.options.fallback);
960
+ const operations = [];
961
+ if (snapshot.items.length === 0 && legacy.items.length > 0)
962
+ operations.push({ type: "setItems", items: legacy.items });
963
+ if (snapshot.collections.length === 0 && legacy.collections.length > 0 && this.options.primary.setCollection) {
964
+ for (const collection of legacy.collections) operations.push({ type: "setCollection", collection });
965
+ }
966
+ if (snapshot.memberships.length === 0 && legacy.memberships.length > 0 && this.options.primary.setCollectionMembership) {
967
+ for (const membership of legacy.memberships) operations.push({ type: "setMembership", membership });
968
+ }
969
+ if (operations.length === 0) return { ready: true, snapshot };
970
+ const next = this.normalized({ ...state, snapshot, archives: [legacy], operations, initialized: true });
971
+ await this.options.journal.write(next);
972
+ Object.assign(state, next);
973
+ this.hasJournal = true;
974
+ this.updateState(state, notify);
975
+ return this.recover(state, locked, notify);
976
+ }
977
+ async preparePrimaryWrite(state, locked, notify) {
978
+ const result = await this.recover(state, locked, notify);
979
+ if (!result.ready || state.initialized || !this.options.migrateFallbackOnEmpty || !this.options.primary || !locked)
980
+ return result;
981
+ let snapshot;
982
+ try {
983
+ snapshot = await this.capture(this.options.primary);
984
+ } catch (cause) {
985
+ if (!this.options.shouldFallback(cause)) throw cause;
986
+ this.degraded(cause, notify);
987
+ return { ready: false };
988
+ }
989
+ return this.bootstrap(state, snapshot, locked, notify);
990
+ }
991
+ async refresh(state, locked, notify, supplied) {
992
+ try {
993
+ if (!this.options.primary) return false;
994
+ if (!locked) throw new RecoveryLockUnavailableError({ operation: "set" });
995
+ const snapshot = supplied ?? await this.capture(this.options.primary);
996
+ const archives = state.archives ?? [await this.capture(this.options.fallback)];
997
+ const next = this.normalized({ ...state, snapshot, archives, initialized: true });
998
+ const unchanged = state.initialized && state.archives !== void 0 && state.snapshot && snapshotContent(state.snapshot) === snapshotContent(snapshot);
999
+ if (!unchanged) {
1000
+ await this.options.journal.write(next);
1001
+ Object.assign(state, next);
1002
+ this.hasJournal = true;
1003
+ }
1004
+ this.updateState(state, notify, false);
1005
+ return true;
1006
+ } catch (cause) {
1007
+ this.degraded(cause, notify);
1008
+ return state.archives !== void 0;
1009
+ }
1010
+ }
1011
+ async recover(state, locked, notify) {
1012
+ const primary = this.options.primary;
1013
+ if (!primary) {
1014
+ this.setSource("fallback", void 0, notify);
1015
+ return { ready: false };
1016
+ }
1017
+ if (state.operations.length === 0) return { ready: true };
1018
+ this.setSource("fallback", void 0, notify);
1019
+ if (!locked) return { ready: false };
1020
+ const replayedOperations = state.operations;
1021
+ let snapshot;
1022
+ try {
1023
+ for (const operation of state.operations) await applyRecoveryOperation(primary, operation);
1024
+ snapshot = await this.capture(primary);
1025
+ const archives = state.archives ?? [await this.capture(this.options.fallback)];
1026
+ const next = this.normalized({ ...state, snapshot, archives, operations: [], initialized: true });
1027
+ await this.options.journal.write(next);
1028
+ Object.assign(state, next);
1029
+ } catch (cause) {
1030
+ this.degraded(cause, notify);
1031
+ return { ready: false };
1032
+ }
1033
+ this.updateState(state, notify, false);
1034
+ for (const operation of replayedOperations) await this.mirror(operation, void 0, notify);
1035
+ this.setSource("primary", void 0, notify);
1036
+ return { ready: true, snapshot };
1037
+ }
1038
+ async commitFallback(state, operation, locked, notify) {
1039
+ if (!locked) throw new RecoveryLockUnavailableError({ operation: "set" });
1040
+ const next = this.normalized({ ...state, operations: [...state.operations, operation] });
1041
+ this.validateScope(next);
1042
+ await this.options.journal.write(next);
1043
+ this.hasJournal = true;
1044
+ Object.assign(state, next);
1045
+ this.updateState(state, notify);
1046
+ this.setSource("fallback", void 0, notify);
1047
+ notify(() => this.options.onSourceChange("fallback"));
1048
+ try {
1049
+ for (const pending of next.operations) await applyRecoveryOperation(this.options.fallback, pending);
1050
+ } catch (cause) {
1051
+ this.degraded(cause, notify);
1052
+ }
1053
+ }
1054
+ normalized(state) {
1055
+ const value = JSON.parse(serializeKeepStorage(state, { operation: "set" }));
1056
+ const parsed = parseRecoveryState(value);
1057
+ if (parsed.version !== 2) throw new KeepStorageParseError({ operation: "set" });
1058
+ return parsed;
1059
+ }
1060
+ async mirror(operation, execute, notify) {
1061
+ if (!this.options.mirrorWrites) return;
1062
+ try {
1063
+ await (execute ? execute(this.options.fallback) : applyRecoveryOperation(this.options.fallback, operation));
1064
+ } catch (cause) {
1065
+ this.degraded(cause, notify);
1066
+ }
1067
+ }
1068
+ setSource(source, error, notify) {
1069
+ if (this.state.source === source) return;
1070
+ this.state = { ...this.state, source };
1071
+ notify(() => this.options.onSourceChange(source, error));
1072
+ for (const listener of this.listeners) notify(listener);
1073
+ }
1074
+ degraded(issue, notify) {
1075
+ const identity = (error) => error instanceof Error ? `${error.name}:${error.message}` : String(error);
1076
+ if (this.state.snapshotStale && this.state.issue !== void 0 && identity(this.state.issue) === identity(issue))
1077
+ return;
1078
+ this.state = { ...this.state, snapshotStale: true, issue };
1079
+ notify(() => this.options.onError(issue));
1080
+ for (const listener of this.listeners) notify(listener);
1081
+ }
1082
+ updateState(state, notify, stale = state.operations.length > 0 || this.state.snapshotStale) {
1083
+ const next = {
1084
+ ...this.state,
1085
+ pendingOperations: state.operations.length,
1086
+ capturedAt: state.snapshot?.capturedAt,
1087
+ snapshotStale: stale
1088
+ };
1089
+ if (!stale) delete next.issue;
1090
+ if (next.pendingOperations === this.state.pendingOperations && next.capturedAt === this.state.capturedAt && next.snapshotStale === this.state.snapshotStale)
1091
+ return;
1092
+ this.state = next;
1093
+ for (const listener of this.listeners) notify(listener);
1094
+ }
1095
+ validateSnapshotScope(snapshot) {
1096
+ if (!this.options.scope) return;
1097
+ if ([...snapshot.items, ...snapshot.collections, ...snapshot.memberships].some(
1098
+ (record) => !isSameKeepScope(record.scope, this.options.scope)
1099
+ )) {
1100
+ throw new KeepStorageParseError({ operation: "getAll" });
1101
+ }
1102
+ }
1103
+ validateScope(state) {
1104
+ for (const snapshot of [state.snapshot, ...state.archives ?? []])
1105
+ if (snapshot) this.validateSnapshotScope(snapshot);
1106
+ for (const backup of state.backups ?? [])
1107
+ this.validateSnapshotScope({
1108
+ ...backup,
1109
+ capabilities: { collections: true, memberships: true },
1110
+ capturedAt: backup.exportedAt
1111
+ });
1112
+ if (!this.options.scope) return;
1113
+ if (state.backups?.some((backup) => backup.scopes?.some((scope) => !isSameKeepScope(scope, this.options.scope)))) {
1114
+ throw new KeepStorageParseError({ operation: "getAll" });
1115
+ }
1116
+ for (const operation of state.operations) {
1117
+ if (operation.type === "setItems") {
1118
+ if (operation.items.some((item) => !isSameKeepScope(item.scope, this.options.scope)))
1119
+ throw new KeepStorageParseError({ operation: "getAll" });
1120
+ } else if (operation.type === "setCollection") {
1121
+ if (!isSameKeepScope(operation.collection.scope, this.options.scope))
1122
+ throw new KeepStorageParseError({ operation: "getAll" });
1123
+ } else if (operation.type === "setMembership") {
1124
+ if (!isSameKeepScope(operation.membership.scope, this.options.scope))
1125
+ throw new KeepStorageParseError({ operation: "getAll" });
1126
+ } else if (operation.type !== "clearItems" && !isSameKeepScope(operation.scope, this.options.scope))
1127
+ throw new KeepStorageParseError({ operation: "getAll" });
1128
+ }
1129
+ }
1130
+ async inspection(state, selections) {
1131
+ const sources = [];
1132
+ const issues = [];
1133
+ for (const [id, adapter] of [
1134
+ ["primary", this.options.primary],
1135
+ ["fallback", this.options.fallback]
1136
+ ]) {
1137
+ if (!adapter) continue;
1138
+ try {
1139
+ sources.push({ id, label: id, snapshot: { ...await this.capture(adapter), capturedAt: 0 } });
1140
+ } catch (cause) {
1141
+ issues.push(`source-unavailable:${id}:${cause instanceof Error ? cause.message : String(cause)}`);
1142
+ }
1143
+ }
1144
+ if (state.snapshot)
1145
+ sources.push({
1146
+ id: "checkpoint",
1147
+ label: "checkpoint",
1148
+ snapshot: overlaySnapshot(state.snapshot, state.operations)
1149
+ });
1150
+ else if (state.operations.length > 0) {
1151
+ const fallback2 = sources.find((source) => source.id === "fallback");
1152
+ if (fallback2)
1153
+ sources.push({
1154
+ id: "checkpoint",
1155
+ label: "checkpoint",
1156
+ snapshot: overlaySnapshot(fallback2.snapshot, state.operations)
1157
+ });
1158
+ }
1159
+ for (const [index, snapshot] of (state.archives ?? []).entries())
1160
+ sources.push({ id: `legacy:${index}`, label: `legacy:${index}`, snapshot });
1161
+ const token = serializeKeepStorage({ scope: this.options.scope, state, sources }, { operation: "getAll" });
1162
+ const rows = buildRows(sources, selections, issues);
1163
+ const desired = {
1164
+ items: [],
1165
+ collections: [],
1166
+ memberships: [],
1167
+ capabilities: { collections: true, memberships: true },
1168
+ capturedAt: Date.now()
1169
+ };
1170
+ for (const row of rows) {
1171
+ const candidate = row.candidates.find((entry) => entry.source === row.selectedSource);
1172
+ if (!candidate) continue;
1173
+ if (row.kind === "item" && isRecoveryItem(candidate.value)) desired.items.push(candidate.value);
1174
+ if (row.kind === "collection" && isKeepCollectionDefinition(candidate.value))
1175
+ desired.collections.push(candidate.value);
1176
+ if (row.kind === "membership" && isKeepCollectionMembership(candidate.value))
1177
+ desired.memberships.push(candidate.value);
1178
+ }
1179
+ const removedCollections = rows.filter((row) => row.kind === "collection" && row.selectedSource === "__remove__");
1180
+ const removedItems = rows.filter((row) => row.kind === "item" && row.selectedSource === "__remove__");
1181
+ desired.items = desired.items.map((item) => {
1182
+ if (!item.collectionId) return item;
1183
+ const exists = desired.collections.some(
1184
+ (collection) => collection.id === item.collectionId && isSameKeepScope(collection.scope, item.scope)
1185
+ );
1186
+ if (exists) return item;
1187
+ if (removedCollections.some((row) => row.key === recordKey("collection", item.collectionId ?? "", item.scope))) {
1188
+ const { collectionId: _collectionId, ...unassigned } = item;
1189
+ return unassigned;
1190
+ }
1191
+ issues.push(`missing-collection:${item.id}:${item.collectionId}`);
1192
+ return item;
1193
+ });
1194
+ desired.memberships = desired.memberships.filter((membership) => {
1195
+ const itemExists = desired.items.some(
1196
+ (item) => item.id === membership.itemId && isSameKeepScope(item.scope, membership.scope)
1197
+ );
1198
+ const collectionExists = desired.collections.some(
1199
+ (collection) => collection.id === membership.collectionId && isSameKeepScope(collection.scope, membership.scope)
1200
+ );
1201
+ if (itemExists && collectionExists) return true;
1202
+ if (removedItems.some((row) => row.key === recordKey("item", membership.itemId, membership.scope)) || removedCollections.some((row) => row.key === recordKey("collection", membership.collectionId, membership.scope)))
1203
+ return false;
1204
+ issues.push(`invalid-membership:${membership.collectionId}/${membership.itemId}`);
1205
+ return true;
1206
+ });
1207
+ const current = sources.find((source) => source.id === "primary")?.snapshot ?? emptySnapshot();
1208
+ const fallback = sources.find((source) => source.id === "fallback")?.snapshot ?? emptySnapshot();
1209
+ const proposedOperations = [
1210
+ ...replacementOperations(overlaySnapshot(current, state.operations), desired),
1211
+ ...replacementOperations(overlaySnapshot(fallback, state.operations), desired)
1212
+ ];
1213
+ const uniqueOperations = /* @__PURE__ */ new Map();
1214
+ for (const operation of proposedOperations) {
1215
+ uniqueOperations.set(serializeKeepStorage(operation, { operation: "getAll" }), operation);
1216
+ }
1217
+ const operations = [...uniqueOperations.values()];
1218
+ for (const operation of operations) {
1219
+ if (operation.type === "setCollection" && !this.options.primary?.setCollection || operation.type === "removeCollection" && !this.options.primary?.removeCollection)
1220
+ issues.push("primary-collections-unavailable");
1221
+ if (operation.type === "setMembership" && !this.options.primary?.setCollectionMembership || operation.type === "removeMembership" && !this.options.primary?.removeCollectionMembership)
1222
+ issues.push("primary-memberships-unavailable");
1223
+ }
1224
+ const backups = sources.map(({ snapshot }) => ({
1225
+ format: KEEP_BACKUP_FORMAT,
1226
+ version: KEEP_BACKUP_VERSION,
1227
+ exportedAt: Date.now(),
1228
+ items: snapshot.items,
1229
+ collections: snapshot.collections,
1230
+ memberships: snapshot.memberships,
1231
+ ...this.options.scope ? { scopes: [this.options.scope] } : {}
1232
+ }));
1233
+ return { token, sources, rows, issues, operations, backups, retainedBackups: state.backups ?? [] };
1234
+ }
1235
+ };
1236
+ function emptySnapshot() {
1237
+ return {
1238
+ items: [],
1239
+ collections: [],
1240
+ memberships: [],
1241
+ capabilities: { collections: false, memberships: false },
1242
+ capturedAt: 0
1243
+ };
1244
+ }
1245
+ function snapshotContent(snapshot) {
1246
+ const { capturedAt: _capturedAt, ...data } = snapshot;
1247
+ return serializeKeepStorage(data, { operation: "set" });
1248
+ }
1249
+ function overlaySnapshot(snapshot, operations) {
1250
+ return {
1251
+ ...snapshot,
1252
+ items: overlayItems(snapshot.items, operations),
1253
+ collections: overlayCollections(snapshot.collections, operations),
1254
+ memberships: overlayMemberships(snapshot.memberships, operations)
1255
+ };
1256
+ }
1257
+ function recordKey(kind, id, scope) {
1258
+ return JSON.stringify([kind, scope?.tenantId ?? null, scope?.userId ?? null, id]);
1259
+ }
1260
+ function buildRows(sources, selections, issues) {
1261
+ const byKey = /* @__PURE__ */ new Map();
1262
+ for (const source of sources) {
1263
+ for (const [kind, records] of [
1264
+ ["item", source.snapshot.items],
1265
+ ["collection", source.snapshot.collections],
1266
+ ["membership", source.snapshot.memberships]
1267
+ ]) {
1268
+ for (const value of records) {
1269
+ const id = "id" in value ? value.id : `${value.collectionId}/${value.itemId}`;
1270
+ const identity = "id" in value ? value.id : JSON.stringify([value.collectionId, value.itemId]);
1271
+ const key = recordKey(kind, identity, value.scope);
1272
+ const row = byKey.get(key) ?? { key, kind, id, candidates: [], conflict: false };
1273
+ row.candidates.push({ source: source.id, value });
1274
+ byKey.set(key, row);
1275
+ }
1276
+ }
1277
+ }
1278
+ for (const row of byKey.values()) {
1279
+ const values = new Set(row.candidates.map(({ value }) => serializeKeepStorage(value, { operation: "getAll" })));
1280
+ row.conflict = values.size > 1;
1281
+ row.selectedSource = selections[row.key] ?? (row.conflict ? void 0 : row.candidates[0]?.source);
1282
+ if (row.selectedSource !== void 0 && row.selectedSource !== "__remove__" && !row.candidates.some(({ source }) => source === row.selectedSource))
1283
+ issues.push(`invalid-selection:${row.id}`);
1284
+ if (row.conflict && row.selectedSource === void 0) issues.push(`unresolved-conflict:${row.id}`);
1285
+ }
1286
+ for (const key of Object.keys(selections)) if (!byKey.has(key)) issues.push("invalid-selection");
1287
+ return [...byKey.values()];
1288
+ }
1289
+ function replacementOperations(current, desired) {
1290
+ const operations = [];
1291
+ for (const membership of current.memberships)
1292
+ if (!desired.memberships.some(
1293
+ (entry) => entry.collectionId === membership.collectionId && entry.itemId === membership.itemId && isSameKeepScope(entry.scope, membership.scope)
1294
+ ))
1295
+ operations.push({
1296
+ type: "removeMembership",
1297
+ collectionId: membership.collectionId,
1298
+ itemId: membership.itemId,
1299
+ scope: membership.scope
1300
+ });
1301
+ for (const collection of current.collections)
1302
+ if (!desired.collections.some((entry) => entry.id === collection.id && isSameKeepScope(entry.scope, collection.scope)))
1303
+ operations.push({ type: "removeCollection", id: collection.id, scope: collection.scope });
1304
+ for (const item of current.items)
1305
+ if (!desired.items.some((entry) => entry.id === item.id && isSameKeepScope(entry.scope, item.scope)))
1306
+ operations.push({ type: "removeItems", ids: [item.id], scope: item.scope });
1307
+ for (const collection of desired.collections) {
1308
+ const existing = current.collections.find(
1309
+ (entry) => entry.id === collection.id && isSameKeepScope(entry.scope, collection.scope)
1310
+ );
1311
+ if (!sameRecoveryRecord(existing, collection)) operations.push({ type: "setCollection", collection });
1312
+ }
1313
+ const isChangedItem = (item) => {
1314
+ const existing = current.items.find((entry) => entry.id === item.id && isSameKeepScope(entry.scope, item.scope));
1315
+ return !sameRecoveryRecord(existing, item);
1316
+ };
1317
+ const changedItems = desired.items.filter(isChangedItem);
1318
+ if (changedItems.length > 0) operations.push({ type: "setItems", items: changedItems });
1319
+ for (const membership of desired.memberships) {
1320
+ const existing = current.memberships.find(
1321
+ (entry) => entry.collectionId === membership.collectionId && entry.itemId === membership.itemId && isSameKeepScope(entry.scope, membership.scope)
1322
+ );
1323
+ if (!sameRecoveryRecord(existing, membership)) operations.push({ type: "setMembership", membership });
1324
+ }
1325
+ return operations;
1326
+ }
1327
+ function sameRecoveryRecord(left, right) {
1328
+ if (left === void 0) return false;
1329
+ return serializeKeepStorage(left, { operation: "getAll" }) === serializeKeepStorage(right, { operation: "getAll" });
1330
+ }
1331
+ async function applyRecoveryOperation(adapter, operation) {
1332
+ switch (operation.type) {
1333
+ case "setItems":
1334
+ return persistKeepItems(adapter, operation.items);
1335
+ case "removeItems":
1336
+ if (adapter.removeMany) return adapter.removeMany(operation.ids, operation.scope);
1337
+ for (const id of operation.ids) await adapter.remove(id, operation.scope);
1338
+ return;
1339
+ case "clearItems":
1340
+ return adapter.clear();
1341
+ case "setCollection":
1342
+ if (!adapter.setCollection) throw new Error("Collection storage is unavailable.");
1343
+ return adapter.setCollection(operation.collection);
1344
+ case "removeCollection":
1345
+ if (!adapter.removeCollection) throw new Error("Collection storage is unavailable.");
1346
+ return adapter.removeCollection(operation.id, operation.scope);
1347
+ case "setMembership":
1348
+ if (!adapter.setCollectionMembership) throw new Error("Collection membership storage is unavailable.");
1349
+ return adapter.setCollectionMembership(operation.membership);
1350
+ case "removeMembership":
1351
+ if (!adapter.removeCollectionMembership) throw new Error("Collection membership storage is unavailable.");
1352
+ return adapter.removeCollectionMembership(operation.collectionId, operation.itemId, operation.scope);
1353
+ }
1354
+ }
1355
+ function overlayItems(items, operations) {
1356
+ let next = items;
1357
+ for (const operation of operations) {
1358
+ if (operation.type === "clearItems") next = [];
1359
+ if (operation.type === "setItems") {
1360
+ for (const item of operation.items) {
1361
+ next = [...next.filter((entry) => entry.id !== item.id || !isSameKeepScope(entry.scope, item.scope)), item];
1362
+ }
1363
+ }
1364
+ if (operation.type === "removeItems") {
1365
+ next = next.filter(
1366
+ (item) => !operation.ids.includes(item.id) || operation.scope !== void 0 && !isSameKeepScope(item.scope, operation.scope)
1367
+ );
1368
+ }
1369
+ }
1370
+ return next;
1371
+ }
1372
+ function overlayCollections(collections, operations) {
1373
+ let next = collections;
1374
+ for (const operation of operations) {
1375
+ if (operation.type === "setCollection") {
1376
+ const collection = operation.collection;
1377
+ next = [
1378
+ ...next.filter((entry) => entry.id !== collection.id || !isSameKeepScope(entry.scope, collection.scope)),
1379
+ collection
1380
+ ];
1381
+ }
1382
+ if (operation.type === "removeCollection") {
1383
+ next = next.filter((entry) => entry.id !== operation.id || !isSameKeepScope(entry.scope, operation.scope));
1384
+ }
1385
+ }
1386
+ return next;
1387
+ }
1388
+ function overlayMemberships(memberships, operations) {
1389
+ let next = memberships;
1390
+ for (const operation of operations) {
1391
+ if (operation.type === "clearItems") next = [];
1392
+ if (operation.type === "setMembership") {
1393
+ const membership = operation.membership;
1394
+ next = [
1395
+ ...next.filter(
1396
+ (entry) => entry.collectionId !== membership.collectionId || entry.itemId !== membership.itemId || !isSameKeepScope(entry.scope, membership.scope)
1397
+ ),
1398
+ membership
1399
+ ];
1400
+ }
1401
+ if (operation.type === "removeMembership") {
1402
+ next = next.filter(
1403
+ (entry) => entry.collectionId !== operation.collectionId || entry.itemId !== operation.itemId || !isSameKeepScope(entry.scope, operation.scope)
1404
+ );
1405
+ }
1406
+ if (operation.type === "removeCollection") {
1407
+ next = next.filter(
1408
+ (entry) => entry.collectionId !== operation.id || !isSameKeepScope(entry.scope, operation.scope)
1409
+ );
1410
+ }
1411
+ if (operation.type === "removeItems") {
1412
+ next = next.filter(
1413
+ (entry) => !operation.ids.includes(entry.itemId) || operation.scope !== void 0 && !isSameKeepScope(entry.scope, operation.scope)
1414
+ );
1415
+ }
1416
+ }
1417
+ return next;
1418
+ }
1419
+ function parseRecoveryState(value, storageKey) {
1420
+ if (!isRecord(value) || value.version !== 1 && value.version !== 2 || !Array.isArray(value.operations) || !value.operations.every(isRecoveryOperation)) {
1421
+ throw new KeepStorageParseError({ operation: "getAll", storageKey });
1422
+ }
1423
+ if (value.version === 1) return { version: 1, operations: value.operations };
1424
+ if (value.snapshot !== void 0 && !isRecoverySnapshot(value.snapshot) || value.archives !== void 0 && (!Array.isArray(value.archives) || !value.archives.every(isRecoverySnapshot)) || value.backups !== void 0 && (!Array.isArray(value.backups) || !value.backups.every(isRecoveryBackup)) || value.initialized !== void 0 && typeof value.initialized !== "boolean")
1425
+ throw new KeepStorageParseError({ operation: "getAll", storageKey });
1426
+ return {
1427
+ version: 2,
1428
+ operations: value.operations,
1429
+ ...isRecoverySnapshot(value.snapshot) ? { snapshot: value.snapshot } : {},
1430
+ ...Array.isArray(value.archives) && value.archives.every(isRecoverySnapshot) ? { archives: value.archives } : {},
1431
+ ...Array.isArray(value.backups) && value.backups.every(isRecoveryBackup) ? { backups: value.backups } : {},
1432
+ ...typeof value.initialized === "boolean" ? { initialized: value.initialized } : {}
1433
+ };
1434
+ }
1435
+ function isRecoveryItem(value) {
1436
+ return isKeepItem(value);
1437
+ }
1438
+ function isRecoverySnapshot(value) {
1439
+ return isRecord(value) && isKeepItemArray(value.items) && Array.isArray(value.collections) && value.collections.every(isKeepCollectionDefinition) && Array.isArray(value.memberships) && value.memberships.every(isKeepCollectionMembership) && isRecord(value.capabilities) && typeof value.capabilities.collections === "boolean" && typeof value.capabilities.memberships === "boolean" && typeof value.capturedAt === "number" && Number.isFinite(value.capturedAt);
1440
+ }
1441
+ function isRecoveryBackup(value) {
1442
+ return isRecord(value) && value.format === KEEP_BACKUP_FORMAT && value.version === KEEP_BACKUP_VERSION && typeof value.exportedAt === "number" && Number.isFinite(value.exportedAt) && isKeepItemArray(value.items) && Array.isArray(value.collections) && value.collections.every(isKeepCollectionDefinition) && Array.isArray(value.memberships) && value.memberships.every(isKeepCollectionMembership) && (value.scopes === void 0 || Array.isArray(value.scopes) && value.scopes.every(isRecoveryScope));
1443
+ }
1444
+ function isRecoveryScope(value) {
1445
+ return isRecord(value) && (value.userId === void 0 || typeof value.userId === "string") && (value.tenantId === void 0 || typeof value.tenantId === "string");
1446
+ }
1447
+ function isRecoveryOperation(value) {
1448
+ if (!isRecord(value)) return false;
1449
+ if (value.scope !== void 0 && (!isRecord(value.scope) || value.scope.userId !== void 0 && typeof value.scope.userId !== "string" || value.scope.tenantId !== void 0 && typeof value.scope.tenantId !== "string"))
1450
+ return false;
1451
+ switch (value.type) {
1452
+ case "setItems":
1453
+ return isKeepItemArray(value.items);
1454
+ case "removeItems":
1455
+ return Array.isArray(value.ids) && value.ids.every((id) => typeof id === "string");
1456
+ case "clearItems":
1457
+ return true;
1458
+ case "setCollection":
1459
+ return isKeepCollectionDefinition(value.collection);
1460
+ case "removeCollection":
1461
+ return typeof value.id === "string";
1462
+ case "setMembership":
1463
+ return isKeepCollectionMembership(value.membership);
1464
+ case "removeMembership":
1465
+ return typeof value.collectionId === "string" && typeof value.itemId === "string";
1466
+ default:
1467
+ return false;
1468
+ }
260
1469
  }
261
1470
 
262
1471
  // src/storage/sync.ts
@@ -285,7 +1494,8 @@ var LocalStorageSyncQueueAdapter = class {
285
1494
  }
286
1495
  async setMany(operations) {
287
1496
  if (!this.storage) return;
288
- this.storage.setItem(this.key, JSON.stringify(operations));
1497
+ const serialized = serializeKeepStorage(operations, { operation: "set", storageKey: this.key });
1498
+ this.storage.setItem(this.key, serialized);
289
1499
  }
290
1500
  async remove(operationIds) {
291
1501
  const ids = new Set(operationIds);
@@ -430,6 +1640,13 @@ var SyncStorageAdapter = class {
430
1640
  this.retryDelayMs = Math.max(0, options.retryDelayMs ?? 0);
431
1641
  this.retryBackoff = Math.max(1, options.retryBackoff ?? 2);
432
1642
  this.storageKey = this.local.storageKey;
1643
+ const localRecovery = this.local.recovery;
1644
+ if (localRecovery && isSameKeepScope(this.local.scope, this.scope ?? this.local.scope)) {
1645
+ this.recovery = {
1646
+ getState: () => ({ ...localRecovery.getState(), repairSupported: false }),
1647
+ subscribe: (listener) => localRecovery.subscribe(listener)
1648
+ };
1649
+ }
433
1650
  if (this.local.getCollections && this.local.setCollection && this.local.removeCollection) {
434
1651
  const getCollections = this.local.getCollections.bind(this.local);
435
1652
  const setCollection = this.local.setCollection.bind(this.local);
@@ -437,7 +1654,7 @@ var SyncStorageAdapter = class {
437
1654
  this.getCollections = async () => {
438
1655
  const collections = await getCollections();
439
1656
  const scope = this.scope;
440
- return scope ? collections.filter((collection) => sameScope(collection.scope, scope)) : collections;
1657
+ return scope ? collections.filter((collection) => sameScope2(collection.scope, scope)) : collections;
441
1658
  };
442
1659
  this.setCollection = async (collection) => {
443
1660
  const scopedCollection = { ...collection, ...this.scope ? { scope: this.scope } : {} };
@@ -491,7 +1708,7 @@ var SyncStorageAdapter = class {
491
1708
  this.getCollectionMemberships = async () => {
492
1709
  const memberships = await getMemberships();
493
1710
  const scope = this.scope;
494
- return scope ? memberships.filter((membership) => sameScope(membership.scope, scope)) : memberships;
1711
+ return scope ? memberships.filter((membership) => sameScope2(membership.scope, scope)) : memberships;
495
1712
  };
496
1713
  this.setCollectionMembership = async (membership) => {
497
1714
  const scoped = { ...membership, ...this.scope ? { scope: this.scope } : {} };
@@ -537,7 +1754,7 @@ var SyncStorageAdapter = class {
537
1754
  const items = await this.local.getAll();
538
1755
  const scope = this.scope;
539
1756
  if (!scope) return items;
540
- return items.filter((item) => sameScope(item.scope, scope));
1757
+ return items.filter((item) => sameScope2(item.scope, scope));
541
1758
  }
542
1759
  async set(item) {
543
1760
  const scopedItem = this.applyScope(item);
@@ -988,7 +2205,7 @@ var SyncStorageAdapter = class {
988
2205
  const localById = new Map(localItems.map((item) => [item.id, item]));
989
2206
  const remoteById = /* @__PURE__ */ new Map();
990
2207
  for (const item of remoteItems) {
991
- if (this.scope && item.scope && !sameScope(item.scope, this.scope)) continue;
2208
+ if (this.scope && item.scope && !sameScope2(item.scope, this.scope)) continue;
992
2209
  if (pendingIds.has(item.id)) continue;
993
2210
  const previous = remoteById.get(item.id);
994
2211
  remoteById.set(item.id, previous ? mergeKeepItemLists([item], [previous])[0] ?? item : item);
@@ -1011,7 +2228,7 @@ var SyncStorageAdapter = class {
1011
2228
  const localCollections = await this.local.getCollections();
1012
2229
  const pendingIds = new Set(this.queueItems.filter(isCollectionSyncOperation).map((operation) => operation.id));
1013
2230
  const remoteById = new Map(
1014
- remoteCollections.filter((collection) => !this.scope || !collection.scope || sameScope(collection.scope, this.scope)).map((collection) => [collection.id, collection])
2231
+ remoteCollections.filter((collection) => !this.scope || !collection.scope || sameScope2(collection.scope, this.scope)).map((collection) => [collection.id, collection])
1015
2232
  );
1016
2233
  for (const collection of remoteById.values()) {
1017
2234
  if (pendingIds.has(collection.id)) continue;
@@ -1019,7 +2236,7 @@ var SyncStorageAdapter = class {
1019
2236
  }
1020
2237
  for (const collection of localCollections) {
1021
2238
  if (pendingIds.has(collection.id) || remoteById.has(collection.id)) continue;
1022
- if (this.scope && !sameScope(collection.scope, this.scope)) continue;
2239
+ if (this.scope && !sameScope2(collection.scope, this.scope)) continue;
1023
2240
  await this.local.removeCollection(collection.id, this.scope);
1024
2241
  }
1025
2242
  this.notifyDataListeners();
@@ -1032,7 +2249,7 @@ var SyncStorageAdapter = class {
1032
2249
  const collectionIds = new Set((await this.getCollections()).map((collection) => collection.id));
1033
2250
  const remoteById = new Map(
1034
2251
  remoteMemberships.filter((membership) => {
1035
- if (this.scope && membership.scope && !sameScope(membership.scope, this.scope)) return false;
2252
+ if (this.scope && membership.scope && !sameScope2(membership.scope, this.scope)) return false;
1036
2253
  if (!itemIds.has(membership.itemId)) return false;
1037
2254
  return collectionIds.has(membership.collectionId);
1038
2255
  }).map((membership) => [getMembershipId(membership.collectionId, membership.itemId), membership])
@@ -1045,7 +2262,7 @@ var SyncStorageAdapter = class {
1045
2262
  for (const membership of localMemberships) {
1046
2263
  const id = getMembershipId(membership.collectionId, membership.itemId);
1047
2264
  if (pendingIds.has(id) || remoteById.has(id)) continue;
1048
- if (this.scope && !sameScope(membership.scope, this.scope)) continue;
2265
+ if (this.scope && !sameScope2(membership.scope, this.scope)) continue;
1049
2266
  await this.local.removeCollectionMembership(membership.collectionId, membership.itemId, this.scope);
1050
2267
  }
1051
2268
  this.notifyDataListeners();
@@ -1144,7 +2361,7 @@ function getScopeKey(options) {
1144
2361
  if (!scope) return "";
1145
2362
  return `:${encodeURIComponent(scope.tenantId ?? "_")}:${encodeURIComponent(scope.userId ?? "_")}`;
1146
2363
  }
1147
- function sameScope(left, right) {
2364
+ function sameScope2(left, right) {
1148
2365
  return left?.userId === right.userId && left?.tenantId === right.tenantId;
1149
2366
  }
1150
2367
  function wait(delay) {
@@ -1172,17 +2389,39 @@ var FallbackStorageAdapter = class {
1172
2389
  constructor(options) {
1173
2390
  this.active = "primary";
1174
2391
  this.listeners = /* @__PURE__ */ new Set();
1175
- this.primary = options.primary;
1176
- this.fallback = options.fallback;
2392
+ const scope = options.scope ?? options.primary?.scope ?? options.fallback.scope;
2393
+ const primary = options.primary && scope ? createScopedStorageAdapter(options.primary, scope) : options.primary;
2394
+ this.fallback = scope ? createScopedStorageAdapter(options.fallback, scope) : options.fallback;
2395
+ this.primary = primary ?? this.fallback;
1177
2396
  this.shouldFallback = options.shouldFallback ?? isRecoverableStorageError;
1178
2397
  this.onFallback = options.onFallback;
1179
2398
  this.migrateFallbackOnEmpty = options.migrateFallbackOnEmpty ?? false;
1180
2399
  this.mirrorWrites = options.mirrorWrites ?? false;
1181
- this.storageKey = options.fallback.storageKey ?? options.primary.storageKey;
1182
- this.scope = options.primary.scope ?? options.fallback.scope;
2400
+ this.storageKey = options.fallback.storageKey ?? options.primary?.storageKey;
2401
+ this.scope = scope;
2402
+ if (!options.primary) this.active = "fallback";
2403
+ if (options.recoveryJournal) {
2404
+ this.journalController = new RecoveryJournalController({
2405
+ primary,
2406
+ fallback: this.fallback,
2407
+ scope: this.scope,
2408
+ migrateFallbackOnEmpty: this.migrateFallbackOnEmpty,
2409
+ journal: options.recoveryJournal,
2410
+ shouldFallback: this.shouldFallback,
2411
+ mirrorWrites: this.mirrorWrites,
2412
+ onSourceChange: (source, error) => {
2413
+ this.active = source;
2414
+ if (source === "fallback" && error !== void 0) this.reportFallbackError(error);
2415
+ this.notifyListeners();
2416
+ },
2417
+ onError: (error) => this.reportFallbackError(error)
2418
+ });
2419
+ this.recovery = this.journalController;
2420
+ }
1183
2421
  if (this.primary.getCollections && this.primary.setCollection && this.primary.removeCollection && this.fallback.getCollections && this.fallback.setCollection && this.fallback.removeCollection) {
1184
2422
  const fallbackGetCollections = this.fallback.getCollections.bind(this.fallback);
1185
2423
  this.getCollections = async () => {
2424
+ if (this.journalController) return this.journalController.readCollections();
1186
2425
  const collections = await this.execute((adapter) => {
1187
2426
  if (!adapter.getCollections) throw new Error("Collection storage is unavailable.");
1188
2427
  return adapter.getCollections();
@@ -1194,18 +2433,22 @@ var FallbackStorageAdapter = class {
1194
2433
  }
1195
2434
  return collections;
1196
2435
  };
1197
- this.setCollection = (collection) => this.executeWrite((adapter) => {
1198
- if (!adapter.setCollection) throw new Error("Collection storage is unavailable.");
1199
- return adapter.setCollection(collection);
1200
- });
1201
- this.removeCollection = (id, scope) => this.executeWrite((adapter) => {
2436
+ this.setCollection = (collection) => {
2437
+ const value = this.scope ? { ...collection, scope: this.scope } : collection;
2438
+ return this.journalController?.write({ type: "setCollection", collection: value }) ?? this.executeWrite((adapter) => {
2439
+ if (!adapter.setCollection) throw new Error("Collection storage is unavailable.");
2440
+ return adapter.setCollection(value);
2441
+ });
2442
+ };
2443
+ this.removeCollection = (id, scope2 = this.scope) => this.journalController?.write({ type: "removeCollection", id, scope: scope2 }) ?? this.executeWrite((adapter) => {
1202
2444
  if (!adapter.removeCollection) throw new Error("Collection storage is unavailable.");
1203
- return adapter.removeCollection(id, scope);
2445
+ return adapter.removeCollection(id, scope2);
1204
2446
  });
1205
2447
  }
1206
2448
  if (this.primary.getCollectionMemberships && this.primary.setCollectionMembership && this.primary.removeCollectionMembership && this.fallback.getCollectionMemberships && this.fallback.setCollectionMembership && this.fallback.removeCollectionMembership) {
1207
2449
  const fallbackGetMemberships = this.fallback.getCollectionMemberships.bind(this.fallback);
1208
2450
  this.getCollectionMemberships = async () => {
2451
+ if (this.journalController) return this.journalController.readMemberships();
1209
2452
  const memberships = await this.execute(
1210
2453
  (adapter) => adapter.getCollectionMemberships?.() ?? Promise.resolve([])
1211
2454
  );
@@ -1214,9 +2457,12 @@ var FallbackStorageAdapter = class {
1214
2457
  for (const membership of fallbackMemberships) await this.setCollectionMembership?.(membership);
1215
2458
  return fallbackMemberships;
1216
2459
  };
1217
- this.setCollectionMembership = (membership) => this.executeWrite((adapter) => adapter.setCollectionMembership?.(membership) ?? Promise.resolve());
1218
- this.removeCollectionMembership = (collectionId, itemId, scope) => this.executeWrite(
1219
- (adapter) => adapter.removeCollectionMembership?.(collectionId, itemId, scope) ?? Promise.resolve()
2460
+ this.setCollectionMembership = (membership) => {
2461
+ const value = this.scope ? { ...membership, scope: this.scope } : membership;
2462
+ return this.journalController?.write({ type: "setMembership", membership: value }) ?? this.executeWrite((adapter) => adapter.setCollectionMembership?.(value) ?? Promise.resolve());
2463
+ };
2464
+ this.removeCollectionMembership = (collectionId, itemId, scope2 = this.scope) => this.journalController?.write({ type: "removeMembership", collectionId, itemId, scope: scope2 }) ?? this.executeWrite(
2465
+ (adapter) => adapter.removeCollectionMembership?.(collectionId, itemId, scope2) ?? Promise.resolve()
1220
2466
  );
1221
2467
  }
1222
2468
  }
@@ -1227,25 +2473,39 @@ var FallbackStorageAdapter = class {
1227
2473
  return this.readAll();
1228
2474
  }
1229
2475
  set(item) {
2476
+ if (this.scope) item = { ...item, scope: this.scope };
2477
+ if (this.journalController)
2478
+ return this.journalController.write({ type: "setItems", items: [item] }, (adapter) => adapter.set(item));
1230
2479
  return this.executeWrite((adapter) => adapter.set(item));
1231
2480
  }
1232
2481
  setMany(items) {
2482
+ if (this.scope) items = items.map((item) => ({ ...item, scope: this.scope }));
2483
+ if (this.journalController) return this.journalController.write({ type: "setItems", items });
1233
2484
  return this.executeWrite(
1234
2485
  (adapter) => adapter.setMany ? adapter.setMany(items) : Promise.all(items.map((item) => adapter.set(item))).then(() => void 0)
1235
2486
  );
1236
2487
  }
1237
- remove(id, scope) {
2488
+ remove(id, scope = this.scope) {
2489
+ if (this.journalController)
2490
+ return this.journalController.write(
2491
+ { type: "removeItems", ids: [id], scope },
2492
+ (adapter) => adapter.remove(id, scope)
2493
+ );
1238
2494
  return this.executeWrite((adapter) => adapter.remove(id, scope));
1239
2495
  }
1240
- removeMany(ids, scope) {
2496
+ removeMany(ids, scope = this.scope) {
2497
+ if (this.journalController) return this.journalController.write({ type: "removeItems", ids, scope });
1241
2498
  return this.executeWrite(
1242
2499
  (adapter) => adapter.removeMany ? adapter.removeMany(ids, scope) : Promise.all(ids.map((id) => adapter.remove(id, scope))).then(() => void 0)
1243
2500
  );
1244
2501
  }
1245
2502
  clear() {
2503
+ if (this.journalController) return this.journalController.write({ type: "clearItems" });
1246
2504
  return this.executeWrite((adapter) => adapter.clear());
1247
2505
  }
1248
2506
  merge(localItems) {
2507
+ if (this.scope) localItems = localItems.map((item) => ({ ...item, scope: this.scope }));
2508
+ if (this.journalController) return this.journalController.merge(localItems);
1249
2509
  return this.execute(async (adapter) => {
1250
2510
  const merged = adapter.merge ? await adapter.merge(localItems) : mergeKeepItemLists(await adapter.getAll(), localItems);
1251
2511
  if (!adapter.merge) await persistKeepItems(adapter, merged);
@@ -1265,13 +2525,16 @@ var FallbackStorageAdapter = class {
1265
2525
  };
1266
2526
  const unsubscribePrimary = this.primary.subscribe?.(() => notify("primary"));
1267
2527
  const unsubscribeFallback = this.fallback.subscribe?.(() => notify("fallback"));
2528
+ const unsubscribeJournal = this.journalController?.subscribeJournalChanges(listener);
1268
2529
  return () => {
1269
2530
  this.listeners.delete(listener);
1270
2531
  unsubscribePrimary?.();
1271
2532
  unsubscribeFallback?.();
2533
+ unsubscribeJournal?.();
1272
2534
  };
1273
2535
  }
1274
2536
  async readAll() {
2537
+ if (this.journalController) return this.journalController.readItems();
1275
2538
  if (this.active === "fallback") return this.fallback.getAll();
1276
2539
  let items;
1277
2540
  try {
@@ -1295,8 +2558,22 @@ var FallbackStorageAdapter = class {
1295
2558
  }
1296
2559
  activateFallback(error) {
1297
2560
  this.active = "fallback";
1298
- this.onFallback?.(error);
1299
- for (const listener of this.listeners) listener();
2561
+ this.reportFallbackError(error);
2562
+ this.notifyListeners();
2563
+ }
2564
+ reportFallbackError(error) {
2565
+ try {
2566
+ this.onFallback?.(error);
2567
+ } catch {
2568
+ }
2569
+ }
2570
+ notifyListeners() {
2571
+ for (const listener of this.listeners) {
2572
+ try {
2573
+ listener();
2574
+ } catch {
2575
+ }
2576
+ }
1300
2577
  }
1301
2578
  async executeWrite(operation) {
1302
2579
  const result = await this.execute(operation);
@@ -1322,22 +2599,80 @@ var FallbackStorageAdapter = class {
1322
2599
  function createBrowserStorageAdapter(options = {}) {
1323
2600
  const browserIndexedDB = options.indexedDB ?? getBrowserIndexedDB2();
1324
2601
  const scopeKey = getKeepScopeKey(options.scope);
1325
- const storageKey = options.key ? `${options.key}${scopeKey}` : scopeKey ? `${DEFAULT_STORAGE_KEY}${scopeKey}` : void 0;
2602
+ const storageKey = `${options.key ?? DEFAULT_STORAGE_KEY}${scopeKey}`;
1326
2603
  const fallback = new LocalStorageAdapter({ key: storageKey, storage: options.storage });
1327
- if (!browserIndexedDB) return options.scope ? createScopedStorageAdapter(fallback, options.scope) : fallback;
2604
+ const databaseName = options.databaseName ? `${options.databaseName}${scopeKey}` : DEFAULT_INDEXEDDB_DATABASE;
2605
+ const storeName = options.storeName ?? DEFAULT_INDEXEDDB_STORE;
2606
+ const primaryKey = JSON.stringify([databaseName, storeName]);
2607
+ const scopeIdentity = JSON.stringify([options.scope?.tenantId ?? null, options.scope?.userId ?? null]);
2608
+ const journalKey = `${fallback.storageKey}:recovery:${encodeURIComponent(primaryKey)}:${encodeURIComponent(scopeIdentity)}`;
2609
+ const lockKey = `recovery:${primaryKey}`;
2610
+ const legacyBackendKey = `${databaseName}:${storeName}`;
2611
+ const legacyJournalKey = `${fallback.storageKey}:recovery:${encodeURIComponent(legacyBackendKey)}`;
2612
+ const recoveryJournal = options.createRecoveryJournal?.({ storageKey: journalKey, lockKey, scope: options.scope }) ?? createBrowserRecoveryJournal(
2613
+ journalKey,
2614
+ legacyJournalKey,
2615
+ lockKey,
2616
+ options.storage ?? getBrowserStorage2(),
2617
+ options.scope,
2618
+ isAmbiguousLegacyBackend(legacyBackendKey, scopeKey)
2619
+ );
1328
2620
  const adapter = new FallbackStorageAdapter({
1329
- primary: new IndexedDBAdapter({
1330
- databaseName: options.databaseName ? `${options.databaseName}${scopeKey}` : void 0,
2621
+ primary: browserIndexedDB ? new IndexedDBAdapter({
2622
+ databaseName,
1331
2623
  storeName: options.storeName,
1332
2624
  version: options.version,
1333
2625
  indexedDB: browserIndexedDB
1334
- }),
2626
+ }) : void 0,
1335
2627
  fallback,
2628
+ scope: options.scope,
2629
+ recoveryJournal,
1336
2630
  migrateFallbackOnEmpty: true,
1337
2631
  mirrorWrites: true
1338
2632
  });
1339
2633
  return options.scope ? createScopedStorageAdapter(adapter, options.scope) : adapter;
1340
2634
  }
2635
+ function createBrowserRecoveryJournal(storageKey, legacyStorageKey, lockKey, storage, scope, ambiguousBackend) {
2636
+ const journal = new LocalStorageRecoveryJournal(storageKey, storage, lockKey);
2637
+ const legacy = new LocalStorageRecoveryJournal(legacyStorageKey, storage, lockKey);
2638
+ return {
2639
+ read: async () => {
2640
+ const current = await journal.read();
2641
+ if (current !== void 0) return current;
2642
+ const previous = await legacy.read();
2643
+ if (previous && ambiguousBackend)
2644
+ throw new KeepStorageParseError({ operation: "getAll", storageKey: legacyStorageKey });
2645
+ if (scope && previous?.operations.some((operation) => operation.type === "clearItems"))
2646
+ throw new KeepStorageParseError({ operation: "getAll", storageKey: legacyStorageKey });
2647
+ return previous;
2648
+ },
2649
+ write: async (state) => {
2650
+ await journal.write(state);
2651
+ try {
2652
+ storage?.removeItem(legacyStorageKey);
2653
+ } catch {
2654
+ }
2655
+ },
2656
+ runExclusive: (operation) => journal.runExclusive(operation),
2657
+ subscribe: (listener) => {
2658
+ if (typeof window === "undefined") return () => void 0;
2659
+ const onStorage = (event) => {
2660
+ if (event.key === null || event.key === storageKey || event.key === legacyStorageKey) listener();
2661
+ };
2662
+ window.addEventListener("storage", onStorage);
2663
+ return () => window.removeEventListener("storage", onStorage);
2664
+ }
2665
+ };
2666
+ }
2667
+ function isAmbiguousLegacyBackend(backendKey, scopeKey) {
2668
+ let candidates = 0;
2669
+ for (let index = 1; index < backendKey.length - 1; index += 1) {
2670
+ if (backendKey[index] !== ":") continue;
2671
+ const databaseName = backendKey.slice(0, index);
2672
+ if (databaseName === DEFAULT_INDEXEDDB_DATABASE || !scopeKey || databaseName.endsWith(scopeKey)) candidates += 1;
2673
+ }
2674
+ return candidates !== 1;
2675
+ }
1341
2676
  function createStorageAdapter(options) {
1342
2677
  const merge = options.merge;
1343
2678
  const subscribe = options.subscribe;
@@ -1554,8 +2889,9 @@ var LocalStorageAdapter = class {
1554
2889
  }
1555
2890
  write(items, operation) {
1556
2891
  if (!this.storage) return;
2892
+ const serialized = serializeKeepStorage(items, { operation, storageKey: this.storageKey });
1557
2893
  try {
1558
- this.storage.setItem(this.storageKey, JSON.stringify(items));
2894
+ this.storage.setItem(this.storageKey, serialized);
1559
2895
  } catch (cause) {
1560
2896
  if (isQuotaExceededError(cause)) {
1561
2897
  throw new KeepStorageQuotaError({
@@ -1574,8 +2910,9 @@ var LocalStorageAdapter = class {
1574
2910
  async writeCollections(collections, operation) {
1575
2911
  if (!this.storage) return;
1576
2912
  const storageKey = `${this.storageKey}:collections`;
2913
+ const serialized = serializeKeepStorage(collections, { operation, storageKey });
1577
2914
  try {
1578
- this.storage.setItem(storageKey, JSON.stringify(collections));
2915
+ this.storage.setItem(storageKey, serialized);
1579
2916
  } catch (cause) {
1580
2917
  if (isQuotaExceededError(cause)) throw new KeepStorageQuotaError({ operation, storageKey, cause });
1581
2918
  throw new KeepStorageAccessError({ operation, storageKey, cause });
@@ -1584,8 +2921,9 @@ var LocalStorageAdapter = class {
1584
2921
  async writeMemberships(memberships, operation) {
1585
2922
  if (!this.storage) return;
1586
2923
  const storageKey = `${this.storageKey}:memberships`;
2924
+ const serialized = serializeKeepStorage(memberships, { operation, storageKey });
1587
2925
  try {
1588
- this.storage.setItem(storageKey, JSON.stringify(memberships));
2926
+ this.storage.setItem(storageKey, serialized);
1589
2927
  } catch (cause) {
1590
2928
  if (isQuotaExceededError(cause)) throw new KeepStorageQuotaError({ operation, storageKey, cause });
1591
2929
  throw new KeepStorageAccessError({ operation, storageKey, cause });
@@ -1635,11 +2973,11 @@ var IndexedDBAdapter = class {
1635
2973
  if (!isKeepCollectionDefinition(collection)) throw new Error("Collection id and name are required.");
1636
2974
  await this.writeCollection(
1637
2975
  "set",
1638
- (store) => store.put({ ...collection, key: collectionKey(collection.id, collection.scope) })
2976
+ (store) => store.put({ ...collection, key: collectionKey2(collection.id, collection.scope) })
1639
2977
  );
1640
2978
  }
1641
2979
  async removeCollection(id, scope) {
1642
- await this.writeCollection("remove", (store) => store.delete(collectionKey(id, scope)));
2980
+ await this.writeCollection("remove", (store) => store.delete(collectionKey2(id, scope)));
1643
2981
  const memberships = await this.getCollectionMemberships();
1644
2982
  for (const membership of memberships) {
1645
2983
  if (membership.collectionId === id && isSameKeepScope(membership.scope, scope)) {
@@ -1667,11 +3005,11 @@ var IndexedDBAdapter = class {
1667
3005
  if (!isKeepCollectionMembership(membership)) throw new Error("Collection membership is invalid.");
1668
3006
  await this.writeCollectionMembership(
1669
3007
  "set",
1670
- (store) => store.put({ ...membership, key: membershipKey(membership.collectionId, membership.itemId, membership.scope) })
3008
+ (store) => store.put({ ...membership, key: membershipKey2(membership.collectionId, membership.itemId, membership.scope) })
1671
3009
  );
1672
3010
  }
1673
3011
  async removeCollectionMembership(collectionId, itemId, scope) {
1674
- await this.writeCollectionMembership("remove", (store) => store.delete(membershipKey(collectionId, itemId, scope)));
3012
+ await this.writeCollectionMembership("remove", (store) => store.delete(membershipKey2(collectionId, itemId, scope)));
1675
3013
  }
1676
3014
  async set(item) {
1677
3015
  return this.setMany([item]);
@@ -1845,7 +3183,7 @@ var IndexedDBAdapter = class {
1845
3183
  });
1846
3184
  }
1847
3185
  };
1848
- var indexedDBStoredItemId = /* @__PURE__ */ Symbol("keepkit.indexeddb-stored-item-id");
3186
+ var indexedDBStoredItemIds = /* @__PURE__ */ new WeakMap();
1849
3187
  function encodeIndexedDBItem(item) {
1850
3188
  if (!item.scope) return item;
1851
3189
  return {
@@ -1859,11 +3197,11 @@ function decodeIndexedDBItem(item) {
1859
3197
  const isEncoded = typeof originalId === "string" && item.scope !== void 0 && item.id === createScopedIndexedDBItemId({ ...item, id: originalId });
1860
3198
  const { __keepkitOriginalId: _encodedOriginalId, ...record } = item;
1861
3199
  const decoded = isEncoded ? { ...record, id: originalId } : item;
1862
- Object.defineProperty(decoded, indexedDBStoredItemId, { value: item.id });
3200
+ indexedDBStoredItemIds.set(decoded, item.id);
1863
3201
  return decoded;
1864
3202
  }
1865
3203
  function getStoredIndexedDBItemId(item) {
1866
- return item[indexedDBStoredItemId] ?? createScopedIndexedDBItemId(item);
3204
+ return indexedDBStoredItemIds.get(item) ?? createScopedIndexedDBItemId(item);
1867
3205
  }
1868
3206
  function createScopedIndexedDBItemId(item) {
1869
3207
  if (!item.scope) return item.id;
@@ -1872,13 +3210,13 @@ function createScopedIndexedDBItemId(item) {
1872
3210
  function getItemIdentity(item) {
1873
3211
  return JSON.stringify([item.scope?.tenantId ?? null, item.scope?.userId ?? null, item.id]);
1874
3212
  }
1875
- function collectionKey(id, scope) {
3213
+ function collectionKey2(id, scope) {
1876
3214
  return JSON.stringify([scope?.tenantId ?? null, scope?.userId ?? null, id]);
1877
3215
  }
1878
3216
  function getItemStorageKey(item) {
1879
3217
  return JSON.stringify([item.scope?.tenantId ?? null, item.scope?.userId ?? null, item.id]);
1880
3218
  }
1881
- function membershipKey(collectionId, itemId, scope) {
3219
+ function membershipKey2(collectionId, itemId, scope) {
1882
3220
  return JSON.stringify([scope?.tenantId ?? null, scope?.userId ?? null, collectionId, itemId]);
1883
3221
  }
1884
3222
  function getBrowserStorage2() {
@@ -1915,25 +3253,33 @@ function isQuotaExceededError(cause) {
1915
3253
  }
1916
3254
 
1917
3255
  export {
3256
+ withLocalStorageWriteLock,
1918
3257
  KeepSyncAuthError,
1919
3258
  isKeepSyncAuthError,
1920
3259
  KeepStorageError,
1921
3260
  KeepStorageQuotaError,
1922
3261
  KeepStorageAccessError,
1923
3262
  KeepStorageParseError,
3263
+ KeepStorageSerializationError,
1924
3264
  normalizeKeepTags,
1925
3265
  persistKeepItems,
1926
3266
  removeKeepItems,
1927
- mergeKeepItemLists,
1928
- isKeepItem,
1929
- isKeepCollectionDefinition,
1930
- isKeepCollectionMembership,
1931
3267
  isRecord,
1932
3268
  getKeepScopeKey,
1933
3269
  isSameKeepScope,
1934
3270
  ScopedStorageAdapter,
1935
3271
  createScopedStorageAdapter,
1936
3272
  ScopedSyncQueueAdapter,
3273
+ mergeKeepItems,
3274
+ migrateKeepItems,
3275
+ migrateLegacyCollectionMemberships,
3276
+ KEEP_BACKUP_FORMAT,
3277
+ KEEP_BACKUP_VERSION,
3278
+ KeepBackupParseError,
3279
+ KeepBackupImportError,
3280
+ exportItems,
3281
+ importItems,
3282
+ LocalStorageRecoveryJournal,
1937
3283
  DEFAULT_SYNC_QUEUE_KEY,
1938
3284
  DEFAULT_SYNC_QUEUE_DATABASE,
1939
3285
  DEFAULT_SYNC_QUEUE_STORE,
@@ -1950,4 +3296,4 @@ export {
1950
3296
  LocalStorageAdapter,
1951
3297
  IndexedDBAdapter
1952
3298
  };
1953
- //# sourceMappingURL=chunk-SLH4DFYQ.js.map
3299
+ //# sourceMappingURL=chunk-SS22UTBH.js.map