@classic-homes/offline-core 0.1.5 → 0.3.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 +2 -2
- package/dist/cache/index.d.ts +42 -1
- package/dist/cache/index.js +6 -6
- package/dist/{chunk-J2ZYJDJX.js → chunk-4KL3GDYP.js} +94 -44
- package/dist/{chunk-WWKATW37.js → chunk-MA4ZHPQS.js} +95 -18
- package/dist/{chunk-DIXYWY34.js → chunk-NCAGT2LL.js} +361 -73
- package/dist/{chunk-ZC7F2HDV.js → chunk-QS7N4PTV.js} +5 -2
- package/dist/{chunk-U27TKOYZ.js → chunk-R2IP2AA5.js} +2 -2
- package/dist/{chunk-PEQVHD6Q.js → chunk-SLDAYKRY.js} +191 -34
- package/dist/{chunk-EWMN3Y7N.js → chunk-UL7MZBSF.js} +2 -2
- package/dist/drafts/index.d.ts +46 -9
- package/dist/drafts/index.js +3 -3
- package/dist/files/index.js +2 -2
- package/dist/index.d.ts +7 -4
- package/dist/index.js +7 -7
- package/dist/storage/index.d.ts +7 -1
- package/dist/storage/index.js +2 -2
- package/dist/sync/index.d.ts +109 -14
- package/dist/sync/index.js +3 -3
- package/dist/{types-Ho1JiLQR.d.ts → types-CRMTQnjY.d.ts} +6 -1
- package/package.json +1 -1
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**:
|
|
242
|
-
- **Cache**:
|
|
241
|
+
- **Drafts**: 7 days (extended on every edit)
|
|
242
|
+
- **Cache**: 1 hour
|
|
243
243
|
|
|
244
244
|
These can be overridden per-operation.
|
|
245
245
|
|
package/dist/cache/index.d.ts
CHANGED
|
@@ -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
|
|
117
|
+
/** Maximum total size of this cache's entries in bytes, approximate (default: 50MB) */
|
|
113
118
|
maxSizeBytes?: number;
|
|
114
119
|
}
|
|
115
120
|
/**
|
|
@@ -119,11 +124,15 @@ declare class CacheService {
|
|
|
119
124
|
private readonly adapter;
|
|
120
125
|
private stats;
|
|
121
126
|
private inFlightFetches;
|
|
127
|
+
private pendingWrites;
|
|
128
|
+
private generation;
|
|
122
129
|
private readonly inFlightTimeout;
|
|
123
130
|
private readonly maxInFlight;
|
|
124
131
|
private readonly maxEntries;
|
|
125
132
|
private readonly maxSizeBytes;
|
|
126
133
|
private accessOrder;
|
|
134
|
+
private entrySizes;
|
|
135
|
+
private entrySizesLoading;
|
|
127
136
|
constructor(adapter: StorageAdapter, options?: CacheServiceOptions);
|
|
128
137
|
/**
|
|
129
138
|
* Clean up stale in-flight requests
|
|
@@ -137,11 +146,36 @@ declare class CacheService {
|
|
|
137
146
|
* Set a cached value
|
|
138
147
|
*/
|
|
139
148
|
set<T>(key: string, value: T, options?: CacheOptions): Promise<void>;
|
|
149
|
+
/**
|
|
150
|
+
* Register a pending write for `key` (see {@link WriteTicket}).
|
|
151
|
+
*/
|
|
152
|
+
private openTicket;
|
|
153
|
+
private isLive;
|
|
154
|
+
/**
|
|
155
|
+
* Cancel the pending writes `matches` selects, and forget their in-flight
|
|
156
|
+
* fetches so later reads start their own.
|
|
157
|
+
*/
|
|
158
|
+
private cancelPending;
|
|
159
|
+
/**
|
|
160
|
+
* Store a value, unless `ticket` is cancelled before the write is issued.
|
|
161
|
+
* A cancellation that lands while the write is in progress deletes the
|
|
162
|
+
* entry again: invalidated data must not survive the invalidation.
|
|
163
|
+
*/
|
|
164
|
+
private write;
|
|
165
|
+
/**
|
|
166
|
+
* Sizes of this cache's entries, read from storage the first time
|
|
167
|
+
*/
|
|
168
|
+
private getEntrySizes;
|
|
140
169
|
/**
|
|
141
170
|
* Enforce cache size limits using LRU eviction
|
|
142
171
|
* @param newKey - Key being added (skip count check if it already exists)
|
|
172
|
+
* @param newSize - Approximate size of the entry being written
|
|
143
173
|
*/
|
|
144
174
|
private enforceLimit;
|
|
175
|
+
/**
|
|
176
|
+
* Sort keys by access time, oldest first
|
|
177
|
+
*/
|
|
178
|
+
private sortByAccess;
|
|
145
179
|
/**
|
|
146
180
|
* Evict least recently used entries
|
|
147
181
|
*/
|
|
@@ -150,6 +184,7 @@ declare class CacheService {
|
|
|
150
184
|
* Get cached value or fetch and cache it
|
|
151
185
|
*/
|
|
152
186
|
getOrSet<T>(key: string, fetcher: () => Promise<T>, options?: GetOrSetOptions): Promise<T>;
|
|
187
|
+
private getOrFetch;
|
|
153
188
|
/**
|
|
154
189
|
* Fetch and cache a value (with deduplication)
|
|
155
190
|
*/
|
|
@@ -162,6 +197,12 @@ declare class CacheService {
|
|
|
162
197
|
* Invalidate a cached value
|
|
163
198
|
*/
|
|
164
199
|
invalidate(key: string): Promise<void>;
|
|
200
|
+
/**
|
|
201
|
+
* Delete one entry from storage (eviction and invalidate). Unlike
|
|
202
|
+
* invalidate() it leaves pending writes alone: eviction makes room, it
|
|
203
|
+
* does not declare the data stale.
|
|
204
|
+
*/
|
|
205
|
+
private removeEntry;
|
|
165
206
|
/**
|
|
166
207
|
* Invalidate all entries with a specific tag
|
|
167
208
|
*/
|
package/dist/cache/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
3
|
-
import '../chunk-
|
|
4
|
-
import '../chunk-
|
|
5
|
-
import '../chunk-
|
|
6
|
-
import '../chunk-
|
|
1
|
+
export { CACHE_PREFIX, CacheService, createCacheService, getCacheKey, getOriginalKey, invalidateAllCache, invalidateCacheByTag } from '../chunk-SLDAYKRY.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 { isExpired, calculateExpiration } from './chunk-
|
|
1
|
+
import { isExpired, calculateExpiration } from './chunk-QS7N4PTV.js';
|
|
2
2
|
import { openDB } from 'idb';
|
|
3
3
|
|
|
4
4
|
// src/storage/memory-adapter.ts
|
|
@@ -351,16 +351,59 @@ var IndexedDBAdapter = class {
|
|
|
351
351
|
constructor(options) {
|
|
352
352
|
this.name = "indexeddb";
|
|
353
353
|
this.db = null;
|
|
354
|
+
this.reopening = null;
|
|
355
|
+
this.initialized = false;
|
|
354
356
|
this.dbName = options?.dbName ?? DEFAULT_DB_NAME;
|
|
355
357
|
}
|
|
356
358
|
/**
|
|
357
|
-
* Get the database,
|
|
359
|
+
* Get the database, reopening it if the connection was closed
|
|
358
360
|
*/
|
|
359
361
|
async getDB() {
|
|
360
|
-
if (
|
|
362
|
+
if (this.db) {
|
|
363
|
+
return this.db;
|
|
364
|
+
}
|
|
365
|
+
if (!this.initialized) {
|
|
361
366
|
throw OfflineStorageError.notInitialized();
|
|
362
367
|
}
|
|
363
|
-
|
|
368
|
+
this.reopening ?? (this.reopening = this.open().finally(() => {
|
|
369
|
+
this.reopening = null;
|
|
370
|
+
}));
|
|
371
|
+
return this.reopening;
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Open the database and keep the connection only while it is usable
|
|
375
|
+
*/
|
|
376
|
+
async open() {
|
|
377
|
+
let db = null;
|
|
378
|
+
const release = () => {
|
|
379
|
+
if (db && this.db === db) {
|
|
380
|
+
this.db = null;
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
db = await openDB(this.dbName, DB_VERSION, {
|
|
384
|
+
upgrade(upgradeDb) {
|
|
385
|
+
if (!upgradeDb.objectStoreNames.contains("blobs")) {
|
|
386
|
+
const blobsStore = upgradeDb.createObjectStore("blobs", { keyPath: "key" });
|
|
387
|
+
blobsStore.createIndex("by-formKey", "metadata.formKey");
|
|
388
|
+
blobsStore.createIndex("by-expiresAt", "metadata.expiresAt");
|
|
389
|
+
}
|
|
390
|
+
if (!upgradeDb.objectStoreNames.contains("json")) {
|
|
391
|
+
const jsonStore = upgradeDb.createObjectStore("json", { keyPath: "key" });
|
|
392
|
+
jsonStore.createIndex("by-expiresAt", "entry.expiresAt");
|
|
393
|
+
jsonStore.createIndex("by-tag", "entry.tags", { multiEntry: true });
|
|
394
|
+
}
|
|
395
|
+
},
|
|
396
|
+
// Another tab wants to upgrade or delete the database: close so it
|
|
397
|
+
// isn't blocked forever
|
|
398
|
+
blocking: () => {
|
|
399
|
+
db?.close();
|
|
400
|
+
release();
|
|
401
|
+
},
|
|
402
|
+
// The browser closed the connection abnormally
|
|
403
|
+
terminated: release
|
|
404
|
+
});
|
|
405
|
+
this.db = db;
|
|
406
|
+
return db;
|
|
364
407
|
}
|
|
365
408
|
// ===== Binary Storage =====
|
|
366
409
|
async storeBlob(key, blob, metadata) {
|
|
@@ -579,25 +622,14 @@ var IndexedDBAdapter = class {
|
|
|
579
622
|
}
|
|
580
623
|
async initialize() {
|
|
581
624
|
try {
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
if (!db.objectStoreNames.contains("blobs")) {
|
|
585
|
-
const blobsStore = db.createObjectStore("blobs", { keyPath: "key" });
|
|
586
|
-
blobsStore.createIndex("by-formKey", "metadata.formKey");
|
|
587
|
-
blobsStore.createIndex("by-expiresAt", "metadata.expiresAt");
|
|
588
|
-
}
|
|
589
|
-
if (!db.objectStoreNames.contains("json")) {
|
|
590
|
-
const jsonStore = db.createObjectStore("json", { keyPath: "key" });
|
|
591
|
-
jsonStore.createIndex("by-expiresAt", "entry.expiresAt");
|
|
592
|
-
jsonStore.createIndex("by-tag", "entry.tags", { multiEntry: true });
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
});
|
|
625
|
+
await this.open();
|
|
626
|
+
this.initialized = true;
|
|
596
627
|
} catch (error) {
|
|
597
628
|
throw OfflineStorageError.idbError("Failed to initialize IndexedDB", error);
|
|
598
629
|
}
|
|
599
630
|
}
|
|
600
631
|
async dispose() {
|
|
632
|
+
this.initialized = false;
|
|
601
633
|
if (this.db) {
|
|
602
634
|
this.db.close();
|
|
603
635
|
this.db = null;
|
|
@@ -659,20 +691,27 @@ async function storeBlob(key, blob, metadata) {
|
|
|
659
691
|
throw new Error("Storage not initialized");
|
|
660
692
|
}
|
|
661
693
|
const encodedKey = encodeKey(key);
|
|
662
|
-
const blobFileHandle = await blobsHandle.getFileHandle(encodedKey, { create: true });
|
|
663
|
-
const blobWritable = await blobFileHandle.createWritable();
|
|
664
|
-
await blobWritable.write(blob);
|
|
665
|
-
await blobWritable.close();
|
|
666
694
|
const fullMetadata = {
|
|
667
695
|
...metadata,
|
|
668
696
|
size: blob.size,
|
|
669
697
|
contentType: blob.type || metadata?.contentType,
|
|
670
698
|
createdAt: metadata?.createdAt ?? Date.now()
|
|
671
699
|
};
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
700
|
+
try {
|
|
701
|
+
const metaFileHandle = await metadataHandle.getFileHandle(`${encodedKey}.json`, {
|
|
702
|
+
create: true
|
|
703
|
+
});
|
|
704
|
+
const metaWritable = await metaFileHandle.createWritable();
|
|
705
|
+
await metaWritable.write(JSON.stringify(fullMetadata));
|
|
706
|
+
await metaWritable.close();
|
|
707
|
+
const blobFileHandle = await blobsHandle.getFileHandle(encodedKey, { create: true });
|
|
708
|
+
const blobWritable = await blobFileHandle.createWritable();
|
|
709
|
+
await blobWritable.write(blob);
|
|
710
|
+
await blobWritable.close();
|
|
711
|
+
} catch (error) {
|
|
712
|
+
await removeFiles(encodedKey);
|
|
713
|
+
throw error;
|
|
714
|
+
}
|
|
676
715
|
const legacy = legacyOpfsFilename(key);
|
|
677
716
|
if (legacy) await removeFiles(legacy);
|
|
678
717
|
}
|
|
@@ -897,20 +936,26 @@ async function initDirectories() {
|
|
|
897
936
|
async function storeBlob(key, blob, metadata) {
|
|
898
937
|
if (!blobsHandle || !metadataHandle) throw new Error('Storage not initialized');
|
|
899
938
|
const encodedKey = encodeKey(key);
|
|
900
|
-
const blobFileHandle = await blobsHandle.getFileHandle(encodedKey, { create: true });
|
|
901
|
-
const blobWritable = await blobFileHandle.createWritable();
|
|
902
|
-
await blobWritable.write(blob);
|
|
903
|
-
await blobWritable.close();
|
|
904
939
|
const fullMetadata = {
|
|
905
940
|
...metadata,
|
|
906
941
|
size: blob.size,
|
|
907
942
|
contentType: blob.type || (metadata && metadata.contentType),
|
|
908
943
|
createdAt: (metadata && metadata.createdAt) || Date.now(),
|
|
909
944
|
};
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
945
|
+
// Metadata first, so an interrupted write leaves an entry cleanup can expire
|
|
946
|
+
try {
|
|
947
|
+
const metaFileHandle = await metadataHandle.getFileHandle(encodedKey + '.json', { create: true });
|
|
948
|
+
const metaWritable = await metaFileHandle.createWritable();
|
|
949
|
+
await metaWritable.write(JSON.stringify(fullMetadata));
|
|
950
|
+
await metaWritable.close();
|
|
951
|
+
const blobFileHandle = await blobsHandle.getFileHandle(encodedKey, { create: true });
|
|
952
|
+
const blobWritable = await blobFileHandle.createWritable();
|
|
953
|
+
await blobWritable.write(blob);
|
|
954
|
+
await blobWritable.close();
|
|
955
|
+
} catch (error) {
|
|
956
|
+
await removeFiles(encodedKey);
|
|
957
|
+
throw error;
|
|
958
|
+
}
|
|
914
959
|
const legacy = legacyFilename(key);
|
|
915
960
|
if (legacy) await removeFiles(legacy);
|
|
916
961
|
}
|
|
@@ -1156,22 +1201,27 @@ var OPFSAdapter = class {
|
|
|
1156
1201
|
}
|
|
1157
1202
|
try {
|
|
1158
1203
|
const encodedKey = this.encodeKey(key);
|
|
1159
|
-
const blobFileHandle = await this.blobsHandle.getFileHandle(encodedKey, { create: true });
|
|
1160
|
-
const blobWritable = await blobFileHandle.createWritable();
|
|
1161
|
-
await blobWritable.write(blob);
|
|
1162
|
-
await blobWritable.close();
|
|
1163
1204
|
const fullMetadata = {
|
|
1164
1205
|
...metadata,
|
|
1165
1206
|
size: blob.size,
|
|
1166
1207
|
contentType: blob.type || metadata?.contentType,
|
|
1167
1208
|
createdAt: metadata?.createdAt ?? Date.now()
|
|
1168
1209
|
};
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1210
|
+
try {
|
|
1211
|
+
const metaFileHandle = await this.metadataHandle.getFileHandle(`${encodedKey}.json`, {
|
|
1212
|
+
create: true
|
|
1213
|
+
});
|
|
1214
|
+
const metaWritable = await metaFileHandle.createWritable();
|
|
1215
|
+
await metaWritable.write(JSON.stringify(fullMetadata));
|
|
1216
|
+
await metaWritable.close();
|
|
1217
|
+
const blobFileHandle = await this.blobsHandle.getFileHandle(encodedKey, { create: true });
|
|
1218
|
+
const blobWritable = await blobFileHandle.createWritable();
|
|
1219
|
+
await blobWritable.write(blob);
|
|
1220
|
+
await blobWritable.close();
|
|
1221
|
+
} catch (error) {
|
|
1222
|
+
await this.removeFiles(encodedKey);
|
|
1223
|
+
throw error;
|
|
1224
|
+
}
|
|
1175
1225
|
const legacy = legacyOpfsFilename(key);
|
|
1176
1226
|
if (legacy) await this.removeFiles(legacy);
|
|
1177
1227
|
} catch (error) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DEFAULT_EXPIRATIONS } from './chunk-
|
|
1
|
+
import { DEFAULT_EXPIRATIONS } from './chunk-QS7N4PTV.js';
|
|
2
2
|
|
|
3
3
|
// src/drafts/types.ts
|
|
4
4
|
var DRAFT_PREFIX = "draft:";
|
|
@@ -66,6 +66,24 @@ function isDraftV2Key(key) {
|
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
// src/drafts/manager.ts
|
|
69
|
+
var draftLocks = /* @__PURE__ */ new Map();
|
|
70
|
+
async function withDraftLock(draftId, fn) {
|
|
71
|
+
const previous = draftLocks.get(draftId) ?? Promise.resolve();
|
|
72
|
+
const run = previous.then(fn, fn);
|
|
73
|
+
const tail = run.catch(() => void 0);
|
|
74
|
+
draftLocks.set(draftId, tail);
|
|
75
|
+
try {
|
|
76
|
+
return await run;
|
|
77
|
+
} finally {
|
|
78
|
+
if (draftLocks.get(draftId) === tail) {
|
|
79
|
+
draftLocks.delete(draftId);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function draftLifetime(metadata) {
|
|
84
|
+
const lifetime = metadata.expiresAt - metadata.updatedAt;
|
|
85
|
+
return lifetime > 0 ? lifetime : DEFAULT_EXPIRATIONS.DRAFT;
|
|
86
|
+
}
|
|
69
87
|
var DraftManagerService = class {
|
|
70
88
|
constructor(adapter) {
|
|
71
89
|
this.adapter = adapter;
|
|
@@ -204,33 +222,44 @@ var DraftManagerService = class {
|
|
|
204
222
|
// Update Operations
|
|
205
223
|
// ============================================
|
|
206
224
|
/**
|
|
207
|
-
* Update draft data
|
|
225
|
+
* Update draft data. This is a local edit: it bumps `version` and
|
|
226
|
+
* `updatedAt` and extends the draft's expiry by its original lifetime.
|
|
227
|
+
*
|
|
228
|
+
* Returns false if the draft does not exist (or has expired), or if
|
|
229
|
+
* `options.expectedVersion` no longer matches.
|
|
208
230
|
*/
|
|
209
|
-
async updateDraft(draftId, data, fileRefs) {
|
|
231
|
+
async updateDraft(draftId, data, fileRefs, options = {}) {
|
|
232
|
+
return withDraftLock(draftId, () => this.writeDraftData(draftId, data, fileRefs, options));
|
|
233
|
+
}
|
|
234
|
+
async writeDraftData(draftId, data, fileRefs, options) {
|
|
210
235
|
const draft = await this.getDraft(draftId);
|
|
211
236
|
if (!draft) {
|
|
212
237
|
return false;
|
|
213
238
|
}
|
|
239
|
+
if (options.expectedVersion !== void 0 && draft.metadata.version !== options.expectedVersion) {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
214
242
|
const now = Date.now();
|
|
215
243
|
const updatedFileRefs = fileRefs ?? draft.fileRefs;
|
|
216
244
|
const fileCount = Object.values(updatedFileRefs).flat().length;
|
|
245
|
+
const lifetime = draftLifetime(draft.metadata);
|
|
217
246
|
const updatedDraft = {
|
|
218
247
|
metadata: {
|
|
219
248
|
...draft.metadata,
|
|
220
249
|
updatedAt: now,
|
|
250
|
+
expiresAt: now + lifetime,
|
|
221
251
|
version: draft.metadata.version + 1,
|
|
222
252
|
deviceId: this.deviceId,
|
|
223
253
|
fileCount,
|
|
224
254
|
// Mark as pending upload if was synced
|
|
225
255
|
syncStatus: draft.metadata.syncStatus === "synced" ? "pending-upload" : draft.metadata.syncStatus
|
|
226
256
|
},
|
|
227
|
-
data: { ...draft.data, ...data },
|
|
257
|
+
data: options.replace ? { ...data } : { ...draft.data, ...data },
|
|
228
258
|
fileRefs: updatedFileRefs
|
|
229
259
|
};
|
|
230
260
|
const key = getDraftV2Key(draft.metadata.formKey, draftId);
|
|
231
|
-
const ttl = updatedDraft.metadata.expiresAt - now;
|
|
232
261
|
await this.adapter.storeJSON(key, updatedDraft, {
|
|
233
|
-
ttl:
|
|
262
|
+
ttl: lifetime,
|
|
234
263
|
tags: [
|
|
235
264
|
"draft",
|
|
236
265
|
"draft-v2",
|
|
@@ -241,23 +270,43 @@ var DraftManagerService = class {
|
|
|
241
270
|
return true;
|
|
242
271
|
}
|
|
243
272
|
/**
|
|
244
|
-
* Update draft metadata only
|
|
273
|
+
* Update draft metadata only.
|
|
274
|
+
*
|
|
275
|
+
* Sync bookkeeping (`syncStatus`, `remoteId`, `lastSyncedAt`, `syncedVersion`)
|
|
276
|
+
* is not a local edit and leaves `version` and `updatedAt` alone. Renaming
|
|
277
|
+
* is: it bumps `version` and marks a synced draft `pending-upload`, unless
|
|
278
|
+
* the same update sets `syncStatus`. Setting `syncStatus: 'synced'` without
|
|
279
|
+
* a `syncedVersion` records the resulting version as synced.
|
|
280
|
+
*
|
|
281
|
+
* Returns false if the draft does not exist, or if
|
|
282
|
+
* `options.expectedVersion` no longer matches.
|
|
245
283
|
*/
|
|
246
|
-
async updateDraftMetadata(draftId, updates) {
|
|
284
|
+
async updateDraftMetadata(draftId, updates, options = {}) {
|
|
285
|
+
return withDraftLock(draftId, () => this.writeDraftMetadata(draftId, updates, options));
|
|
286
|
+
}
|
|
287
|
+
async writeDraftMetadata(draftId, updates, options) {
|
|
247
288
|
const draft = await this.getDraft(draftId);
|
|
248
289
|
if (!draft) {
|
|
249
290
|
return false;
|
|
250
291
|
}
|
|
292
|
+
if (options.expectedVersion !== void 0 && draft.metadata.version !== options.expectedVersion) {
|
|
293
|
+
return false;
|
|
294
|
+
}
|
|
251
295
|
const now = Date.now();
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
296
|
+
const renamed = updates.name !== void 0 && updates.name !== draft.metadata.name;
|
|
297
|
+
const metadata = { ...draft.metadata, ...updates };
|
|
298
|
+
if (renamed) {
|
|
299
|
+
metadata.version = draft.metadata.version + 1;
|
|
300
|
+
metadata.updatedAt = now;
|
|
301
|
+
metadata.expiresAt = now + draftLifetime(draft.metadata);
|
|
302
|
+
if (updates.syncStatus === void 0 && draft.metadata.syncStatus === "synced") {
|
|
303
|
+
metadata.syncStatus = "pending-upload";
|
|
259
304
|
}
|
|
260
|
-
}
|
|
305
|
+
}
|
|
306
|
+
if (updates.syncStatus === "synced" && updates.syncedVersion === void 0) {
|
|
307
|
+
metadata.syncedVersion = metadata.version;
|
|
308
|
+
}
|
|
309
|
+
const updatedDraft = { ...draft, metadata };
|
|
261
310
|
const key = getDraftV2Key(draft.metadata.formKey, draftId);
|
|
262
311
|
const ttl = updatedDraft.metadata.expiresAt - now;
|
|
263
312
|
await this.adapter.storeJSON(key, updatedDraft, {
|
|
@@ -275,18 +324,29 @@ var DraftManagerService = class {
|
|
|
275
324
|
// Delete Operations
|
|
276
325
|
// ============================================
|
|
277
326
|
/**
|
|
278
|
-
* Delete a draft
|
|
327
|
+
* Delete a draft.
|
|
328
|
+
*
|
|
329
|
+
* Returns false if the draft does not exist, or if
|
|
330
|
+
* `options.expectedVersion` no longer matches (it was edited meanwhile).
|
|
279
331
|
*/
|
|
280
|
-
async deleteDraft(draftId, deleteFiles = false) {
|
|
332
|
+
async deleteDraft(draftId, deleteFiles = false, options = {}) {
|
|
333
|
+
return withDraftLock(draftId, () => this.removeDraft(draftId, deleteFiles, options));
|
|
334
|
+
}
|
|
335
|
+
async removeDraft(draftId, deleteFiles, options) {
|
|
281
336
|
const draft = await this.getDraft(draftId);
|
|
282
337
|
if (!draft) {
|
|
283
338
|
return false;
|
|
284
339
|
}
|
|
340
|
+
if (options.expectedVersion !== void 0 && draft.metadata.version !== options.expectedVersion) {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
285
343
|
const key = getDraftV2Key(draft.metadata.formKey, draftId);
|
|
286
344
|
await this.adapter.deleteJSON(key);
|
|
287
345
|
if (deleteFiles) {
|
|
288
346
|
const fileIds = Object.values(draft.fileRefs).flat();
|
|
347
|
+
const shared = fileIds.length > 0 ? await this.referencedFileIds() : /* @__PURE__ */ new Set();
|
|
289
348
|
for (const fileId of fileIds) {
|
|
349
|
+
if (shared.has(fileId)) continue;
|
|
290
350
|
try {
|
|
291
351
|
await this.adapter.deleteBlob(fileId);
|
|
292
352
|
} catch {
|
|
@@ -295,6 +355,23 @@ var DraftManagerService = class {
|
|
|
295
355
|
}
|
|
296
356
|
return true;
|
|
297
357
|
}
|
|
358
|
+
/**
|
|
359
|
+
* File IDs referenced by any stored draft (multi-draft and legacy)
|
|
360
|
+
*/
|
|
361
|
+
async referencedFileIds() {
|
|
362
|
+
const ids = /* @__PURE__ */ new Set();
|
|
363
|
+
const keys = [
|
|
364
|
+
...await this.adapter.listJSON(DRAFT_V2_PREFIX),
|
|
365
|
+
...(await this.adapter.listJSON(DRAFT_PREFIX)).filter(isLegacyDraftKey)
|
|
366
|
+
];
|
|
367
|
+
for (const key of keys) {
|
|
368
|
+
const entry = await this.adapter.getJSON(key);
|
|
369
|
+
for (const id of Object.values(entry?.data?.fileRefs ?? {}).flat()) {
|
|
370
|
+
ids.add(id);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return ids;
|
|
374
|
+
}
|
|
298
375
|
/**
|
|
299
376
|
* Delete all drafts for a form key
|
|
300
377
|
*/
|