@classic-homes/offline-core 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -238,8 +238,8 @@ import { createCacheService } from '@classic-homes/offline-core/cache';
238
238
  ## Default Expirations
239
239
 
240
240
  - **Files**: 7 days
241
- - **Drafts**: 24 hours
242
- - **Cache**: 5 minutes
241
+ - **Drafts**: 7 days (extended on every edit)
242
+ - **Cache**: 1 hour
243
243
 
244
244
  These can be overridden per-operation.
245
245
 
@@ -26,6 +26,11 @@ interface CacheOptions {
26
26
  ttl?: number;
27
27
  /** Tags for bulk invalidation */
28
28
  tags?: string[];
29
+ /**
30
+ * How long an expired entry is kept for stale reads before storage cleanup
31
+ * deletes it (default: ttl)
32
+ */
33
+ staleTime?: number;
29
34
  }
30
35
  /**
31
36
  * Options for the getOrSet operation
@@ -109,7 +114,7 @@ interface CacheServiceOptions {
109
114
  maxInFlight?: number;
110
115
  /** Maximum number of cache entries (default: 1000) */
111
116
  maxEntries?: number;
112
- /** Maximum total cache size in bytes (default: 50MB) */
117
+ /** Maximum total size of this cache's entries in bytes, approximate (default: 50MB) */
113
118
  maxSizeBytes?: number;
114
119
  }
115
120
  /**
@@ -124,6 +129,8 @@ declare class CacheService {
124
129
  private readonly maxEntries;
125
130
  private readonly maxSizeBytes;
126
131
  private accessOrder;
132
+ private entrySizes;
133
+ private entrySizesLoading;
127
134
  constructor(adapter: StorageAdapter, options?: CacheServiceOptions);
128
135
  /**
129
136
  * Clean up stale in-flight requests
@@ -137,11 +144,20 @@ declare class CacheService {
137
144
  * Set a cached value
138
145
  */
139
146
  set<T>(key: string, value: T, options?: CacheOptions): Promise<void>;
147
+ /**
148
+ * Sizes of this cache's entries, read from storage the first time
149
+ */
150
+ private getEntrySizes;
140
151
  /**
141
152
  * Enforce cache size limits using LRU eviction
142
153
  * @param newKey - Key being added (skip count check if it already exists)
154
+ * @param newSize - Approximate size of the entry being written
143
155
  */
144
156
  private enforceLimit;
157
+ /**
158
+ * Sort keys by access time, oldest first
159
+ */
160
+ private sortByAccess;
145
161
  /**
146
162
  * Evict least recently used entries
147
163
  */
@@ -1,6 +1,6 @@
1
- export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-PEQVHD6Q.js';
2
- import '../chunk-J2ZYJDJX.js';
3
- import '../chunk-U27TKOYZ.js';
4
- import '../chunk-EWMN3Y7N.js';
5
- import '../chunk-WWKATW37.js';
6
- import '../chunk-ZC7F2HDV.js';
1
+ export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-JPXEFKZO.js';
2
+ import '../chunk-4KL3GDYP.js';
3
+ import '../chunk-R2IP2AA5.js';
4
+ import '../chunk-UL7MZBSF.js';
5
+ import '../chunk-MA4ZHPQS.js';
6
+ import '../chunk-QS7N4PTV.js';
@@ -1,4 +1,4 @@
1
- import { generateDraftId, DraftManagerService } from './chunk-WWKATW37.js';
1
+ import { generateDraftId, DraftManagerService } from './chunk-MA4ZHPQS.js';
2
2
 
3
3
  // src/sync/types.ts
4
4
  var SyncConflictError = class extends Error {
@@ -550,10 +550,48 @@ function compareDrafts(local, remote) {
550
550
  };
551
551
  }
552
552
 
553
+ // src/sync/lock.ts
554
+ var SYNC_LOCK_NAME = "classic-offline-sync";
555
+ var localLockHeld = false;
556
+ function getLockManager() {
557
+ if (typeof navigator === "undefined") return null;
558
+ const locks = navigator.locks;
559
+ return locks && typeof locks.request === "function" ? locks : null;
560
+ }
561
+ async function withSyncLock(fn) {
562
+ const locks = getLockManager();
563
+ if (locks) {
564
+ return locks.request(
565
+ SYNC_LOCK_NAME,
566
+ { ifAvailable: true },
567
+ async (lock) => lock ? { acquired: true, value: await fn() } : { acquired: false }
568
+ );
569
+ }
570
+ if (localLockHeld) {
571
+ return { acquired: false };
572
+ }
573
+ localLockHeld = true;
574
+ try {
575
+ return { acquired: true, value: await fn() };
576
+ } finally {
577
+ localLockHeld = false;
578
+ }
579
+ }
580
+
553
581
  // src/sync/service.ts
554
582
  var DEFAULT_SYNC_INTERVAL = 3e4;
555
583
  var DEFAULT_BATCH_SIZE = 50;
556
584
  var CONFLICTS_STORAGE_KEY = "sync-conflicts";
585
+ var RETRY_BASE_DELAY_MS = 5e3;
586
+ var RETRY_MAX_DELAY_MS = 15 * 60 * 1e3;
587
+ var PENDING_STATUSES = ["pending-upload", "local-only"];
588
+ function errorMessage(error) {
589
+ return error instanceof Error ? error.message : String(error);
590
+ }
591
+ function hasLocalEdits(metadata) {
592
+ if (metadata.syncStatus !== "synced") return true;
593
+ return metadata.syncedVersion !== void 0 && metadata.version !== metadata.syncedVersion;
594
+ }
557
595
  var SyncService = class {
558
596
  constructor(adapter, config) {
559
597
  this.adapter = adapter;
@@ -563,6 +601,9 @@ var SyncService = class {
563
601
  this.conflicts = [];
564
602
  this.eventListeners = /* @__PURE__ */ new Map();
565
603
  this.connectivityUnsubscribe = null;
604
+ this.pendingDraftCount = 0;
605
+ /** Upload backoff per local draft ID */
606
+ this.uploadFailures = /* @__PURE__ */ new Map();
566
607
  this.syncAdapter = config.adapter;
567
608
  this.config = {
568
609
  syncIntervalMs: config.syncIntervalMs ?? DEFAULT_SYNC_INTERVAL,
@@ -590,6 +631,7 @@ var SyncService = class {
590
631
  async initialize() {
591
632
  await this.queue.initialize();
592
633
  await this.loadConflicts();
634
+ await this.refreshPendingCount();
593
635
  }
594
636
  // ============================================
595
637
  // Properties
@@ -613,10 +655,24 @@ var SyncService = class {
613
655
  return this.queue.lastSyncAt;
614
656
  }
615
657
  /**
616
- * Get pending sync count
658
+ * Number of local drafts waiting to be uploaded ('local-only' or
659
+ * 'pending-upload'), as of the last sync, `initialize()` or
660
+ * `refreshPendingCount()`
617
661
  */
618
662
  get pendingCount() {
619
- return this.queue.pendingCount;
663
+ return this.pendingDraftCount;
664
+ }
665
+ /**
666
+ * Recount the local drafts waiting to be uploaded
667
+ */
668
+ async refreshPendingCount() {
669
+ try {
670
+ const pending = await this.draftManager.listDrafts({ syncStatus: PENDING_STATUSES });
671
+ this.pendingDraftCount = pending.length;
672
+ } catch (error) {
673
+ console.warn("[SyncService] Failed to count pending drafts:", error);
674
+ }
675
+ return this.pendingDraftCount;
620
676
  }
621
677
  /**
622
678
  * Get current conflicts
@@ -644,6 +700,14 @@ var SyncService = class {
644
700
  return this.createErrorResult("Device is offline");
645
701
  }
646
702
  this.isSyncing = true;
703
+ try {
704
+ const locked = await withSyncLock(() => this.runSyncAll());
705
+ return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
706
+ } finally {
707
+ this.isSyncing = false;
708
+ }
709
+ }
710
+ async runSyncAll() {
647
711
  const startTime = Date.now();
648
712
  this.emit("sync:start", null);
649
713
  try {
@@ -660,6 +724,7 @@ var SyncService = class {
660
724
  this.onConflictDetected?.(result.conflicts);
661
725
  }
662
726
  await this.queue.updateLastSyncAt(Date.now());
727
+ await this.refreshPendingCount();
663
728
  this.emit("sync:complete", result);
664
729
  this.onSyncComplete?.(result);
665
730
  return result;
@@ -668,11 +733,10 @@ var SyncService = class {
668
733
  error instanceof Error ? error.message : "Unknown error",
669
734
  startTime
670
735
  );
736
+ await this.refreshPendingCount();
671
737
  this.emit("sync:error", error);
672
738
  this.onSyncError?.(error instanceof Error ? error : new Error(String(error)));
673
739
  return errorResult;
674
- } finally {
675
- this.isSyncing = false;
676
740
  }
677
741
  }
678
742
  /**
@@ -686,13 +750,28 @@ var SyncService = class {
686
750
  return this.createErrorResult("Device is offline");
687
751
  }
688
752
  this.isSyncing = true;
753
+ try {
754
+ const locked = await withSyncLock(() => this.runSyncDraft(draftId));
755
+ return locked.acquired ? locked.value : this.createErrorResult("Sync already in progress");
756
+ } finally {
757
+ this.isSyncing = false;
758
+ }
759
+ }
760
+ async runSyncDraft(draftId) {
689
761
  const startTime = Date.now();
690
762
  try {
691
763
  const draft = await this.draftManager.getDraft(draftId);
692
764
  if (!draft) {
693
765
  return this.createErrorResult("Draft not found");
694
766
  }
695
- const result = await this.syncSingleDraft(draft);
767
+ let result;
768
+ try {
769
+ result = await this.syncSingleDraft(draft);
770
+ this.uploadFailures.delete(draftId);
771
+ } catch (error) {
772
+ this.recordUploadFailure(draftId, startTime);
773
+ throw error;
774
+ }
696
775
  return {
697
776
  success: true,
698
777
  uploaded: result.uploaded ? 1 : 0,
@@ -709,7 +788,7 @@ var SyncService = class {
709
788
  startTime
710
789
  );
711
790
  } finally {
712
- this.isSyncing = false;
791
+ await this.refreshPendingCount();
713
792
  }
714
793
  }
715
794
  /**
@@ -723,13 +802,10 @@ var SyncService = class {
723
802
  const payload = this.createPayload(draft);
724
803
  if (draft.metadata.remoteId) {
725
804
  await this.syncAdapter.updateDraft(draft.metadata.remoteId, payload);
805
+ await this.markUploaded(draft, draft.metadata.remoteId);
726
806
  } else {
727
807
  const remote = await this.syncAdapter.createDraft(payload);
728
- await this.draftManager.updateDraftMetadata(draftId, {
729
- remoteId: remote.id,
730
- syncStatus: "synced",
731
- lastSyncedAt: Date.now()
732
- });
808
+ await this.markUploaded(draft, remote.id);
733
809
  }
734
810
  await this.removeConflict(draftId);
735
811
  }
@@ -857,67 +933,122 @@ var SyncService = class {
857
933
  // Private Methods
858
934
  // ============================================
859
935
  /**
860
- * Perform the actual sync
936
+ * Perform the actual sync. One draft failing does not stop the rest: each
937
+ * failure is recorded in `failures` and the sync carries on.
861
938
  */
862
939
  async performSync() {
863
940
  const startTime = Date.now();
864
941
  let uploaded = 0;
865
942
  let downloaded = 0;
866
- let deletedRemote = 0;
943
+ const deletedRemote = 0;
867
944
  let deletedLocal = 0;
868
945
  const conflicts = [];
946
+ const failures = [];
869
947
  const localDrafts = await this.draftManager.listDrafts();
870
- const pendingDrafts = localDrafts.filter(
871
- (d) => d.syncStatus === "pending-upload" || d.syncStatus === "local-only"
872
- );
948
+ const pendingDrafts = localDrafts.filter((d) => PENDING_STATUSES.includes(d.syncStatus));
873
949
  const remoteDrafts = await this.syncAdapter.fetchDrafts();
874
950
  const remoteMap = new Map(remoteDrafts.map((r) => [r.id, r]));
875
951
  for (const metadata of pendingDrafts) {
876
- const draft = await this.draftManager.getDraft(metadata.id);
877
- if (!draft) continue;
878
- const result = await this.syncSingleDraft(draft);
879
- if (result.uploaded) uploaded++;
880
- if (result.conflict) conflicts.push(result.conflict);
952
+ if (this.isBackedOff(metadata.id, startTime)) continue;
953
+ try {
954
+ const draft = await this.draftManager.getDraft(metadata.id);
955
+ if (!draft) continue;
956
+ const result = await this.syncSingleDraft(draft);
957
+ this.uploadFailures.delete(metadata.id);
958
+ if (result.uploaded) uploaded++;
959
+ if (result.conflict) conflicts.push(result.conflict);
960
+ } catch (error) {
961
+ this.recordUploadFailure(metadata.id, startTime);
962
+ failures.push({
963
+ operation: "upload",
964
+ draftId: metadata.id,
965
+ remoteId: metadata.remoteId ?? void 0,
966
+ error: errorMessage(error)
967
+ });
968
+ }
881
969
  }
882
970
  for (const remote of remoteDrafts) {
883
971
  const localDraft = localDrafts.find((d) => d.remoteId === remote.id);
884
- if (!localDraft) {
885
- await this.downloadRemoteDraft(remote);
886
- downloaded++;
887
- } else if (localDraft.syncStatus === "synced") {
888
- const local = await this.draftManager.getDraft(localDraft.id);
889
- if (local && remote.updatedAt > (local.metadata.lastSyncedAt ?? 0)) {
890
- if (local.metadata.updatedAt > (local.metadata.lastSyncedAt ?? 0)) {
891
- conflicts.push(createConflict(local, remote));
892
- await this.draftManager.updateDraftMetadata(localDraft.id, {
893
- syncStatus: "conflict"
894
- });
895
- } else {
896
- await this.downloadRemoteDraft(remote, localDraft.id);
897
- downloaded++;
972
+ try {
973
+ if (!localDraft) {
974
+ await this.downloadRemoteDraft(remote);
975
+ downloaded++;
976
+ } else if (localDraft.syncStatus === "synced") {
977
+ const local = await this.draftManager.getDraft(localDraft.id);
978
+ if (local && remote.updatedAt > (local.metadata.lastSyncedAt ?? 0)) {
979
+ if (hasLocalEdits(local.metadata)) {
980
+ conflicts.push(createConflict(local, remote));
981
+ await this.draftManager.updateDraftMetadata(localDraft.id, {
982
+ syncStatus: "conflict"
983
+ });
984
+ } else if (await this.downloadRemoteDraft(remote, local)) {
985
+ downloaded++;
986
+ }
898
987
  }
899
988
  }
989
+ } catch (error) {
990
+ failures.push({
991
+ operation: "download",
992
+ draftId: localDraft?.id,
993
+ remoteId: remote.id,
994
+ error: errorMessage(error)
995
+ });
900
996
  }
901
997
  }
902
998
  const syncedDrafts = localDrafts.filter((d) => d.remoteId && d.syncStatus === "synced");
903
999
  for (const metadata of syncedDrafts) {
904
- if (!remoteMap.has(metadata.remoteId)) {
905
- await this.draftManager.deleteDraft(metadata.id);
906
- deletedLocal++;
907
- this.emit("draft:deleted", { draftId: metadata.id, remoteId: metadata.remoteId });
1000
+ if (remoteMap.has(metadata.remoteId)) continue;
1001
+ try {
1002
+ const current = await this.draftManager.getDraftMetadata(metadata.id);
1003
+ if (!current || current.syncStatus !== "synced" || current.version !== metadata.version || current.remoteId !== metadata.remoteId) {
1004
+ continue;
1005
+ }
1006
+ const deleted = await this.draftManager.deleteDraft(metadata.id, false, {
1007
+ expectedVersion: metadata.version
1008
+ });
1009
+ if (deleted) {
1010
+ deletedLocal++;
1011
+ this.emit("draft:deleted", { draftId: metadata.id, remoteId: metadata.remoteId });
1012
+ }
1013
+ } catch (error) {
1014
+ failures.push({
1015
+ operation: "delete",
1016
+ draftId: metadata.id,
1017
+ remoteId: metadata.remoteId ?? void 0,
1018
+ error: errorMessage(error)
1019
+ });
908
1020
  }
909
1021
  }
910
1022
  return {
911
- success: true,
1023
+ success: failures.length === 0,
912
1024
  uploaded,
913
1025
  downloaded,
914
1026
  deletedRemote,
915
1027
  deletedLocal,
916
1028
  conflicts,
1029
+ failures,
1030
+ ...failures.length > 0 && {
1031
+ error: `${failures.length} draft(s) failed to sync: ${failures[0].error}`
1032
+ },
917
1033
  timestamp: Date.now(),
918
1034
  durationMs: Date.now() - startTime
919
1035
  };
920
1036
  }
1037
+ /**
1038
+ * Whether a failing draft is still waiting out its retry delay
1039
+ */
1040
+ isBackedOff(draftId, now) {
1041
+ const failure = this.uploadFailures.get(draftId);
1042
+ return failure !== void 0 && now < failure.nextAttemptAt;
1043
+ }
1044
+ /**
1045
+ * Record a failed upload and schedule its next attempt (exponential backoff)
1046
+ */
1047
+ recordUploadFailure(draftId, now) {
1048
+ const attempts = (this.uploadFailures.get(draftId)?.attempts ?? 0) + 1;
1049
+ const delay = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (attempts - 1));
1050
+ this.uploadFailures.set(draftId, { attempts, nextAttemptAt: now + delay });
1051
+ }
921
1052
  /**
922
1053
  * Sync a single draft
923
1054
  */
@@ -926,10 +1057,7 @@ var SyncService = class {
926
1057
  try {
927
1058
  if (draft.metadata.remoteId) {
928
1059
  await this.syncAdapter.updateDraft(draft.metadata.remoteId, payload);
929
- await this.draftManager.updateDraftMetadata(draft.metadata.id, {
930
- syncStatus: "synced",
931
- lastSyncedAt: Date.now()
932
- });
1060
+ await this.markUploaded(draft, draft.metadata.remoteId);
933
1061
  this.emit("draft:uploaded", {
934
1062
  draftId: draft.metadata.id,
935
1063
  remoteId: draft.metadata.remoteId
@@ -937,11 +1065,7 @@ var SyncService = class {
937
1065
  return { uploaded: true, downloaded: false, conflict: null };
938
1066
  } else {
939
1067
  const remote = await this.syncAdapter.createDraft(payload);
940
- await this.draftManager.updateDraftMetadata(draft.metadata.id, {
941
- remoteId: remote.id,
942
- syncStatus: "synced",
943
- lastSyncedAt: Date.now()
944
- });
1068
+ await this.markUploaded(draft, remote.id);
945
1069
  this.emit("draft:uploaded", { draftId: draft.metadata.id, remoteId: remote.id });
946
1070
  return { uploaded: true, downloaded: false, conflict: null };
947
1071
  }
@@ -961,17 +1085,46 @@ var SyncService = class {
961
1085
  }
962
1086
  }
963
1087
  /**
964
- * Download a remote draft
1088
+ * Mark an uploaded draft as synced, but only if it was not edited while the
1089
+ * upload was in flight (compare-and-set on `version`). An edited draft stays
1090
+ * pending so the edit is uploaded next time; its remote ID is still
1091
+ * recorded so that upload updates the remote copy instead of creating another.
965
1092
  */
966
- async downloadRemoteDraft(remote, existingDraftId) {
967
- if (existingDraftId) {
968
- await this.draftManager.updateDraft(existingDraftId, remote.data, remote.fileRefs);
969
- await this.draftManager.updateDraftMetadata(existingDraftId, {
970
- name: remote.name,
971
- syncStatus: "synced",
972
- remoteId: remote.id,
973
- lastSyncedAt: Date.now()
1093
+ async markUploaded(draft, remoteId) {
1094
+ const { id, version } = draft.metadata;
1095
+ const marked = await this.draftManager.updateDraftMetadata(
1096
+ id,
1097
+ { remoteId, syncStatus: "synced", lastSyncedAt: Date.now(), syncedVersion: version },
1098
+ { expectedVersion: version }
1099
+ );
1100
+ if (!marked) {
1101
+ await this.draftManager.updateDraftMetadata(id, { remoteId });
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Download a remote draft. Into an existing local draft only if that draft
1106
+ * is unchanged since it was read; returns false when a local edit won.
1107
+ */
1108
+ async downloadRemoteDraft(remote, existing) {
1109
+ if (existing) {
1110
+ const { id, version } = existing.metadata;
1111
+ const applied = await this.draftManager.updateDraft(id, remote.data, remote.fileRefs, {
1112
+ expectedVersion: version,
1113
+ replace: true
974
1114
  });
1115
+ if (!applied) {
1116
+ return false;
1117
+ }
1118
+ await this.draftManager.updateDraftMetadata(
1119
+ id,
1120
+ {
1121
+ name: remote.name,
1122
+ syncStatus: "synced",
1123
+ remoteId: remote.id,
1124
+ lastSyncedAt: Date.now()
1125
+ },
1126
+ { expectedVersion: version + 1 }
1127
+ );
975
1128
  } else {
976
1129
  const metadata = await this.draftManager.createDraft(remote.formKey, {
977
1130
  name: remote.name,
@@ -985,6 +1138,7 @@ var SyncService = class {
985
1138
  });
986
1139
  }
987
1140
  this.emit("draft:downloaded", remote);
1141
+ return true;
988
1142
  }
989
1143
  /**
990
1144
  * Create a payload from a draft
@@ -997,7 +1151,9 @@ var SyncService = class {
997
1151
  fileRefs: draft.fileRefs,
998
1152
  version: draft.metadata.version,
999
1153
  updatedAt: draft.metadata.updatedAt,
1000
- deviceId: draft.metadata.deviceId
1154
+ deviceId: draft.metadata.deviceId,
1155
+ // Idempotency key for creates
1156
+ localId: draft.metadata.id
1001
1157
  };
1002
1158
  }
1003
1159
  /**