@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 +2 -2
- package/dist/cache/index.d.ts +17 -1
- package/dist/cache/index.js +6 -6
- package/dist/{chunk-DIXYWY34.js → chunk-34PR6T4B.js} +216 -60
- package/dist/{chunk-J2ZYJDJX.js → chunk-4KL3GDYP.js} +94 -44
- package/dist/{chunk-PEQVHD6Q.js → chunk-JPXEFKZO.js} +97 -23
- package/dist/{chunk-WWKATW37.js → chunk-MA4ZHPQS.js} +95 -18
- package/dist/{chunk-ZC7F2HDV.js → chunk-QS7N4PTV.js} +5 -2
- package/dist/{chunk-U27TKOYZ.js → chunk-R2IP2AA5.js} +2 -2
- 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 +64 -7
- package/dist/sync/index.js +3 -3
- package/dist/{types-Ho1JiLQR.d.ts → types-CRMTQnjY.d.ts} +6 -1
- package/package.json +1 -1
|
@@ -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,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createFileStorageService } from './chunk-
|
|
3
|
-
import { createDraftStorageService } from './chunk-
|
|
4
|
-
import { createDraftManagerService } from './chunk-
|
|
5
|
-
import { DEFAULT_EXPIRATIONS, CleanupScheduler } from './chunk-
|
|
1
|
+
import { OfflineStorageError, createAdapter, detectAvailableAdapters } from './chunk-4KL3GDYP.js';
|
|
2
|
+
import { createFileStorageService } from './chunk-R2IP2AA5.js';
|
|
3
|
+
import { createDraftStorageService } from './chunk-UL7MZBSF.js';
|
|
4
|
+
import { createDraftManagerService } from './chunk-MA4ZHPQS.js';
|
|
5
|
+
import { DEFAULT_EXPIRATIONS, CleanupScheduler } from './chunk-QS7N4PTV.js';
|
|
6
6
|
|
|
7
7
|
// src/cache/types.ts
|
|
8
8
|
var CACHE_PREFIX = "cache:";
|
|
@@ -21,6 +21,13 @@ var DEFAULT_IN_FLIGHT_TIMEOUT = 3e4;
|
|
|
21
21
|
var DEFAULT_MAX_IN_FLIGHT = 100;
|
|
22
22
|
var DEFAULT_MAX_ENTRIES = 1e3;
|
|
23
23
|
var DEFAULT_MAX_SIZE_BYTES = 50 * 1024 * 1024;
|
|
24
|
+
function estimateSize(entry) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.stringify(entry)?.length ?? 0;
|
|
27
|
+
} catch {
|
|
28
|
+
return 0;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
24
31
|
var CacheService = class {
|
|
25
32
|
constructor(adapter, options) {
|
|
26
33
|
this.adapter = adapter;
|
|
@@ -33,6 +40,11 @@ var CacheService = class {
|
|
|
33
40
|
this.inFlightFetches = /* @__PURE__ */ new Map();
|
|
34
41
|
// Track access order for LRU eviction (key -> last access timestamp)
|
|
35
42
|
this.accessOrder = /* @__PURE__ */ new Map();
|
|
43
|
+
// Approximate size of each of this cache's entries (key -> bytes), loaded
|
|
44
|
+
// lazily from storage. Size limits count only these, never other data on
|
|
45
|
+
// the origin (files, drafts, other caches) that storage.estimate() reports.
|
|
46
|
+
this.entrySizes = null;
|
|
47
|
+
this.entrySizesLoading = null;
|
|
36
48
|
this.inFlightTimeout = options?.inFlightTimeout ?? DEFAULT_IN_FLIGHT_TIMEOUT;
|
|
37
49
|
this.maxInFlight = options?.maxInFlight ?? DEFAULT_MAX_IN_FLIGHT;
|
|
38
50
|
this.maxEntries = options?.maxEntries ?? DEFAULT_MAX_ENTRIES;
|
|
@@ -99,17 +111,39 @@ var CacheService = class {
|
|
|
99
111
|
expiresAt: ttl > 0 ? now + ttl : null,
|
|
100
112
|
tags: options.tags
|
|
101
113
|
};
|
|
102
|
-
|
|
114
|
+
const size = estimateSize(entry);
|
|
115
|
+
await this.enforceLimit(key, size);
|
|
116
|
+
const staleTime = options.staleTime ?? ttl;
|
|
103
117
|
await this.adapter.storeJSON(storageKey, entry, {
|
|
104
|
-
tags: options.tags ? [...options.tags, "cache"] : ["cache"]
|
|
118
|
+
tags: options.tags ? [...options.tags, "cache"] : ["cache"],
|
|
119
|
+
...ttl > 0 && { ttl: ttl + Math.max(0, staleTime) }
|
|
105
120
|
});
|
|
106
121
|
this.accessOrder.set(key, now);
|
|
122
|
+
this.entrySizes?.set(key, size);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Sizes of this cache's entries, read from storage the first time
|
|
126
|
+
*/
|
|
127
|
+
async getEntrySizes() {
|
|
128
|
+
if (this.entrySizes) return this.entrySizes;
|
|
129
|
+
this.entrySizesLoading ?? (this.entrySizesLoading = (async () => {
|
|
130
|
+
const sizes = /* @__PURE__ */ new Map();
|
|
131
|
+
for (const key of await this.keys()) {
|
|
132
|
+
const entry = await this.adapter.getJSON(getCacheKey(key));
|
|
133
|
+
if (entry) sizes.set(key, estimateSize(entry.data));
|
|
134
|
+
}
|
|
135
|
+
this.entrySizes = sizes;
|
|
136
|
+
this.entrySizesLoading = null;
|
|
137
|
+
return sizes;
|
|
138
|
+
})());
|
|
139
|
+
return this.entrySizesLoading;
|
|
107
140
|
}
|
|
108
141
|
/**
|
|
109
142
|
* Enforce cache size limits using LRU eviction
|
|
110
143
|
* @param newKey - Key being added (skip count check if it already exists)
|
|
144
|
+
* @param newSize - Approximate size of the entry being written
|
|
111
145
|
*/
|
|
112
|
-
async enforceLimit(newKey) {
|
|
146
|
+
async enforceLimit(newKey, newSize = 0) {
|
|
113
147
|
const keys = await this.keys();
|
|
114
148
|
const isNewEntry = newKey ? !keys.includes(newKey) : true;
|
|
115
149
|
if (isNewEntry && keys.length >= this.maxEntries) {
|
|
@@ -117,24 +151,42 @@ var CacheService = class {
|
|
|
117
151
|
await this.evictLRU(keys, evictCount);
|
|
118
152
|
}
|
|
119
153
|
try {
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
154
|
+
const sizes = await this.getEntrySizes();
|
|
155
|
+
const current = await this.keys();
|
|
156
|
+
const live = new Set(current);
|
|
157
|
+
for (const key of sizes.keys()) {
|
|
158
|
+
if (!live.has(key)) sizes.delete(key);
|
|
159
|
+
}
|
|
160
|
+
const candidates = current.filter((key) => key !== newKey);
|
|
161
|
+
let total = newSize;
|
|
162
|
+
for (const key of candidates) total += sizes.get(key) ?? 0;
|
|
163
|
+
if (total <= this.maxSizeBytes) return;
|
|
164
|
+
const sorted = this.sortByAccess(candidates);
|
|
165
|
+
const toEvict = [];
|
|
166
|
+
for (const key of sorted) {
|
|
167
|
+
if (total <= this.maxSizeBytes) break;
|
|
168
|
+
total -= sizes.get(key) ?? 0;
|
|
169
|
+
toEvict.push(key);
|
|
124
170
|
}
|
|
171
|
+
await this.evictLRU(toEvict, toEvict.length);
|
|
125
172
|
} catch {
|
|
126
173
|
}
|
|
127
174
|
}
|
|
128
175
|
/**
|
|
129
|
-
*
|
|
176
|
+
* Sort keys by access time, oldest first
|
|
130
177
|
*/
|
|
131
|
-
|
|
132
|
-
|
|
178
|
+
sortByAccess(keys) {
|
|
179
|
+
return [...keys].sort((a, b) => {
|
|
133
180
|
const accessA = this.accessOrder.get(a) ?? 0;
|
|
134
181
|
const accessB = this.accessOrder.get(b) ?? 0;
|
|
135
182
|
return accessA - accessB;
|
|
136
183
|
});
|
|
137
|
-
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Evict least recently used entries
|
|
187
|
+
*/
|
|
188
|
+
async evictLRU(keys, count) {
|
|
189
|
+
const toEvict = this.sortByAccess(keys).slice(0, count);
|
|
138
190
|
for (const key of toEvict) {
|
|
139
191
|
await this.invalidate(key);
|
|
140
192
|
this.accessOrder.delete(key);
|
|
@@ -164,12 +216,12 @@ var CacheService = class {
|
|
|
164
216
|
const now = Date.now();
|
|
165
217
|
const age = now - entry.createdAt;
|
|
166
218
|
if (age < (entry.expiresAt !== null ? entry.expiresAt - entry.createdAt : 0) + staleThreshold) {
|
|
167
|
-
void this.revalidateInBackground(key, fetcher, { ttl, tags });
|
|
219
|
+
void this.revalidateInBackground(key, fetcher, { ttl, tags, staleTime });
|
|
168
220
|
return cached.value;
|
|
169
221
|
}
|
|
170
222
|
}
|
|
171
223
|
}
|
|
172
|
-
return this.fetchAndCache(key, fetcher, { ttl, tags }, onFetching, onFetchComplete);
|
|
224
|
+
return this.fetchAndCache(key, fetcher, { ttl, tags, staleTime }, onFetching, onFetchComplete);
|
|
173
225
|
}
|
|
174
226
|
/**
|
|
175
227
|
* Fetch and cache a value (with deduplication)
|
|
@@ -222,12 +274,14 @@ var CacheService = class {
|
|
|
222
274
|
const storageKey = getCacheKey(key);
|
|
223
275
|
await this.adapter.deleteJSON(storageKey);
|
|
224
276
|
this.accessOrder.delete(key);
|
|
277
|
+
this.entrySizes?.delete(key);
|
|
225
278
|
}
|
|
226
279
|
/**
|
|
227
280
|
* Invalidate all entries with a specific tag
|
|
228
281
|
*/
|
|
229
282
|
async invalidateByTag(tag) {
|
|
230
283
|
this.cleanupStaleInFlight();
|
|
284
|
+
this.entrySizes = null;
|
|
231
285
|
return this.adapter.deleteJSONByTag(tag);
|
|
232
286
|
}
|
|
233
287
|
/**
|
|
@@ -237,6 +291,7 @@ var CacheService = class {
|
|
|
237
291
|
this.cleanupStaleInFlight();
|
|
238
292
|
const count = await this.adapter.deleteJSONByTag("cache");
|
|
239
293
|
this.accessOrder.clear();
|
|
294
|
+
this.entrySizes = null;
|
|
240
295
|
return count;
|
|
241
296
|
}
|
|
242
297
|
/**
|
|
@@ -328,13 +383,32 @@ async function initOfflineStorage(options) {
|
|
|
328
383
|
initPromise = null;
|
|
329
384
|
}
|
|
330
385
|
}
|
|
386
|
+
async function createInitializedAdapter(preferredAdapters, dbName) {
|
|
387
|
+
let remaining = [...preferredAdapters];
|
|
388
|
+
for (; ; ) {
|
|
389
|
+
const { adapter, adapterName } = await createAdapter({
|
|
390
|
+
preferredAdapters: remaining,
|
|
391
|
+
dbName
|
|
392
|
+
});
|
|
393
|
+
try {
|
|
394
|
+
await adapter.initialize();
|
|
395
|
+
return { adapter, adapterName };
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (adapterName === "memory") {
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
console.warn(`[OfflineStorage] ${adapterName} adapter failed to initialize:`, error);
|
|
401
|
+
await adapter.dispose().catch(() => void 0);
|
|
402
|
+
remaining = remaining.slice(remaining.indexOf(adapterName) + 1);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
331
406
|
async function doInitialize(options) {
|
|
332
407
|
const mergedOptions = { ...DEFAULT_OPTIONS, ...options };
|
|
333
|
-
const { adapter, adapterName } = await
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
await adapter.initialize();
|
|
408
|
+
const { adapter, adapterName } = await createInitializedAdapter(
|
|
409
|
+
mergedOptions.preferredAdapters,
|
|
410
|
+
mergedOptions.dbName
|
|
411
|
+
);
|
|
338
412
|
const files = createFileStorageService(adapter);
|
|
339
413
|
const drafts = createDraftStorageService(adapter);
|
|
340
414
|
const draftManager = createDraftManagerService(adapter);
|
|
@@ -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
|
*/
|
|
@@ -91,8 +91,11 @@ function isExpired(expiresAt) {
|
|
|
91
91
|
var DEFAULT_EXPIRATIONS = {
|
|
92
92
|
/** Form draft expiration: 7 days */
|
|
93
93
|
DRAFT: 7 * 24 * 60 * 60 * 1e3,
|
|
94
|
-
/**
|
|
95
|
-
|
|
94
|
+
/**
|
|
95
|
+
* File attachment expiration: 7 days, the same as drafts, so a restored
|
|
96
|
+
* draft still has its attachments
|
|
97
|
+
*/
|
|
98
|
+
FILE: 7 * 24 * 60 * 60 * 1e3,
|
|
96
99
|
/** Cache entry expiration: 1 hour */
|
|
97
100
|
CACHE: 60 * 60 * 1e3
|
|
98
101
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DEFAULT_EXPIRATIONS } from './chunk-
|
|
1
|
+
import { DEFAULT_EXPIRATIONS } from './chunk-QS7N4PTV.js';
|
|
2
2
|
|
|
3
3
|
// src/files/types.ts
|
|
4
4
|
function storedFileToBlobMetadata(file) {
|
|
@@ -58,7 +58,7 @@ var FileStorageService = class {
|
|
|
58
58
|
if (constraints.maxFiles !== void 0) {
|
|
59
59
|
const totalCount = existingCount + files.length;
|
|
60
60
|
if (totalCount > constraints.maxFiles) {
|
|
61
|
-
const excess = files.slice(constraints.maxFiles - existingCount);
|
|
61
|
+
const excess = files.slice(Math.max(0, constraints.maxFiles - existingCount));
|
|
62
62
|
for (const file of excess) {
|
|
63
63
|
errors.push({
|
|
64
64
|
file,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { getDraftKey, DRAFT_PREFIX, getFormKeyFromDraftKey } from './chunk-
|
|
2
|
-
import { DEFAULT_EXPIRATIONS } from './chunk-
|
|
1
|
+
import { getDraftKey, DRAFT_PREFIX, getFormKeyFromDraftKey } from './chunk-MA4ZHPQS.js';
|
|
2
|
+
import { DEFAULT_EXPIRATIONS } from './chunk-QS7N4PTV.js';
|
|
3
3
|
|
|
4
4
|
// src/drafts/service.ts
|
|
5
5
|
var DraftStorageService = class {
|