@procedures/store 0.0.0-stage → 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.
Files changed (115) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +21 -0
  3. package/README.md +65 -2
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/errors.d.ts +16 -0
  6. package/dist/errors.d.ts.map +1 -0
  7. package/dist/errors.js +18 -0
  8. package/dist/errors.js.map +1 -0
  9. package/dist/index.d.ts +19 -0
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +19 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/module.d.ts +23 -0
  14. package/dist/module.d.ts.map +1 -0
  15. package/dist/module.js +26 -0
  16. package/dist/module.js.map +1 -0
  17. package/dist/procedures.d.ts +13 -0
  18. package/dist/procedures.d.ts.map +1 -0
  19. package/dist/procedures.js +14 -0
  20. package/dist/procedures.js.map +1 -0
  21. package/dist/program-store/attach.d.ts +20 -0
  22. package/dist/program-store/attach.d.ts.map +1 -0
  23. package/dist/program-store/attach.js +36 -0
  24. package/dist/program-store/attach.js.map +1 -0
  25. package/dist/program-store/collection.d.ts +19 -0
  26. package/dist/program-store/collection.d.ts.map +1 -0
  27. package/dist/program-store/collection.js +34 -0
  28. package/dist/program-store/collection.js.map +1 -0
  29. package/dist/program-store/file.d.ts +29 -0
  30. package/dist/program-store/file.d.ts.map +1 -0
  31. package/dist/program-store/file.js +156 -0
  32. package/dist/program-store/file.js.map +1 -0
  33. package/dist/program-store/index.d.ts +11 -0
  34. package/dist/program-store/index.d.ts.map +1 -0
  35. package/dist/program-store/index.js +10 -0
  36. package/dist/program-store/index.js.map +1 -0
  37. package/dist/program-store/memory.d.ts +15 -0
  38. package/dist/program-store/memory.d.ts.map +1 -0
  39. package/dist/program-store/memory.js +25 -0
  40. package/dist/program-store/memory.js.map +1 -0
  41. package/dist/program-store/procedures.d.ts +23 -0
  42. package/dist/program-store/procedures.d.ts.map +1 -0
  43. package/dist/program-store/procedures.js +228 -0
  44. package/dist/program-store/procedures.js.map +1 -0
  45. package/dist/program-store/types.d.ts +50 -0
  46. package/dist/program-store/types.d.ts.map +1 -0
  47. package/dist/program-store/types.js +41 -0
  48. package/dist/program-store/types.js.map +1 -0
  49. package/dist/register.d.ts +7 -0
  50. package/dist/register.d.ts.map +1 -0
  51. package/dist/register.js +9 -0
  52. package/dist/register.js.map +1 -0
  53. package/dist/storage/adapter.d.ts +148 -0
  54. package/dist/storage/adapter.d.ts.map +1 -0
  55. package/dist/storage/adapter.js +214 -0
  56. package/dist/storage/adapter.js.map +1 -0
  57. package/dist/storage/api.d.ts +125 -0
  58. package/dist/storage/api.d.ts.map +1 -0
  59. package/dist/storage/api.js +220 -0
  60. package/dist/storage/api.js.map +1 -0
  61. package/dist/storage/factory.d.ts +134 -0
  62. package/dist/storage/factory.d.ts.map +1 -0
  63. package/dist/storage/factory.js +166 -0
  64. package/dist/storage/factory.js.map +1 -0
  65. package/dist/storage/hybrid.d.ts +193 -0
  66. package/dist/storage/hybrid.d.ts.map +1 -0
  67. package/dist/storage/hybrid.js +519 -0
  68. package/dist/storage/hybrid.js.map +1 -0
  69. package/dist/storage/index.d.ts +21 -0
  70. package/dist/storage/index.d.ts.map +1 -0
  71. package/dist/storage/index.js +20 -0
  72. package/dist/storage/index.js.map +1 -0
  73. package/dist/storage/procedures.d.ts +14 -0
  74. package/dist/storage/procedures.d.ts.map +1 -0
  75. package/dist/storage/procedures.js +101 -0
  76. package/dist/storage/procedures.js.map +1 -0
  77. package/dist/storage/serialization.d.ts +123 -0
  78. package/dist/storage/serialization.d.ts.map +1 -0
  79. package/dist/storage/serialization.js +216 -0
  80. package/dist/storage/serialization.js.map +1 -0
  81. package/dist/storage/synced-registry.d.ts +246 -0
  82. package/dist/storage/synced-registry.d.ts.map +1 -0
  83. package/dist/storage/synced-registry.js +575 -0
  84. package/dist/storage/synced-registry.js.map +1 -0
  85. package/dist/storage/types.d.ts +130 -0
  86. package/dist/storage/types.d.ts.map +1 -0
  87. package/dist/storage/types.js +8 -0
  88. package/dist/storage/types.js.map +1 -0
  89. package/dist/types.d.ts +7 -0
  90. package/dist/types.d.ts.map +1 -0
  91. package/dist/types.js +7 -0
  92. package/dist/types.js.map +1 -0
  93. package/package.json +78 -3
  94. package/src/errors.ts +20 -0
  95. package/src/index.ts +19 -0
  96. package/src/module.ts +30 -0
  97. package/src/procedures.ts +17 -0
  98. package/src/program-store/attach.ts +46 -0
  99. package/src/program-store/collection.ts +39 -0
  100. package/src/program-store/file.ts +157 -0
  101. package/src/program-store/index.ts +17 -0
  102. package/src/program-store/memory.ts +30 -0
  103. package/src/program-store/procedures.ts +351 -0
  104. package/src/program-store/types.ts +78 -0
  105. package/src/register.ts +11 -0
  106. package/src/storage/adapter.ts +273 -0
  107. package/src/storage/api.ts +335 -0
  108. package/src/storage/factory.ts +268 -0
  109. package/src/storage/hybrid.ts +676 -0
  110. package/src/storage/index.ts +61 -0
  111. package/src/storage/procedures.ts +149 -0
  112. package/src/storage/serialization.ts +283 -0
  113. package/src/storage/synced-registry.ts +698 -0
  114. package/src/storage/types.ts +180 -0
  115. package/src/types.ts +7 -0
@@ -0,0 +1,676 @@
1
+ /**
2
+ * Hybrid Storage Implementation
3
+ *
4
+ * Combines local cache (InMemoryStorage) with remote persistence (ApiStorage).
5
+ * Provides fast local reads with remote backup and sync.
6
+ *
7
+ * Features:
8
+ * - Local cache for fast reads, with a remote read on a miss
9
+ * - Write-through or write-back strategies
10
+ * - Automatic sync on initialization
11
+ * - Conflict resolution
12
+ * - Offline operation queue
13
+ */
14
+
15
+ import type { CollectionStorage, StorageMetadata } from "@procedures/collections";
16
+ import { InMemoryStorage } from "@procedures/collections";
17
+
18
+ /**
19
+ * Conflict resolution strategy.
20
+ */
21
+ export type ConflictResolution = "local" | "remote" | "merge" | "error";
22
+
23
+ /**
24
+ * Write strategy for hybrid storage.
25
+ */
26
+ export type WriteStrategy = "write-through" | "write-back";
27
+
28
+ /**
29
+ * Hybrid storage configuration options.
30
+ */
31
+ export interface HybridStorageOptions {
32
+ /**
33
+ * Write strategy
34
+ * - write-through: Write to both local and remote immediately
35
+ * - write-back: Write to local immediately, sync to remote later
36
+ * @default "write-through"
37
+ */
38
+ writeStrategy?: WriteStrategy;
39
+
40
+ /**
41
+ * Conflict resolution strategy
42
+ * - local: Local changes win
43
+ * - remote: Remote changes win
44
+ * - merge: Custom merge function (requires mergeFn)
45
+ * - error: Throw error on conflict
46
+ * @default "remote"
47
+ */
48
+ conflictResolution?: ConflictResolution;
49
+
50
+ /**
51
+ * Custom merge function for conflict resolution.
52
+ * Only used when conflictResolution is "merge".
53
+ *
54
+ * @param local - Local version
55
+ * @param remote - Remote version
56
+ * @returns Merged value
57
+ */
58
+ mergeFn?: <T>(local: T, remote: T) => T;
59
+
60
+ /**
61
+ * The key of a remote item, for the local cache. The default reads a string `id` field. Give
62
+ * a function for items with another key, for example `getSerializedKey` for procedure records.
63
+ */
64
+ keyOf?: (item: any) => string | undefined;
65
+
66
+ /**
67
+ * Automatic sync interval in milliseconds (for write-back mode).
68
+ * Set to 0 to disable automatic sync.
69
+ * @default 5000 (5 seconds)
70
+ */
71
+ syncInterval?: number;
72
+
73
+ /**
74
+ * Initialize by syncing from remote on construction.
75
+ * @default true
76
+ */
77
+ syncOnInit?: boolean;
78
+
79
+ /**
80
+ * Maximum offline operations to queue.
81
+ * @default 1000
82
+ */
83
+ maxOfflineOps?: number;
84
+
85
+ /**
86
+ * Enable offline operation queue.
87
+ * When remote is unavailable, operations are queued and retried.
88
+ * @default true
89
+ */
90
+ offlineQueue?: boolean;
91
+ }
92
+
93
+ /**
94
+ * Offline operation for write-back/queue.
95
+ */
96
+ interface OfflineOperation {
97
+ type: "set" | "delete" | "setBatch" | "deleteBatch" | "clear";
98
+ data: unknown;
99
+ timestamp: number;
100
+ }
101
+
102
+ /** The ids that an operation changes ("*" for clear). */
103
+ function idsOf(op: OfflineOperation): string[] {
104
+ const data = op.data as { id?: string; ids?: string[]; items?: Array<[string, unknown]> };
105
+ switch (op.type) {
106
+ case "set":
107
+ case "delete":
108
+ return data.id === undefined ? [] : [data.id];
109
+ case "setBatch":
110
+ return (data.items ?? []).map(([id]) => id);
111
+ case "deleteBatch":
112
+ return data.ids ?? [];
113
+ case "clear":
114
+ return ["*"];
115
+ }
116
+ }
117
+
118
+ const defaultKeyOf = (item: unknown): string | undefined => {
119
+ const id = (item as { id?: unknown } | null)?.id;
120
+ return typeof id === "string" && id.length > 0 ? id : undefined;
121
+ };
122
+
123
+ /**
124
+ * Hybrid storage combining local cache with remote persistence.
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const client = new Client({
129
+ * transport: new HttpTransport({ baseUrl: "https://api.example.com" })
130
+ * });
131
+ *
132
+ * const remote = new ApiStorage(client, { collection: "users" });
133
+ * const hybrid = new HybridStorage(remote, {
134
+ * writeStrategy: "write-through",
135
+ * conflictResolution: "remote",
136
+ * syncInterval: 5000
137
+ * });
138
+ *
139
+ * // Fast local reads
140
+ * const user = await hybrid.get("123"); // From cache, or from the remote on a miss
141
+ *
142
+ * // Writes go to both local and remote
143
+ * await hybrid.set("123", { name: "John" });
144
+ * ```
145
+ */
146
+ export class HybridStorage<T> implements CollectionStorage<T> {
147
+ private local: InMemoryStorage<T>;
148
+ private remote: CollectionStorage<T>;
149
+ private options: {
150
+ writeStrategy: WriteStrategy;
151
+ conflictResolution: ConflictResolution;
152
+ mergeFn?: <T>(local: T, remote: T) => T;
153
+ keyOf: (item: T) => string | undefined;
154
+ syncInterval: number;
155
+ syncOnInit: boolean;
156
+ maxOfflineOps: number;
157
+ offlineQueue: boolean;
158
+ };
159
+ private offlineOps: OfflineOperation[] = [];
160
+ private syncTimer: ReturnType<typeof setInterval> | null = null;
161
+ private isOnline = true;
162
+ /** A counter of local writes for each id, so a sync does not restore an older remote value */
163
+ private readonly writeVersions = new Map<string, number>();
164
+ private clearVersion = 0;
165
+ /** The running sync: syncs run one at a time */
166
+ private syncChain: Promise<unknown> = Promise.resolve();
167
+ private stats = {
168
+ cacheHits: 0,
169
+ cacheMisses: 0,
170
+ syncCount: 0,
171
+ conflicts: 0,
172
+ };
173
+
174
+ constructor(
175
+ remote: CollectionStorage<T>,
176
+ options: HybridStorageOptions = {}
177
+ ) {
178
+ this.local = new InMemoryStorage<T>();
179
+ this.remote = remote;
180
+ this.options = {
181
+ writeStrategy: options.writeStrategy ?? "write-through",
182
+ conflictResolution: options.conflictResolution ?? "remote",
183
+ ...(options.mergeFn !== undefined && { mergeFn: options.mergeFn }),
184
+ keyOf: options.keyOf ?? defaultKeyOf,
185
+ syncInterval: options.syncInterval ?? 5000,
186
+ syncOnInit: options.syncOnInit ?? true,
187
+ maxOfflineOps: options.maxOfflineOps ?? 1000,
188
+ offlineQueue: options.offlineQueue ?? true,
189
+ };
190
+
191
+ // Initialize with remote data
192
+ if (this.options.syncOnInit) {
193
+ this.syncFromRemote().catch((err) => {
194
+ console.error("Failed to sync on init:", err);
195
+ });
196
+ }
197
+
198
+ // Start periodic sync for write-back mode
199
+ if (
200
+ this.options.writeStrategy === "write-back" &&
201
+ this.options.syncInterval > 0
202
+ ) {
203
+ this.startPeriodicSync();
204
+ }
205
+ }
206
+
207
+ //
208
+ // ═══ Read Operations ═══
209
+ //
210
+
211
+ /**
212
+ * The local item, or else the remote item (which the cache then keeps). When the remote
213
+ * cannot answer, the storage is offline and the result is undefined.
214
+ */
215
+ async get(id: string): Promise<T | undefined> {
216
+ // Try local cache first
217
+ const cached = await this.local.get(id);
218
+ if (cached !== undefined) {
219
+ this.stats.cacheHits++;
220
+ return cached;
221
+ }
222
+
223
+ this.stats.cacheMisses++;
224
+ // A pending local delete means "no item": do not read it back from the remote
225
+ if (this.hasPendingOp(id)) {
226
+ return undefined;
227
+ }
228
+ const version = this.versionOf(id);
229
+ try {
230
+ const remote = await this.remote.get(id);
231
+ this.isOnline = true;
232
+ if (remote !== undefined && this.versionOf(id) === version) {
233
+ await this.local.set(id, remote);
234
+ }
235
+ return remote;
236
+ } catch {
237
+ this.isOnline = false;
238
+ return undefined;
239
+ }
240
+ }
241
+
242
+ async getAll(): Promise<T[]> {
243
+ // Return local cache
244
+ return this.local.getAll();
245
+ }
246
+
247
+ async find(predicate: (item: T) => boolean): Promise<T[]> {
248
+ // Search local cache
249
+ return this.local.find(predicate);
250
+ }
251
+
252
+ async has(id: string): Promise<boolean> {
253
+ return this.local.has(id);
254
+ }
255
+
256
+ async size(): Promise<number> {
257
+ return this.local.size();
258
+ }
259
+
260
+ //
261
+ // ═══ Write Operations ═══
262
+ //
263
+
264
+ async set(id: string, value: T): Promise<void> {
265
+ this.bump(id);
266
+ // Always write to local immediately
267
+ await this.local.set(id, value);
268
+
269
+ if (this.options.writeStrategy === "write-through") {
270
+ // Write-through: sync to remote immediately
271
+ try {
272
+ await this.remote.set(id, value);
273
+ } catch (error) {
274
+ this.handleRemoteFailure("set", { id, value });
275
+ throw error;
276
+ }
277
+ } else {
278
+ // Write-back: queue for later sync
279
+ this.queueOperation({
280
+ type: "set",
281
+ data: { id, value },
282
+ timestamp: Date.now(),
283
+ });
284
+ }
285
+ }
286
+
287
+ async delete(id: string): Promise<boolean> {
288
+ this.bump(id);
289
+ const existed = await this.local.delete(id);
290
+
291
+ if (this.options.writeStrategy === "write-through") {
292
+ try {
293
+ await this.remote.delete(id);
294
+ } catch (error) {
295
+ this.handleRemoteFailure("delete", { id });
296
+ throw error;
297
+ }
298
+ } else {
299
+ this.queueOperation({
300
+ type: "delete",
301
+ data: { id },
302
+ timestamp: Date.now(),
303
+ });
304
+ }
305
+
306
+ return existed;
307
+ }
308
+
309
+ async clear(): Promise<void> {
310
+ this.clearVersion++;
311
+ await this.local.clear();
312
+
313
+ if (this.options.writeStrategy === "write-through") {
314
+ try {
315
+ await this.remote.clear();
316
+ } catch (error) {
317
+ this.handleRemoteFailure("clear", {});
318
+ throw error;
319
+ }
320
+ } else {
321
+ this.queueOperation({
322
+ type: "clear",
323
+ data: {},
324
+ timestamp: Date.now(),
325
+ });
326
+ }
327
+ }
328
+
329
+ //
330
+ // ═══ Bulk Operations ═══
331
+ //
332
+
333
+ async setBatch(items: Array<[string, T]>): Promise<void> {
334
+ for (const [id] of items) this.bump(id);
335
+ await this.local.setBatch(items);
336
+
337
+ if (this.options.writeStrategy === "write-through") {
338
+ try {
339
+ await this.remote.setBatch(items);
340
+ } catch (error) {
341
+ this.handleRemoteFailure("setBatch", { items });
342
+ throw error;
343
+ }
344
+ } else {
345
+ this.queueOperation({
346
+ type: "setBatch",
347
+ data: { items },
348
+ timestamp: Date.now(),
349
+ });
350
+ }
351
+ }
352
+
353
+ async deleteBatch(ids: string[]): Promise<number> {
354
+ for (const id of ids) this.bump(id);
355
+ const deleted = await this.local.deleteBatch(ids);
356
+
357
+ if (this.options.writeStrategy === "write-through") {
358
+ try {
359
+ await this.remote.deleteBatch(ids);
360
+ } catch (error) {
361
+ this.handleRemoteFailure("deleteBatch", { ids });
362
+ throw error;
363
+ }
364
+ } else {
365
+ this.queueOperation({
366
+ type: "deleteBatch",
367
+ data: { ids },
368
+ timestamp: Date.now(),
369
+ });
370
+ }
371
+
372
+ return deleted;
373
+ }
374
+
375
+ getBatch(ids: string[]): Promise<Map<string, T>> {
376
+ return this.local.getBatch(ids);
377
+ }
378
+
379
+ //
380
+ // ═══ Sync Operations ═══
381
+ //
382
+
383
+ /**
384
+ * Sync all data from remote to local.
385
+ * Handles conflicts according to conflict resolution strategy.
386
+ *
387
+ * - Each remote item goes into the cache under `keyOf(item)`.
388
+ * - A local item that the remote does not have is removed, unless a queued local operation
389
+ * changes it (the remote deleted it).
390
+ * - An id that a local write changed during the sync keeps the local value: the remote value
391
+ * is older.
392
+ * - Syncs run one at a time.
393
+ */
394
+ syncFromRemote(): Promise<void> {
395
+ return this.serialize(() => this.pullRemote());
396
+ }
397
+
398
+ /**
399
+ * Sync all pending offline operations to remote.
400
+ * Processes queued operations in order. When one fails, it and the later operations stay in
401
+ * the queue: the operations that reached the remote are not sent again.
402
+ */
403
+ syncToRemote(): Promise<void> {
404
+ return this.serialize(() => this.pushQueue());
405
+ }
406
+
407
+ /**
408
+ * Force a full sync (both directions).
409
+ */
410
+ async sync(): Promise<void> {
411
+ await this.syncToRemote();
412
+ await this.syncFromRemote();
413
+ }
414
+
415
+ //
416
+ // ═══ Lifecycle & Metadata ═══
417
+ //
418
+
419
+ async close(): Promise<void> {
420
+ // Stop periodic sync
421
+ if (this.syncTimer) {
422
+ clearInterval(this.syncTimer);
423
+ this.syncTimer = null;
424
+ }
425
+
426
+ // Sync pending operations before closing
427
+ if (this.offlineOps.length > 0) {
428
+ try {
429
+ await this.syncToRemote();
430
+ } catch (error) {
431
+ console.error("Failed to sync before close:", error);
432
+ }
433
+ }
434
+
435
+ // Close remote storage (an ApiStorage leaves the caller's client open)
436
+ await this.remote.close();
437
+ }
438
+
439
+ async getMetadata(): Promise<StorageMetadata> {
440
+ const totalOps = this.stats.cacheHits + this.stats.cacheMisses;
441
+ const hitRate = totalOps > 0 ? (this.stats.cacheHits / totalOps) * 100 : 0;
442
+ const currentSize = await this.local.size();
443
+
444
+ return {
445
+ type: "hybrid",
446
+ size: currentSize,
447
+ stats: {
448
+ hitRate: Math.round(hitRate * 100) / 100,
449
+ cacheHits: this.stats.cacheHits,
450
+ cacheMisses: this.stats.cacheMisses,
451
+ syncCount: this.stats.syncCount,
452
+ conflicts: this.stats.conflicts,
453
+ pendingOps: this.offlineOps.length,
454
+ isOnline: this.isOnline,
455
+ writeStrategy: this.options.writeStrategy,
456
+ conflictResolution: this.options.conflictResolution,
457
+ },
458
+ };
459
+ }
460
+
461
+ //
462
+ // ═══ Internal Helpers ═══
463
+ //
464
+
465
+ private async pullRemote(): Promise<void> {
466
+ const versions = new Map(this.writeVersions);
467
+ const clearVersion = this.clearVersion;
468
+ // True when a local write changed the id after the sync started
469
+ const changedLocally = (id: string): boolean =>
470
+ this.clearVersion !== clearVersion || (this.writeVersions.get(id) ?? 0) !== (versions.get(id) ?? 0);
471
+
472
+ let remoteData: T[];
473
+ try {
474
+ remoteData = await this.remote.getAll();
475
+ } catch (error) {
476
+ this.isOnline = false;
477
+ throw error;
478
+ }
479
+
480
+ const remoteIds = new Set<string>();
481
+ for (const item of remoteData) {
482
+ const id = this.options.keyOf(item);
483
+ if (!id) {
484
+ console.warn("Item has no key, skipping:", item);
485
+ continue;
486
+ }
487
+ remoteIds.add(id);
488
+ if (changedLocally(id) || this.hasPendingOp(id)) {
489
+ continue;
490
+ }
491
+
492
+ const localItem = await this.local.get(id);
493
+ if (localItem === undefined) {
494
+ // No local version - just store remote
495
+ await this.local.set(id, item);
496
+ } else if (JSON.stringify(localItem) !== JSON.stringify(item)) {
497
+ // Conflict - resolve according to strategy
498
+ const resolved = this.resolveConflict(localItem, item);
499
+ await this.local.set(id, resolved);
500
+ this.stats.conflicts++;
501
+ }
502
+ }
503
+
504
+ // The remote deleted these items
505
+ for (const id of await this.localIds()) {
506
+ if (!remoteIds.has(id) && !changedLocally(id) && !this.hasPendingOp(id)) {
507
+ await this.local.delete(id);
508
+ }
509
+ }
510
+
511
+ this.stats.syncCount++;
512
+ this.isOnline = true;
513
+ }
514
+
515
+ private async pushQueue(): Promise<void> {
516
+ while (this.offlineOps.length > 0) {
517
+ const op = this.offlineOps[0]!;
518
+ try {
519
+ await this.executeOperation(op);
520
+ } catch (error) {
521
+ // This operation and the later ones stay queued
522
+ this.isOnline = false;
523
+ throw error;
524
+ }
525
+ // Remove the operation only after it reached the remote
526
+ if (this.offlineOps[0] === op) {
527
+ this.offlineOps.shift();
528
+ }
529
+ }
530
+ this.isOnline = true;
531
+ }
532
+
533
+ /** Run syncs one at a time. */
534
+ private serialize(run: () => Promise<void>): Promise<void> {
535
+ const next = this.syncChain.then(run, run);
536
+ this.syncChain = next.catch(() => undefined);
537
+ return next;
538
+ }
539
+
540
+ private async localIds(): Promise<string[]> {
541
+ return [...this.local.keys()];
542
+ }
543
+
544
+ private bump(id: string): void {
545
+ this.writeVersions.set(id, (this.writeVersions.get(id) ?? 0) + 1);
546
+ }
547
+
548
+ private versionOf(id: string): string {
549
+ return `${this.clearVersion}:${this.writeVersions.get(id) ?? 0}`;
550
+ }
551
+
552
+ private hasPendingOp(id: string): boolean {
553
+ return this.offlineOps.some((op) => {
554
+ const ids = idsOf(op);
555
+ return ids.includes(id) || ids.includes("*");
556
+ });
557
+ }
558
+
559
+ /**
560
+ * Resolve conflict between local and remote versions.
561
+ */
562
+ private resolveConflict(local: T, remote: T): T {
563
+ switch (this.options.conflictResolution) {
564
+ case "local":
565
+ return local;
566
+
567
+ case "remote":
568
+ return remote;
569
+
570
+ case "merge":
571
+ if (!this.options.mergeFn) {
572
+ throw new Error(
573
+ "Merge function required for conflict resolution strategy 'merge'"
574
+ );
575
+ }
576
+ return this.options.mergeFn(local, remote);
577
+
578
+ case "error":
579
+ throw new Error(
580
+ `Conflict detected between local and remote versions`
581
+ );
582
+
583
+ default:
584
+ return remote;
585
+ }
586
+ }
587
+
588
+ /**
589
+ * Queue operation for later sync.
590
+ */
591
+ private queueOperation(op: OfflineOperation): void {
592
+ if (!this.options.offlineQueue) {
593
+ return;
594
+ }
595
+
596
+ this.offlineOps.push(op);
597
+
598
+ // Enforce max queue size
599
+ if (this.offlineOps.length > this.options.maxOfflineOps) {
600
+ this.offlineOps.shift(); // Remove oldest
601
+ }
602
+ }
603
+
604
+ /**
605
+ * Execute a queued operation against remote storage.
606
+ */
607
+ private async executeOperation(op: OfflineOperation): Promise<void> {
608
+ const data = op.data as any;
609
+
610
+ switch (op.type) {
611
+ case "set":
612
+ await this.remote.set(data.id, data.value);
613
+ break;
614
+
615
+ case "delete":
616
+ await this.remote.delete(data.id);
617
+ break;
618
+
619
+ case "setBatch":
620
+ await this.remote.setBatch(data.items);
621
+ break;
622
+
623
+ case "deleteBatch":
624
+ await this.remote.deleteBatch(data.ids);
625
+ break;
626
+
627
+ case "clear":
628
+ await this.remote.clear();
629
+ break;
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Handle remote operation failure.
635
+ */
636
+ private handleRemoteFailure(operation: OfflineOperation["type"], data: unknown): void {
637
+ console.error(`Remote ${operation} failed, marking offline`);
638
+ this.isOnline = false;
639
+
640
+ // Queue operation if offline queue enabled
641
+ if (this.options.offlineQueue) {
642
+ this.queueOperation({
643
+ type: operation,
644
+ data,
645
+ timestamp: Date.now(),
646
+ });
647
+ }
648
+ }
649
+
650
+ /**
651
+ * Start periodic background sync.
652
+ */
653
+ private startPeriodicSync(): void {
654
+ this.syncTimer = setInterval(() => {
655
+ this.syncToRemote().catch((err) => {
656
+ console.error("Periodic sync failed:", err);
657
+ });
658
+ }, this.options.syncInterval);
659
+ // The timer must not keep the process alive (deep dive DATA-9)
660
+ (this.syncTimer as { unref?: () => void }).unref?.();
661
+ }
662
+
663
+ /**
664
+ * Get current online status.
665
+ */
666
+ isRemoteOnline(): boolean {
667
+ return this.isOnline;
668
+ }
669
+
670
+ /**
671
+ * Get pending offline operations count.
672
+ */
673
+ getPendingOpsCount(): number {
674
+ return this.offlineOps.length;
675
+ }
676
+ }