@classic-homes/offline-svelte 0.1.4 → 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/dist/useDraftSync.svelte.js +32 -16
- package/dist/usePersistedForm.svelte.js +106 -28
- package/package.json +4 -7
- package/dist/__tests__/setup.d.ts +0 -1
- package/dist/__tests__/setup.js +0 -48
- package/dist/__tests__/useFileStorage.test.d.ts +0 -1
- package/dist/__tests__/useFileStorage.test.js +0 -139
- package/dist/__tests__/useOfflineCache.test.d.ts +0 -1
- package/dist/__tests__/useOfflineCache.test.js +0 -119
- package/dist/__tests__/usePersistedForm.test.d.ts +0 -1
- package/dist/__tests__/usePersistedForm.test.js +0 -150
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
* {/if}
|
|
44
44
|
* ```
|
|
45
45
|
*/
|
|
46
|
-
import {
|
|
46
|
+
import { untrack } from 'svelte';
|
|
47
47
|
import { getOfflineStorage, isOfflineStorageInitialized, createSyncService, } from '@classic-homes/offline-core';
|
|
48
48
|
/**
|
|
49
49
|
* Create a draft sync composable
|
|
@@ -61,6 +61,7 @@ export function useDraftSync(options) {
|
|
|
61
61
|
let isAutoSyncActive = $state(false);
|
|
62
62
|
// Sync service instance
|
|
63
63
|
let syncService = null;
|
|
64
|
+
let disposed = false;
|
|
64
65
|
/**
|
|
65
66
|
* Initialize the sync service
|
|
66
67
|
*/
|
|
@@ -69,7 +70,8 @@ export function useDraftSync(options) {
|
|
|
69
70
|
return;
|
|
70
71
|
}
|
|
71
72
|
const storage = getOfflineStorage();
|
|
72
|
-
|
|
73
|
+
// Local reference: dispose() may clear syncService while this awaits
|
|
74
|
+
const service = createSyncService(storage.adapter, {
|
|
73
75
|
adapter,
|
|
74
76
|
syncIntervalMs,
|
|
75
77
|
autoSyncOnReconnect,
|
|
@@ -77,12 +79,15 @@ export function useDraftSync(options) {
|
|
|
77
79
|
isSyncing = false;
|
|
78
80
|
lastSyncAt = result.timestamp;
|
|
79
81
|
lastResult = result;
|
|
80
|
-
|
|
82
|
+
pendingCount = service.pendingCount;
|
|
83
|
+
// The service keeps unresolved conflicts across syncs; a sync that
|
|
84
|
+
// finds no new ones must not clear the list.
|
|
85
|
+
conflicts = service.getConflicts();
|
|
81
86
|
error = result.error ?? null;
|
|
82
87
|
onSyncComplete?.(result);
|
|
83
88
|
},
|
|
84
89
|
onConflictDetected: (newConflicts) => {
|
|
85
|
-
conflicts =
|
|
90
|
+
conflicts = service.getConflicts();
|
|
86
91
|
onConflictDetected?.(newConflicts);
|
|
87
92
|
},
|
|
88
93
|
onOnlineStatusChange: (online) => {
|
|
@@ -95,15 +100,21 @@ export function useDraftSync(options) {
|
|
|
95
100
|
onSyncError?.(err);
|
|
96
101
|
},
|
|
97
102
|
});
|
|
98
|
-
|
|
103
|
+
syncService = service;
|
|
104
|
+
await service.initialize();
|
|
105
|
+
// Destroyed (or disposed) while initializing: dispose() already disposed
|
|
106
|
+
// this service; don't touch it or restart auto-sync
|
|
107
|
+
if (disposed || syncService !== service) {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
99
110
|
// Update state from service
|
|
100
|
-
isOnline =
|
|
101
|
-
lastSyncAt =
|
|
102
|
-
pendingCount =
|
|
103
|
-
conflicts =
|
|
111
|
+
isOnline = service.isOnline;
|
|
112
|
+
lastSyncAt = service.lastSyncAt;
|
|
113
|
+
pendingCount = service.pendingCount;
|
|
114
|
+
conflicts = service.getConflicts();
|
|
104
115
|
// Start auto-sync if enabled
|
|
105
116
|
if (autoSync) {
|
|
106
|
-
|
|
117
|
+
service.startAutoSync();
|
|
107
118
|
isAutoSyncActive = true;
|
|
108
119
|
}
|
|
109
120
|
}
|
|
@@ -220,13 +231,18 @@ export function useDraftSync(options) {
|
|
|
220
231
|
syncService?.dispose();
|
|
221
232
|
syncService = null;
|
|
222
233
|
}
|
|
223
|
-
// Initialize on mount
|
|
234
|
+
// Initialize on mount, clean up on destroy. untrack: initialization writes
|
|
235
|
+
// state this effect must not subscribe to.
|
|
224
236
|
$effect(() => {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
237
|
+
untrack(() => {
|
|
238
|
+
initSyncService().catch((err) => {
|
|
239
|
+
error = err instanceof Error ? err.message : 'Failed to initialize sync';
|
|
240
|
+
});
|
|
241
|
+
});
|
|
242
|
+
return () => {
|
|
243
|
+
disposed = true;
|
|
244
|
+
dispose();
|
|
245
|
+
};
|
|
230
246
|
});
|
|
231
247
|
return {
|
|
232
248
|
get isOnline() {
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
* </script>
|
|
30
30
|
* ```
|
|
31
31
|
*/
|
|
32
|
+
import { untrack } from 'svelte';
|
|
32
33
|
import { getOfflineStorage, isOfflineStorageInitialized, } from '@classic-homes/offline-core';
|
|
33
34
|
const DEFAULT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
34
35
|
const DEFAULT_DEBOUNCE_MS = 500;
|
|
@@ -48,7 +49,14 @@ export function usePersistedForm(options) {
|
|
|
48
49
|
let draftRestored = $state(false);
|
|
49
50
|
let fileRefs = $state({});
|
|
50
51
|
let lastSubmitTime = 0;
|
|
52
|
+
let submitInFlight = false;
|
|
51
53
|
let debounceTimer = null;
|
|
54
|
+
// Settles when the initial draft load finishes; autosaves wait for it
|
|
55
|
+
let loadPromise = Promise.resolve();
|
|
56
|
+
// Fields (and file refs) edited since mount, layered over a draft that
|
|
57
|
+
// finishes loading after the user started typing
|
|
58
|
+
let touched = {};
|
|
59
|
+
let touchedFileRefs = {};
|
|
52
60
|
// Multi-draft state
|
|
53
61
|
let currentDraftId = $state(initialDraftId ?? null);
|
|
54
62
|
let currentDraftMetadata = $state(null);
|
|
@@ -74,9 +82,10 @@ export function usePersistedForm(options) {
|
|
|
74
82
|
// Load current draft for this form
|
|
75
83
|
draft = await storage.draftManager.getCurrentDraft(storageKey);
|
|
76
84
|
}
|
|
85
|
+
// Edits made while the draft was loading stay on top of it
|
|
77
86
|
if (draft) {
|
|
78
|
-
data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data };
|
|
79
|
-
fileRefs = draft.fileRefs
|
|
87
|
+
data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data, ...touched };
|
|
88
|
+
fileRefs = { ...draft.fileRefs, ...touchedFileRefs };
|
|
80
89
|
currentDraftId = draft.metadata.id;
|
|
81
90
|
currentDraftMetadata = draft.metadata;
|
|
82
91
|
draftRestored = true;
|
|
@@ -88,9 +97,9 @@ export function usePersistedForm(options) {
|
|
|
88
97
|
// Legacy single-draft mode
|
|
89
98
|
const result = await storage.drafts.loadDraft(storageKey);
|
|
90
99
|
if (result.restored && result.draft) {
|
|
91
|
-
// Merge draft data with initial values
|
|
92
|
-
data = { ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data };
|
|
93
|
-
fileRefs = result.draft.fileRefs
|
|
100
|
+
// Merge draft data with initial values; edits made while loading win
|
|
101
|
+
data = { ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data, ...touched };
|
|
102
|
+
fileRefs = { ...result.draft.fileRefs, ...touchedFileRefs };
|
|
94
103
|
draftRestored = true;
|
|
95
104
|
onDraftRestored?.();
|
|
96
105
|
}
|
|
@@ -107,18 +116,28 @@ export function usePersistedForm(options) {
|
|
|
107
116
|
if (!isOfflineStorageInitialized() || !isDirty) {
|
|
108
117
|
return;
|
|
109
118
|
}
|
|
119
|
+
// Saving before the stored draft has loaded would create a second draft
|
|
120
|
+
// (or overwrite the stored one) instead of updating it
|
|
121
|
+
await loadPromise;
|
|
110
122
|
try {
|
|
111
123
|
const storage = getOfflineStorage();
|
|
124
|
+
// Snapshot the $state proxies: IndexedDB/OPFS structured cloning throws
|
|
125
|
+
// DataCloneError on proxies (nested values included).
|
|
126
|
+
const dataToPersist = $state.snapshot(data);
|
|
127
|
+
const fileRefsToPersist = $state.snapshot(fileRefs);
|
|
112
128
|
// Filter out excluded fields
|
|
113
|
-
const dataToPersist = { ...data };
|
|
114
129
|
for (const field of excludeFields) {
|
|
115
130
|
delete dataToPersist[field];
|
|
116
131
|
}
|
|
117
132
|
if (multiDraft) {
|
|
118
133
|
// Multi-draft mode: Use DraftManagerService
|
|
134
|
+
// Expired or deleted meanwhile: save the edits as a new draft rather
|
|
135
|
+
// than silently dropping them
|
|
136
|
+
if (currentDraftId &&
|
|
137
|
+
!(await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefsToPersist))) {
|
|
138
|
+
currentDraftId = null;
|
|
139
|
+
}
|
|
119
140
|
if (currentDraftId) {
|
|
120
|
-
// Update existing draft
|
|
121
|
-
await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefs);
|
|
122
141
|
// Update metadata
|
|
123
142
|
const metadata = await storage.draftManager.getDraftMetadata(currentDraftId);
|
|
124
143
|
if (metadata) {
|
|
@@ -130,7 +149,7 @@ export function usePersistedForm(options) {
|
|
|
130
149
|
// Create new draft
|
|
131
150
|
const metadata = await storage.draftManager.createDraft(storageKey, {
|
|
132
151
|
initialData: dataToPersist,
|
|
133
|
-
initialFileRefs:
|
|
152
|
+
initialFileRefs: fileRefsToPersist,
|
|
134
153
|
expirationMs,
|
|
135
154
|
});
|
|
136
155
|
currentDraftId = metadata.id;
|
|
@@ -141,7 +160,7 @@ export function usePersistedForm(options) {
|
|
|
141
160
|
}
|
|
142
161
|
else {
|
|
143
162
|
// Legacy single-draft mode
|
|
144
|
-
await storage.drafts.saveDraft(storageKey, dataToPersist,
|
|
163
|
+
await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefsToPersist, {
|
|
145
164
|
excludeFields: excludeFields,
|
|
146
165
|
expirationMs,
|
|
147
166
|
});
|
|
@@ -155,18 +174,39 @@ export function usePersistedForm(options) {
|
|
|
155
174
|
* Debounced draft saving
|
|
156
175
|
*/
|
|
157
176
|
function scheduleSaveDraft() {
|
|
158
|
-
|
|
159
|
-
clearTimeout(debounceTimer);
|
|
160
|
-
}
|
|
177
|
+
cancelPendingSave();
|
|
161
178
|
debounceTimer = setTimeout(() => {
|
|
179
|
+
debounceTimer = null;
|
|
162
180
|
void saveDraft();
|
|
163
181
|
}, debounceMs);
|
|
164
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Run a queued debounced save now instead of dropping it
|
|
185
|
+
*/
|
|
186
|
+
function flushPendingSave() {
|
|
187
|
+
if (debounceTimer) {
|
|
188
|
+
cancelPendingSave();
|
|
189
|
+
// Next microtask: during an effect teardown Svelte reads $state as it
|
|
190
|
+
// was before the effect's last run, so saving synchronously here would
|
|
191
|
+
// see isDirty === false and save nothing
|
|
192
|
+
void Promise.resolve().then(saveDraft);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Cancel a queued debounced save
|
|
197
|
+
*/
|
|
198
|
+
function cancelPendingSave() {
|
|
199
|
+
if (debounceTimer) {
|
|
200
|
+
clearTimeout(debounceTimer);
|
|
201
|
+
debounceTimer = null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
165
204
|
/**
|
|
166
205
|
* Set a field value
|
|
167
206
|
*/
|
|
168
207
|
function setField(field, value) {
|
|
169
208
|
data[field] = value;
|
|
209
|
+
touched = { ...touched, [field]: value };
|
|
170
210
|
isDirty = true;
|
|
171
211
|
scheduleSaveDraft();
|
|
172
212
|
}
|
|
@@ -175,6 +215,7 @@ export function usePersistedForm(options) {
|
|
|
175
215
|
*/
|
|
176
216
|
function setFields(fields) {
|
|
177
217
|
Object.assign(data, fields);
|
|
218
|
+
touched = { ...touched, ...fields };
|
|
178
219
|
isDirty = true;
|
|
179
220
|
scheduleSaveDraft();
|
|
180
221
|
}
|
|
@@ -221,6 +262,10 @@ export function usePersistedForm(options) {
|
|
|
221
262
|
*/
|
|
222
263
|
async function handleSubmit(event) {
|
|
223
264
|
event?.preventDefault();
|
|
265
|
+
// Ignore re-entry (e.g. a double click) while a submit is in flight
|
|
266
|
+
if (submitInFlight) {
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
224
269
|
// Check cooldown
|
|
225
270
|
const now = Date.now();
|
|
226
271
|
if (now - lastSubmitTime < submitCooldownMs) {
|
|
@@ -231,6 +276,9 @@ export function usePersistedForm(options) {
|
|
|
231
276
|
if (!validate()) {
|
|
232
277
|
return;
|
|
233
278
|
}
|
|
279
|
+
// A queued autosave must not recreate the draft after it is cleared
|
|
280
|
+
cancelPendingSave();
|
|
281
|
+
submitInFlight = true;
|
|
234
282
|
isSubmitting = true;
|
|
235
283
|
globalError = null;
|
|
236
284
|
try {
|
|
@@ -240,14 +288,18 @@ export function usePersistedForm(options) {
|
|
|
240
288
|
lastSubmitTime = now;
|
|
241
289
|
isSubmitted = true;
|
|
242
290
|
// Clear draft on success
|
|
291
|
+
cancelPendingSave();
|
|
243
292
|
await clearDraft();
|
|
244
293
|
}
|
|
245
294
|
catch (err) {
|
|
246
295
|
globalError = err instanceof Error ? err.message : 'Submission failed';
|
|
247
296
|
lastSubmitTime = 0; // Reset cooldown on error
|
|
297
|
+
// The autosave was cancelled for the submit; keep the edits
|
|
298
|
+
void saveDraft();
|
|
248
299
|
throw err;
|
|
249
300
|
}
|
|
250
301
|
finally {
|
|
302
|
+
submitInFlight = false;
|
|
251
303
|
isSubmitting = false;
|
|
252
304
|
}
|
|
253
305
|
}
|
|
@@ -255,11 +307,14 @@ export function usePersistedForm(options) {
|
|
|
255
307
|
* Reset the form
|
|
256
308
|
*/
|
|
257
309
|
function reset() {
|
|
310
|
+
cancelPendingSave();
|
|
258
311
|
data = JSON.parse(JSON.stringify(originalInitialValues));
|
|
259
312
|
errors = {};
|
|
260
313
|
globalError = null;
|
|
261
314
|
isSubmitted = false;
|
|
262
315
|
isDirty = false;
|
|
316
|
+
touched = {};
|
|
317
|
+
touchedFileRefs = {};
|
|
263
318
|
draftRestored = false;
|
|
264
319
|
fileRefs = {};
|
|
265
320
|
void clearDraft();
|
|
@@ -292,20 +347,23 @@ export function usePersistedForm(options) {
|
|
|
292
347
|
}
|
|
293
348
|
try {
|
|
294
349
|
const storage = getOfflineStorage();
|
|
295
|
-
if (multiDraft
|
|
296
|
-
// Multi-draft mode:
|
|
297
|
-
|
|
298
|
-
currentDraftId
|
|
299
|
-
|
|
300
|
-
|
|
350
|
+
if (multiDraft) {
|
|
351
|
+
// Multi-draft mode: delete this draft and only its own files. Other
|
|
352
|
+
// drafts of the same form keep theirs, so no deleteFormFiles here.
|
|
353
|
+
if (currentDraftId) {
|
|
354
|
+
await storage.draftManager.deleteDraft(currentDraftId, true);
|
|
355
|
+
currentDraftId = null;
|
|
356
|
+
currentDraftMetadata = null;
|
|
357
|
+
onDraftChange?.(null);
|
|
358
|
+
}
|
|
301
359
|
}
|
|
302
360
|
else {
|
|
303
361
|
// Legacy single-draft mode
|
|
304
362
|
await storage.drafts.clearDraft(storageKey);
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
363
|
+
// Also clear associated files
|
|
364
|
+
for (const fieldName of fileFields) {
|
|
365
|
+
await storage.files.deleteFormFiles(storageKey, fieldName);
|
|
366
|
+
}
|
|
309
367
|
}
|
|
310
368
|
}
|
|
311
369
|
catch (err) {
|
|
@@ -323,6 +381,7 @@ export function usePersistedForm(options) {
|
|
|
323
381
|
*/
|
|
324
382
|
function updateFileRefs(fieldName, fileIds) {
|
|
325
383
|
fileRefs = { ...fileRefs, [fieldName]: fileIds };
|
|
384
|
+
touchedFileRefs = { ...touchedFileRefs, [fieldName]: fileIds };
|
|
326
385
|
isDirty = true;
|
|
327
386
|
scheduleSaveDraft();
|
|
328
387
|
}
|
|
@@ -338,6 +397,10 @@ export function usePersistedForm(options) {
|
|
|
338
397
|
for (const fieldName of fileFields) {
|
|
339
398
|
const ids = fileRefs[fieldName] || [];
|
|
340
399
|
const fileMap = await storage.files.getFilesAsFileObjects(ids);
|
|
400
|
+
const missing = ids.filter((id) => !fileMap.has(id));
|
|
401
|
+
if (missing.length > 0) {
|
|
402
|
+
console.warn(`[usePersistedForm] ${missing.length} file(s) for "${fieldName}" are missing from storage (expired or deleted)`, missing);
|
|
403
|
+
}
|
|
341
404
|
result[fieldName] = Array.from(fileMap.values());
|
|
342
405
|
}
|
|
343
406
|
return result;
|
|
@@ -350,15 +413,16 @@ export function usePersistedForm(options) {
|
|
|
350
413
|
throw new Error('Offline storage not initialized');
|
|
351
414
|
}
|
|
352
415
|
const storage = getOfflineStorage();
|
|
353
|
-
//
|
|
354
|
-
|
|
416
|
+
// Snapshot the $state proxies (structured clone rejects them), then
|
|
417
|
+
// filter out excluded fields
|
|
418
|
+
const dataToPersist = $state.snapshot(data);
|
|
355
419
|
for (const field of excludeFields) {
|
|
356
420
|
delete dataToPersist[field];
|
|
357
421
|
}
|
|
358
422
|
const metadata = await storage.draftManager.createDraft(storageKey, {
|
|
359
423
|
name,
|
|
360
424
|
initialData: dataToPersist,
|
|
361
|
-
initialFileRefs: fileRefs,
|
|
425
|
+
initialFileRefs: $state.snapshot(fileRefs),
|
|
362
426
|
expirationMs,
|
|
363
427
|
});
|
|
364
428
|
// Switch to the new draft
|
|
@@ -386,6 +450,8 @@ export function usePersistedForm(options) {
|
|
|
386
450
|
currentDraftId = draft.metadata.id;
|
|
387
451
|
currentDraftMetadata = draft.metadata;
|
|
388
452
|
isDirty = false;
|
|
453
|
+
touched = {};
|
|
454
|
+
touchedFileRefs = {};
|
|
389
455
|
draftRestored = true;
|
|
390
456
|
// Set as current draft
|
|
391
457
|
await storage.draftManager.setCurrentDraft(storageKey, draftIdToLoad);
|
|
@@ -393,9 +459,21 @@ export function usePersistedForm(options) {
|
|
|
393
459
|
onDraftRestored?.();
|
|
394
460
|
return true;
|
|
395
461
|
}
|
|
396
|
-
// Load draft on initialization
|
|
462
|
+
// Load draft on initialization. untrack: loadDraft reads currentDraftId
|
|
463
|
+
// (and isDirty), which the composable itself changes on autosave/clear;
|
|
464
|
+
// tracking them would reload and clobber in-progress edits.
|
|
465
|
+
// Destroying the component or leaving the page flushes a queued save
|
|
466
|
+
// rather than dropping the last edits.
|
|
397
467
|
$effect(() => {
|
|
398
|
-
|
|
468
|
+
untrack(() => {
|
|
469
|
+
loadPromise = loadDraft();
|
|
470
|
+
});
|
|
471
|
+
const onPageHide = () => flushPendingSave();
|
|
472
|
+
window.addEventListener('pagehide', onPageHide);
|
|
473
|
+
return () => {
|
|
474
|
+
window.removeEventListener('pagehide', onPageHide);
|
|
475
|
+
flushPendingSave();
|
|
476
|
+
};
|
|
399
477
|
});
|
|
400
478
|
return {
|
|
401
479
|
get data() {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@classic-homes/offline-svelte",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Svelte bindings for offline persistence and caching",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"svelte": "./dist/index.js",
|
|
@@ -29,7 +29,9 @@
|
|
|
29
29
|
},
|
|
30
30
|
"sideEffects": false,
|
|
31
31
|
"files": [
|
|
32
|
-
"dist"
|
|
32
|
+
"dist",
|
|
33
|
+
"!dist/__tests__",
|
|
34
|
+
"!dist/**/*.test.*"
|
|
33
35
|
],
|
|
34
36
|
"scripts": {
|
|
35
37
|
"build": "svelte-package -i src",
|
|
@@ -61,11 +63,6 @@
|
|
|
61
63
|
"svelte": "^5.0.0",
|
|
62
64
|
"zod": "^3.23.0"
|
|
63
65
|
},
|
|
64
|
-
"peerDependenciesMeta": {
|
|
65
|
-
"zod": {
|
|
66
|
-
"optional": true
|
|
67
|
-
}
|
|
68
|
-
},
|
|
69
66
|
"dependencies": {
|
|
70
67
|
"@classic-homes/offline-core": "*"
|
|
71
68
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import 'fake-indexeddb/auto';
|
package/dist/__tests__/setup.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Vitest setup file for Svelte tests
|
|
3
|
-
*/
|
|
4
|
-
import { vi, beforeEach } from 'vitest';
|
|
5
|
-
import 'fake-indexeddb/auto';
|
|
6
|
-
// Mock URL.createObjectURL and revokeObjectURL
|
|
7
|
-
global.URL.createObjectURL = vi.fn((blob) => `blob:mock-${blob.size}`);
|
|
8
|
-
global.URL.revokeObjectURL = vi.fn();
|
|
9
|
-
// Mock navigator.storage
|
|
10
|
-
Object.defineProperty(navigator, 'storage', {
|
|
11
|
-
value: {
|
|
12
|
-
estimate: vi.fn().mockResolvedValue({
|
|
13
|
-
quota: 1000000000,
|
|
14
|
-
usage: 0,
|
|
15
|
-
}),
|
|
16
|
-
},
|
|
17
|
-
writable: true,
|
|
18
|
-
});
|
|
19
|
-
// Mock localStorage for tests
|
|
20
|
-
const localStorageStore = {};
|
|
21
|
-
const localStorageMock = {
|
|
22
|
-
getItem: vi.fn((key) => localStorageStore[key] ?? null),
|
|
23
|
-
setItem: vi.fn((key, value) => {
|
|
24
|
-
localStorageStore[key] = value;
|
|
25
|
-
}),
|
|
26
|
-
removeItem: vi.fn((key) => {
|
|
27
|
-
delete localStorageStore[key];
|
|
28
|
-
}),
|
|
29
|
-
clear: vi.fn(() => {
|
|
30
|
-
for (const key of Object.keys(localStorageStore)) {
|
|
31
|
-
delete localStorageStore[key];
|
|
32
|
-
}
|
|
33
|
-
}),
|
|
34
|
-
get length() {
|
|
35
|
-
return Object.keys(localStorageStore).length;
|
|
36
|
-
},
|
|
37
|
-
key: vi.fn((index) => Object.keys(localStorageStore)[index] ?? null),
|
|
38
|
-
};
|
|
39
|
-
Object.defineProperty(globalThis, 'localStorage', {
|
|
40
|
-
value: localStorageMock,
|
|
41
|
-
writable: true,
|
|
42
|
-
});
|
|
43
|
-
beforeEach(() => {
|
|
44
|
-
for (const key of Object.keys(localStorageStore)) {
|
|
45
|
-
delete localStorageStore[key];
|
|
46
|
-
}
|
|
47
|
-
vi.clearAllMocks();
|
|
48
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,139 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for useFileStorage composable
|
|
3
|
-
*
|
|
4
|
-
* Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
|
|
5
|
-
* These tests focus on the FileStorageService used by the composable.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
8
|
-
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
9
|
-
describe('FileStorageService integration (used by useFileStorage)', () => {
|
|
10
|
-
let storage;
|
|
11
|
-
beforeEach(async () => {
|
|
12
|
-
storage = await initOfflineStorage({
|
|
13
|
-
preferredAdapters: ['memory'],
|
|
14
|
-
});
|
|
15
|
-
});
|
|
16
|
-
afterEach(async () => {
|
|
17
|
-
await storage.cleanup.runCleanup();
|
|
18
|
-
await storage.dispose();
|
|
19
|
-
});
|
|
20
|
-
describe('file validation', () => {
|
|
21
|
-
it('should validate file size', () => {
|
|
22
|
-
const file = new File(['x'.repeat(2000)], 'large.txt', { type: 'text/plain' });
|
|
23
|
-
const errors = storage.files.validateFiles([file], { maxSizeBytes: 1000 });
|
|
24
|
-
expect(errors).toHaveLength(1);
|
|
25
|
-
expect(errors[0].code).toBe('TOO_LARGE');
|
|
26
|
-
});
|
|
27
|
-
it('should validate file count', () => {
|
|
28
|
-
const files = [
|
|
29
|
-
new File(['1'], 'file1.txt'),
|
|
30
|
-
new File(['2'], 'file2.txt'),
|
|
31
|
-
new File(['3'], 'file3.txt'),
|
|
32
|
-
];
|
|
33
|
-
const errors = storage.files.validateFiles(files, { maxFiles: 2 });
|
|
34
|
-
expect(errors).toHaveLength(1);
|
|
35
|
-
expect(errors[0].code).toBe('TOO_MANY_FILES');
|
|
36
|
-
});
|
|
37
|
-
it('should validate file type', () => {
|
|
38
|
-
const file = new File(['data'], 'doc.pdf', { type: 'application/pdf' });
|
|
39
|
-
const errors = storage.files.validateFiles([file], { acceptedTypes: ['image/*'] });
|
|
40
|
-
expect(errors).toHaveLength(1);
|
|
41
|
-
expect(errors[0].code).toBe('INVALID_TYPE');
|
|
42
|
-
});
|
|
43
|
-
it('should accept wildcard MIME types', () => {
|
|
44
|
-
const imageFile = new File(['data'], 'img.png', { type: 'image/png' });
|
|
45
|
-
const errors = storage.files.validateFiles([imageFile], { acceptedTypes: ['image/*'] });
|
|
46
|
-
expect(errors).toHaveLength(0);
|
|
47
|
-
});
|
|
48
|
-
});
|
|
49
|
-
describe('file storage', () => {
|
|
50
|
-
it('should store and retrieve files', async () => {
|
|
51
|
-
const file = new File(['test content'], 'test.txt', { type: 'text/plain' });
|
|
52
|
-
const stored = await storage.files.storeFile(file, {
|
|
53
|
-
formKey: 'form1',
|
|
54
|
-
fieldName: 'attachment',
|
|
55
|
-
});
|
|
56
|
-
expect(stored.id).toMatch(/^file:/);
|
|
57
|
-
expect(stored.filename).toBe('test.txt');
|
|
58
|
-
expect(stored.formKey).toBe('form1');
|
|
59
|
-
expect(stored.fieldName).toBe('attachment');
|
|
60
|
-
const retrieved = await storage.files.getFile(stored.id);
|
|
61
|
-
expect(retrieved).not.toBeNull();
|
|
62
|
-
expect(retrieved.filename).toBe('test.txt');
|
|
63
|
-
});
|
|
64
|
-
it('should store multiple files', async () => {
|
|
65
|
-
const files = [new File(['1'], 'file1.txt'), new File(['2'], 'file2.txt')];
|
|
66
|
-
const stored = await storage.files.storeFiles(files, {
|
|
67
|
-
formKey: 'form1',
|
|
68
|
-
fieldName: 'attachments',
|
|
69
|
-
});
|
|
70
|
-
expect(stored).toHaveLength(2);
|
|
71
|
-
});
|
|
72
|
-
it('should filter files by formKey and fieldName', async () => {
|
|
73
|
-
await storage.files.storeFile(new File(['1'], 'f1.txt'), {
|
|
74
|
-
formKey: 'form1',
|
|
75
|
-
fieldName: 'docs',
|
|
76
|
-
});
|
|
77
|
-
await storage.files.storeFile(new File(['2'], 'f2.txt'), {
|
|
78
|
-
formKey: 'form1',
|
|
79
|
-
fieldName: 'photos',
|
|
80
|
-
});
|
|
81
|
-
await storage.files.storeFile(new File(['3'], 'f3.txt'), {
|
|
82
|
-
formKey: 'form2',
|
|
83
|
-
fieldName: 'docs',
|
|
84
|
-
});
|
|
85
|
-
const form1Files = await storage.files.getFiles({ formKey: 'form1' });
|
|
86
|
-
expect(form1Files).toHaveLength(2);
|
|
87
|
-
const docsFiles = await storage.files.getFiles({ formKey: 'form1', fieldName: 'docs' });
|
|
88
|
-
expect(docsFiles).toHaveLength(1);
|
|
89
|
-
expect(docsFiles[0].fieldName).toBe('docs');
|
|
90
|
-
});
|
|
91
|
-
it('should delete files', async () => {
|
|
92
|
-
const stored = await storage.files.storeFile(new File(['data'], 'test.txt'), {
|
|
93
|
-
formKey: 'form1',
|
|
94
|
-
fieldName: 'doc',
|
|
95
|
-
});
|
|
96
|
-
const deleted = await storage.files.deleteFile(stored.id);
|
|
97
|
-
expect(deleted).toBe(true);
|
|
98
|
-
const retrieved = await storage.files.getFile(stored.id);
|
|
99
|
-
expect(retrieved).toBeNull();
|
|
100
|
-
});
|
|
101
|
-
it('should delete all files for a form', async () => {
|
|
102
|
-
await storage.files.storeFile(new File(['1'], 'f1.txt'), {
|
|
103
|
-
formKey: 'form1',
|
|
104
|
-
fieldName: 'docs',
|
|
105
|
-
});
|
|
106
|
-
await storage.files.storeFile(new File(['2'], 'f2.txt'), {
|
|
107
|
-
formKey: 'form1',
|
|
108
|
-
fieldName: 'photos',
|
|
109
|
-
});
|
|
110
|
-
await storage.files.storeFile(new File(['3'], 'f3.txt'), {
|
|
111
|
-
formKey: 'form2',
|
|
112
|
-
fieldName: 'docs',
|
|
113
|
-
});
|
|
114
|
-
const result = await storage.files.deleteFormFiles('form1');
|
|
115
|
-
expect(result.deletedCount).toBe(2);
|
|
116
|
-
const remaining = await storage.files.getFiles();
|
|
117
|
-
expect(remaining).toHaveLength(1);
|
|
118
|
-
expect(remaining[0].formKey).toBe('form2');
|
|
119
|
-
});
|
|
120
|
-
it('should generate preview URLs for images', async () => {
|
|
121
|
-
const imageFile = new File(['fake image'], 'photo.png', { type: 'image/png' });
|
|
122
|
-
const stored = await storage.files.storeFile(imageFile, {
|
|
123
|
-
formKey: 'form1',
|
|
124
|
-
fieldName: 'photo',
|
|
125
|
-
});
|
|
126
|
-
const retrieved = await storage.files.getFile(stored.id, true);
|
|
127
|
-
expect(retrieved.previewUrl).toBeDefined();
|
|
128
|
-
expect(retrieved.previewUrl).toMatch(/^blob:/);
|
|
129
|
-
});
|
|
130
|
-
it('should convert files back to File objects for submission', async () => {
|
|
131
|
-
const stored = await storage.files.storeFile(new File(['content'], 'test.txt', { type: 'text/plain' }), { formKey: 'form1', fieldName: 'doc' });
|
|
132
|
-
const fileMap = await storage.files.getFilesAsFileObjects([stored.id]);
|
|
133
|
-
expect(fileMap.size).toBe(1);
|
|
134
|
-
const file = fileMap.get(stored.id);
|
|
135
|
-
expect(file.name).toBe('test.txt');
|
|
136
|
-
expect(file.type).toBe('text/plain');
|
|
137
|
-
});
|
|
138
|
-
});
|
|
139
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for useOfflineCache composable
|
|
3
|
-
*
|
|
4
|
-
* Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
|
|
5
|
-
* These tests focus on the utility functions and basic functionality.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
8
|
-
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
9
|
-
import { invalidateCacheByTag, invalidateAllCache } from '../useOfflineCache.svelte.js';
|
|
10
|
-
describe('useOfflineCache utilities', () => {
|
|
11
|
-
let storage;
|
|
12
|
-
beforeEach(async () => {
|
|
13
|
-
storage = await initOfflineStorage({
|
|
14
|
-
preferredAdapters: ['memory'],
|
|
15
|
-
});
|
|
16
|
-
});
|
|
17
|
-
afterEach(async () => {
|
|
18
|
-
await storage.cleanup.runCleanup();
|
|
19
|
-
await storage.dispose();
|
|
20
|
-
});
|
|
21
|
-
describe('invalidateCacheByTag', () => {
|
|
22
|
-
it('should invalidate entries by tag', async () => {
|
|
23
|
-
await storage.cache.set('k1', 'v1', { tags: ['user'] });
|
|
24
|
-
await storage.cache.set('k2', 'v2', { tags: ['user'] });
|
|
25
|
-
await storage.cache.set('k3', 'v3', { tags: ['other'] });
|
|
26
|
-
const deleted = await invalidateCacheByTag('user');
|
|
27
|
-
expect(deleted).toBe(2);
|
|
28
|
-
// Verify entries are gone
|
|
29
|
-
const result1 = await storage.cache.get('k1');
|
|
30
|
-
const result2 = await storage.cache.get('k2');
|
|
31
|
-
const result3 = await storage.cache.get('k3');
|
|
32
|
-
expect(result1.hit).toBe(false);
|
|
33
|
-
expect(result2.hit).toBe(false);
|
|
34
|
-
expect(result3.hit).toBe(true);
|
|
35
|
-
});
|
|
36
|
-
it('should return 0 when no entries match', async () => {
|
|
37
|
-
await storage.cache.set('k1', 'v1', { tags: ['other'] });
|
|
38
|
-
const deleted = await invalidateCacheByTag('nonexistent');
|
|
39
|
-
expect(deleted).toBe(0);
|
|
40
|
-
});
|
|
41
|
-
});
|
|
42
|
-
describe('invalidateAllCache', () => {
|
|
43
|
-
it('should invalidate all cache entries', async () => {
|
|
44
|
-
await storage.cache.set('k1', 'v1');
|
|
45
|
-
await storage.cache.set('k2', 'v2');
|
|
46
|
-
await storage.cache.set('k3', 'v3');
|
|
47
|
-
const deleted = await invalidateAllCache();
|
|
48
|
-
expect(deleted).toBe(3);
|
|
49
|
-
// Verify all entries are gone
|
|
50
|
-
const keys = await storage.cache.keys();
|
|
51
|
-
expect(keys).toHaveLength(0);
|
|
52
|
-
});
|
|
53
|
-
it('should return 0 when cache is empty', async () => {
|
|
54
|
-
const deleted = await invalidateAllCache();
|
|
55
|
-
expect(deleted).toBe(0);
|
|
56
|
-
});
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
describe('CacheService integration (used by useOfflineCache)', () => {
|
|
60
|
-
let storage;
|
|
61
|
-
beforeEach(async () => {
|
|
62
|
-
storage = await initOfflineStorage({
|
|
63
|
-
preferredAdapters: ['memory'],
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
afterEach(async () => {
|
|
67
|
-
await storage.cleanup.runCleanup();
|
|
68
|
-
await storage.dispose();
|
|
69
|
-
});
|
|
70
|
-
it('should support get and set operations', async () => {
|
|
71
|
-
await storage.cache.set('test-key', { name: 'test', value: 42 }, { ttl: 10000 });
|
|
72
|
-
const result = await storage.cache.get('test-key');
|
|
73
|
-
expect(result.hit).toBe(true);
|
|
74
|
-
expect(result.value).toEqual({ name: 'test', value: 42 });
|
|
75
|
-
});
|
|
76
|
-
it('should support getOrSet with fetcher', async () => {
|
|
77
|
-
const fetcher = vi.fn().mockResolvedValue('fetched-value');
|
|
78
|
-
const value = await storage.cache.getOrSet('key', fetcher, { ttl: 10000 });
|
|
79
|
-
expect(value).toBe('fetched-value');
|
|
80
|
-
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
81
|
-
// Second call should use cache
|
|
82
|
-
const value2 = await storage.cache.getOrSet('key', fetcher);
|
|
83
|
-
expect(value2).toBe('fetched-value');
|
|
84
|
-
expect(fetcher).toHaveBeenCalledTimes(1);
|
|
85
|
-
});
|
|
86
|
-
it('should support invalidation', async () => {
|
|
87
|
-
await storage.cache.set('key', 'value');
|
|
88
|
-
await storage.cache.invalidate('key');
|
|
89
|
-
const result = await storage.cache.get('key');
|
|
90
|
-
expect(result.hit).toBe(false);
|
|
91
|
-
});
|
|
92
|
-
it('should track staleness', async () => {
|
|
93
|
-
vi.useFakeTimers();
|
|
94
|
-
const now = Date.now();
|
|
95
|
-
vi.setSystemTime(now);
|
|
96
|
-
await storage.cache.set('key', 'value', { ttl: 1000 });
|
|
97
|
-
// Fresh
|
|
98
|
-
let result = await storage.cache.get('key');
|
|
99
|
-
expect(result.hit).toBe(true);
|
|
100
|
-
expect(result.stale).toBe(false);
|
|
101
|
-
// Expired (stale)
|
|
102
|
-
vi.setSystemTime(now + 2000);
|
|
103
|
-
result = await storage.cache.get('key');
|
|
104
|
-
expect(result.hit).toBe(true);
|
|
105
|
-
expect(result.stale).toBe(true);
|
|
106
|
-
vi.useRealTimers();
|
|
107
|
-
});
|
|
108
|
-
it('should support tags for bulk invalidation', async () => {
|
|
109
|
-
await storage.cache.set('user:1', { name: 'John' }, { tags: ['user', 'active'] });
|
|
110
|
-
await storage.cache.set('user:2', { name: 'Jane' }, { tags: ['user', 'inactive'] });
|
|
111
|
-
await storage.cache.set('post:1', { title: 'Hello' }, { tags: ['post'] });
|
|
112
|
-
const deleted = await storage.cache.invalidateByTag('user');
|
|
113
|
-
expect(deleted).toBe(2);
|
|
114
|
-
const userResult = await storage.cache.get('user:1');
|
|
115
|
-
expect(userResult.hit).toBe(false);
|
|
116
|
-
const postResult = await storage.cache.get('post:1');
|
|
117
|
-
expect(postResult.hit).toBe(true);
|
|
118
|
-
});
|
|
119
|
-
});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for usePersistedForm composable
|
|
3
|
-
*
|
|
4
|
-
* Note: Svelte 5 runes ($state, $effect) require the Svelte compiler context.
|
|
5
|
-
* These tests focus on the DraftStorageService used by the composable.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
|
8
|
-
import { initOfflineStorage } from '@classic-homes/offline-core';
|
|
9
|
-
describe('DraftStorageService integration (used by usePersistedForm)', () => {
|
|
10
|
-
let storage;
|
|
11
|
-
beforeEach(async () => {
|
|
12
|
-
storage = await initOfflineStorage({
|
|
13
|
-
preferredAdapters: ['memory'],
|
|
14
|
-
});
|
|
15
|
-
});
|
|
16
|
-
afterEach(async () => {
|
|
17
|
-
await storage.cleanup.runCleanup();
|
|
18
|
-
await storage.dispose();
|
|
19
|
-
});
|
|
20
|
-
describe('draft persistence', () => {
|
|
21
|
-
it('should save and load drafts', async () => {
|
|
22
|
-
const formData = { name: 'John', email: 'john@example.com' };
|
|
23
|
-
await storage.drafts.saveDraft('contact-form', formData);
|
|
24
|
-
const result = await storage.drafts.loadDraft('contact-form');
|
|
25
|
-
expect(result.restored).toBe(true);
|
|
26
|
-
expect(result.draft).not.toBeNull();
|
|
27
|
-
expect(result.draft.data).toEqual(formData);
|
|
28
|
-
});
|
|
29
|
-
it('should return empty result for non-existent draft', async () => {
|
|
30
|
-
const result = await storage.drafts.loadDraft('non-existent');
|
|
31
|
-
expect(result.restored).toBe(false);
|
|
32
|
-
expect(result.draft).toBeNull();
|
|
33
|
-
});
|
|
34
|
-
it('should exclude specified fields', async () => {
|
|
35
|
-
const formData = {
|
|
36
|
-
name: 'John',
|
|
37
|
-
password: 'secret123',
|
|
38
|
-
confirmPassword: 'secret123',
|
|
39
|
-
};
|
|
40
|
-
await storage.drafts.saveDraft('signup', formData, {}, {
|
|
41
|
-
excludeFields: ['password', 'confirmPassword'],
|
|
42
|
-
});
|
|
43
|
-
const result = await storage.drafts.loadDraft('signup');
|
|
44
|
-
expect(result.draft.data.name).toBe('John');
|
|
45
|
-
expect(result.draft.data.password).toBeUndefined();
|
|
46
|
-
expect(result.draft.data.confirmPassword).toBeUndefined();
|
|
47
|
-
});
|
|
48
|
-
it('should save draft with file references', async () => {
|
|
49
|
-
const formData = { title: 'Document' };
|
|
50
|
-
const fileRefs = {
|
|
51
|
-
attachments: ['file:1', 'file:2'],
|
|
52
|
-
photo: ['file:3'],
|
|
53
|
-
};
|
|
54
|
-
await storage.drafts.saveDraft('upload-form', formData, fileRefs);
|
|
55
|
-
const result = await storage.drafts.loadDraft('upload-form');
|
|
56
|
-
expect(result.draft.fileRefs).toEqual(fileRefs);
|
|
57
|
-
});
|
|
58
|
-
});
|
|
59
|
-
describe('draft clearing', () => {
|
|
60
|
-
it('should clear a draft', async () => {
|
|
61
|
-
await storage.drafts.saveDraft('form1', { value: 1 });
|
|
62
|
-
await storage.drafts.clearDraft('form1');
|
|
63
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
64
|
-
expect(result.draft).toBeNull();
|
|
65
|
-
});
|
|
66
|
-
it('should clear all drafts', async () => {
|
|
67
|
-
await storage.drafts.saveDraft('form1', { v: 1 });
|
|
68
|
-
await storage.drafts.saveDraft('form2', { v: 2 });
|
|
69
|
-
const deleted = await storage.drafts.clearAllDrafts();
|
|
70
|
-
expect(deleted).toBe(2);
|
|
71
|
-
expect(await storage.drafts.hasDraft('form1')).toBe(false);
|
|
72
|
-
expect(await storage.drafts.hasDraft('form2')).toBe(false);
|
|
73
|
-
});
|
|
74
|
-
});
|
|
75
|
-
describe('draft existence check', () => {
|
|
76
|
-
it('should return true for existing draft', async () => {
|
|
77
|
-
await storage.drafts.saveDraft('form1', { value: 1 });
|
|
78
|
-
expect(await storage.drafts.hasDraft('form1')).toBe(true);
|
|
79
|
-
});
|
|
80
|
-
it('should return false for non-existent draft', async () => {
|
|
81
|
-
expect(await storage.drafts.hasDraft('non-existent')).toBe(false);
|
|
82
|
-
});
|
|
83
|
-
});
|
|
84
|
-
describe('draft listing', () => {
|
|
85
|
-
it('should list all draft form keys', async () => {
|
|
86
|
-
await storage.drafts.saveDraft('form1', { v: 1 });
|
|
87
|
-
await storage.drafts.saveDraft('form2', { v: 2 });
|
|
88
|
-
await storage.drafts.saveDraft('form3', { v: 3 });
|
|
89
|
-
const keys = await storage.drafts.listDraftFormKeys();
|
|
90
|
-
expect(keys).toHaveLength(3);
|
|
91
|
-
expect(keys).toContain('form1');
|
|
92
|
-
expect(keys).toContain('form2');
|
|
93
|
-
expect(keys).toContain('form3');
|
|
94
|
-
});
|
|
95
|
-
});
|
|
96
|
-
describe('draft info', () => {
|
|
97
|
-
it('should return draft info for existing draft', async () => {
|
|
98
|
-
vi.useFakeTimers();
|
|
99
|
-
const now = Date.now();
|
|
100
|
-
vi.setSystemTime(now);
|
|
101
|
-
await storage.drafts.saveDraft('form1', { value: 1 }, { field1: ['file:1'] }, { expirationMs: 10000 });
|
|
102
|
-
const info = await storage.drafts.getDraftInfo('form1');
|
|
103
|
-
expect(info.exists).toBe(true);
|
|
104
|
-
expect(info.timestamp).toBe(now);
|
|
105
|
-
expect(info.expiresAt).toBe(now + 10000);
|
|
106
|
-
expect(info.hasFiles).toBe(true);
|
|
107
|
-
vi.useRealTimers();
|
|
108
|
-
});
|
|
109
|
-
it('should return hasFiles false when no files', async () => {
|
|
110
|
-
await storage.drafts.saveDraft('form1', { value: 1 });
|
|
111
|
-
const info = await storage.drafts.getDraftInfo('form1');
|
|
112
|
-
expect(info.hasFiles).toBe(false);
|
|
113
|
-
});
|
|
114
|
-
});
|
|
115
|
-
describe('draft merging', () => {
|
|
116
|
-
it('should merge data into existing draft', async () => {
|
|
117
|
-
await storage.drafts.saveDraft('form1', { name: 'John', email: 'old@example.com' });
|
|
118
|
-
await storage.drafts.mergeDraft('form1', { email: 'new@example.com', phone: '123' });
|
|
119
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
120
|
-
expect(result.draft.data).toEqual({
|
|
121
|
-
name: 'John',
|
|
122
|
-
email: 'new@example.com',
|
|
123
|
-
phone: '123',
|
|
124
|
-
});
|
|
125
|
-
});
|
|
126
|
-
it('should preserve file references when merging', async () => {
|
|
127
|
-
await storage.drafts.saveDraft('form1', { name: 'John' }, { docs: ['file:1'] });
|
|
128
|
-
await storage.drafts.mergeDraft('form1', { email: 'john@example.com' });
|
|
129
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
130
|
-
expect(result.draft.fileRefs.docs).toEqual(['file:1']);
|
|
131
|
-
});
|
|
132
|
-
});
|
|
133
|
-
describe('file reference updates', () => {
|
|
134
|
-
it('should update file references', async () => {
|
|
135
|
-
await storage.drafts.saveDraft('form1', { title: 'Doc' }, { files: ['file:1'] });
|
|
136
|
-
const updated = await storage.drafts.updateFileRefs('form1', 'files', [
|
|
137
|
-
'file:1',
|
|
138
|
-
'file:2',
|
|
139
|
-
'file:3',
|
|
140
|
-
]);
|
|
141
|
-
expect(updated).toBe(true);
|
|
142
|
-
const result = await storage.drafts.loadDraft('form1');
|
|
143
|
-
expect(result.draft.fileRefs.files).toEqual(['file:1', 'file:2', 'file:3']);
|
|
144
|
-
});
|
|
145
|
-
it('should return false when draft does not exist', async () => {
|
|
146
|
-
const updated = await storage.drafts.updateFileRefs('non-existent', 'files', ['file:1']);
|
|
147
|
-
expect(updated).toBe(false);
|
|
148
|
-
});
|
|
149
|
-
});
|
|
150
|
-
});
|