@classic-homes/offline-svelte 0.1.3 → 0.1.5

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.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Vitest setup file for Svelte tests
3
3
  */
4
- import { vi } from 'vitest';
4
+ import { vi, beforeEach } from 'vitest';
5
5
  import 'fake-indexeddb/auto';
6
6
  // Mock URL.createObjectURL and revokeObjectURL
7
7
  global.URL.createObjectURL = vi.fn((blob) => `blob:mock-${blob.size}`);
@@ -16,3 +16,33 @@ Object.defineProperty(navigator, 'storage', {
16
16
  },
17
17
  writable: true,
18
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
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Tests that run the usePersistedForm composable itself (runes compiled via
3
+ * the .svelte.test.ts suffix).
4
+ */
5
+ import { describe, it, expect, afterEach, vi } from 'vitest';
6
+ import { flushSync } from 'svelte';
7
+ import { z } from 'zod';
8
+ import { initOfflineStorage, resetOfflineStorage, } from '@classic-homes/offline-core';
9
+ import { usePersistedForm } from '../usePersistedForm.svelte.js';
10
+ const schema = z.object({ name: z.string(), tags: z.array(z.string()) });
11
+ const DEBOUNCE_MS = 10;
12
+ function mount(options = {}) {
13
+ let form;
14
+ const destroy = $effect.root(() => {
15
+ form = usePersistedForm({
16
+ schema,
17
+ initialValues: { name: '', tags: [] },
18
+ storageKey: 'runes-form',
19
+ debounceMs: DEBOUNCE_MS,
20
+ submitCooldownMs: 0,
21
+ onSubmit: async () => { },
22
+ ...options,
23
+ });
24
+ });
25
+ flushSync();
26
+ return { form, destroy };
27
+ }
28
+ describe('usePersistedForm (Svelte)', () => {
29
+ let storage;
30
+ let destroy;
31
+ afterEach(async () => {
32
+ destroy?.();
33
+ destroy = undefined;
34
+ await resetOfflineStorage();
35
+ });
36
+ it('persists drafts through IndexedDB (no $state proxies reach structured clone)', async () => {
37
+ storage = await initOfflineStorage({ preferredAdapters: ['indexeddb'] });
38
+ const warn = vi.spyOn(console, 'warn');
39
+ const mounted = mount();
40
+ destroy = mounted.destroy;
41
+ mounted.form.setField('tags', ['a', 'b']);
42
+ mounted.form.updateFileRefs('docs', ['file:1']);
43
+ await vi.waitFor(async () => {
44
+ const result = await storage.drafts.loadDraft('runes-form');
45
+ expect(result.draft?.data).toEqual({ name: '', tags: ['a', 'b'] });
46
+ expect(result.draft?.fileRefs).toEqual({ docs: ['file:1'] });
47
+ });
48
+ expect(warn).not.toHaveBeenCalledWith('Failed to save form draft:', expect.anything());
49
+ warn.mockRestore();
50
+ });
51
+ it('does not load another draft into the form after submit clears the current one', async () => {
52
+ storage = await initOfflineStorage({ preferredAdapters: ['memory'] });
53
+ await storage.draftManager.createDraft('runes-form', {
54
+ initialData: { name: 'older', tags: [] },
55
+ });
56
+ await new Promise((resolve) => setTimeout(resolve, 5));
57
+ await storage.draftManager.createDraft('runes-form', {
58
+ initialData: { name: 'newest', tags: [] },
59
+ });
60
+ const mounted = mount({ multiDraft: true });
61
+ destroy = mounted.destroy;
62
+ const { form } = mounted;
63
+ await vi.waitFor(() => expect(form.data.name).toBe('newest'));
64
+ form.setField('name', 'submitted');
65
+ await form.handleSubmit();
66
+ flushSync();
67
+ await new Promise((resolve) => setTimeout(resolve, DEBOUNCE_MS * 3));
68
+ expect(form.currentDraftId).toBeNull();
69
+ expect(form.data.name).toBe('submitted');
70
+ const remaining = await storage.draftManager.listDrafts({ formKey: 'runes-form' });
71
+ expect(remaining.map((d) => d.name)).toHaveLength(1);
72
+ });
73
+ it('ignores a second submit and drops the queued autosave', async () => {
74
+ storage = await initOfflineStorage({ preferredAdapters: ['memory'] });
75
+ let release;
76
+ const onSubmit = vi.fn(() => new Promise((resolve) => (release = resolve)));
77
+ const mounted = mount({ onSubmit });
78
+ destroy = mounted.destroy;
79
+ const { form } = mounted;
80
+ form.setField('name', 'x');
81
+ const first = form.handleSubmit();
82
+ await form.handleSubmit();
83
+ await vi.waitFor(() => expect(onSubmit).toHaveBeenCalled());
84
+ release();
85
+ await first;
86
+ await new Promise((resolve) => setTimeout(resolve, DEBOUNCE_MS * 3));
87
+ expect(onSubmit).toHaveBeenCalledTimes(1);
88
+ expect((await storage.drafts.loadDraft('runes-form')).draft).toBeNull();
89
+ });
90
+ });
@@ -77,12 +77,14 @@ export function useDraftSync(options) {
77
77
  isSyncing = false;
78
78
  lastSyncAt = result.timestamp;
79
79
  lastResult = result;
80
- conflicts = result.conflicts;
80
+ // The service keeps unresolved conflicts across syncs; a sync that
81
+ // finds no new ones must not clear the list.
82
+ conflicts = syncService?.getConflicts() ?? result.conflicts;
81
83
  error = result.error ?? null;
82
84
  onSyncComplete?.(result);
83
85
  },
84
86
  onConflictDetected: (newConflicts) => {
85
- conflicts = newConflicts;
87
+ conflicts = syncService?.getConflicts() ?? newConflicts;
86
88
  onConflictDetected?.(newConflicts);
87
89
  },
88
90
  onOnlineStatusChange: (online) => {
@@ -29,6 +29,7 @@
29
29
  * {/if}
30
30
  * ```
31
31
  */
32
+ import { invalidateCacheByTag, invalidateAllCache } from '@classic-homes/offline-core';
32
33
  export interface UseOfflineCacheOptions<T = unknown> {
33
34
  /** Cache key */
34
35
  key: string;
@@ -73,11 +74,4 @@ export interface UseOfflineCacheReturn<T> {
73
74
  * Create a cache composable for a specific key
74
75
  */
75
76
  export declare function useOfflineCache<T>(options: UseOfflineCacheOptions<T>): UseOfflineCacheReturn<T>;
76
- /**
77
- * Invalidate cache entries by tag
78
- */
79
- export declare function invalidateCacheByTag(tag: string): Promise<number>;
80
- /**
81
- * Invalidate all cache entries
82
- */
83
- export declare function invalidateAllCache(): Promise<number>;
77
+ export { invalidateCacheByTag, invalidateAllCache };
@@ -29,7 +29,7 @@
29
29
  * {/if}
30
30
  * ```
31
31
  */
32
- import { getOfflineStorage, isOfflineStorageInitialized, } from '@classic-homes/offline-core';
32
+ import { getOfflineStorage, isOfflineStorageInitialized, invalidateCacheByTag, invalidateAllCache, } from '@classic-homes/offline-core';
33
33
  /**
34
34
  * Create a cache composable for a specific key
35
35
  */
@@ -207,23 +207,4 @@ export function useOfflineCache(options) {
207
207
  has,
208
208
  };
209
209
  }
210
- /**
211
- * Invalidate cache entries by tag
212
- */
213
- export async function invalidateCacheByTag(tag) {
214
- if (!isOfflineStorageInitialized()) {
215
- return 0;
216
- }
217
- const storage = getOfflineStorage();
218
- return storage.cache.invalidateByTag(tag);
219
- }
220
- /**
221
- * Invalidate all cache entries
222
- */
223
- export async function invalidateAllCache() {
224
- if (!isOfflineStorageInitialized()) {
225
- return 0;
226
- }
227
- const storage = getOfflineStorage();
228
- return storage.cache.invalidateAll();
229
- }
210
+ export { invalidateCacheByTag, invalidateAllCache };
@@ -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,6 +49,7 @@ 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;
52
54
  // Multi-draft state
53
55
  let currentDraftId = $state(initialDraftId ?? null);
@@ -74,7 +76,8 @@ export function usePersistedForm(options) {
74
76
  // Load current draft for this form
75
77
  draft = await storage.draftManager.getCurrentDraft(storageKey);
76
78
  }
77
- if (draft) {
79
+ // Don't overwrite edits made while the draft was loading
80
+ if (draft && !isDirty) {
78
81
  data = { ...JSON.parse(JSON.stringify(initialValues)), ...draft.data };
79
82
  fileRefs = draft.fileRefs || {};
80
83
  currentDraftId = draft.metadata.id;
@@ -87,7 +90,7 @@ export function usePersistedForm(options) {
87
90
  else {
88
91
  // Legacy single-draft mode
89
92
  const result = await storage.drafts.loadDraft(storageKey);
90
- if (result.restored && result.draft) {
93
+ if (result.restored && result.draft && !isDirty) {
91
94
  // Merge draft data with initial values
92
95
  data = { ...JSON.parse(JSON.stringify(initialValues)), ...result.draft.data };
93
96
  fileRefs = result.draft.fileRefs || {};
@@ -109,8 +112,11 @@ export function usePersistedForm(options) {
109
112
  }
110
113
  try {
111
114
  const storage = getOfflineStorage();
115
+ // Snapshot the $state proxies: IndexedDB/OPFS structured cloning throws
116
+ // DataCloneError on proxies (nested values included).
117
+ const dataToPersist = $state.snapshot(data);
118
+ const fileRefsToPersist = $state.snapshot(fileRefs);
112
119
  // Filter out excluded fields
113
- const dataToPersist = { ...data };
114
120
  for (const field of excludeFields) {
115
121
  delete dataToPersist[field];
116
122
  }
@@ -118,7 +124,7 @@ export function usePersistedForm(options) {
118
124
  // Multi-draft mode: Use DraftManagerService
119
125
  if (currentDraftId) {
120
126
  // Update existing draft
121
- await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefs);
127
+ await storage.draftManager.updateDraft(currentDraftId, dataToPersist, fileRefsToPersist);
122
128
  // Update metadata
123
129
  const metadata = await storage.draftManager.getDraftMetadata(currentDraftId);
124
130
  if (metadata) {
@@ -130,7 +136,7 @@ export function usePersistedForm(options) {
130
136
  // Create new draft
131
137
  const metadata = await storage.draftManager.createDraft(storageKey, {
132
138
  initialData: dataToPersist,
133
- initialFileRefs: fileRefs,
139
+ initialFileRefs: fileRefsToPersist,
134
140
  expirationMs,
135
141
  });
136
142
  currentDraftId = metadata.id;
@@ -141,7 +147,7 @@ export function usePersistedForm(options) {
141
147
  }
142
148
  else {
143
149
  // Legacy single-draft mode
144
- await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefs, {
150
+ await storage.drafts.saveDraft(storageKey, dataToPersist, fileRefsToPersist, {
145
151
  excludeFields: excludeFields,
146
152
  expirationMs,
147
153
  });
@@ -155,13 +161,21 @@ export function usePersistedForm(options) {
155
161
  * Debounced draft saving
156
162
  */
157
163
  function scheduleSaveDraft() {
158
- if (debounceTimer) {
159
- clearTimeout(debounceTimer);
160
- }
164
+ cancelPendingSave();
161
165
  debounceTimer = setTimeout(() => {
166
+ debounceTimer = null;
162
167
  void saveDraft();
163
168
  }, debounceMs);
164
169
  }
170
+ /**
171
+ * Cancel a queued debounced save
172
+ */
173
+ function cancelPendingSave() {
174
+ if (debounceTimer) {
175
+ clearTimeout(debounceTimer);
176
+ debounceTimer = null;
177
+ }
178
+ }
165
179
  /**
166
180
  * Set a field value
167
181
  */
@@ -221,6 +235,10 @@ export function usePersistedForm(options) {
221
235
  */
222
236
  async function handleSubmit(event) {
223
237
  event?.preventDefault();
238
+ // Ignore re-entry (e.g. a double click) while a submit is in flight
239
+ if (submitInFlight) {
240
+ return;
241
+ }
224
242
  // Check cooldown
225
243
  const now = Date.now();
226
244
  if (now - lastSubmitTime < submitCooldownMs) {
@@ -231,6 +249,9 @@ export function usePersistedForm(options) {
231
249
  if (!validate()) {
232
250
  return;
233
251
  }
252
+ // A queued autosave must not recreate the draft after it is cleared
253
+ cancelPendingSave();
254
+ submitInFlight = true;
234
255
  isSubmitting = true;
235
256
  globalError = null;
236
257
  try {
@@ -240,6 +261,7 @@ export function usePersistedForm(options) {
240
261
  lastSubmitTime = now;
241
262
  isSubmitted = true;
242
263
  // Clear draft on success
264
+ cancelPendingSave();
243
265
  await clearDraft();
244
266
  }
245
267
  catch (err) {
@@ -248,6 +270,7 @@ export function usePersistedForm(options) {
248
270
  throw err;
249
271
  }
250
272
  finally {
273
+ submitInFlight = false;
251
274
  isSubmitting = false;
252
275
  }
253
276
  }
@@ -255,6 +278,7 @@ export function usePersistedForm(options) {
255
278
  * Reset the form
256
279
  */
257
280
  function reset() {
281
+ cancelPendingSave();
258
282
  data = JSON.parse(JSON.stringify(originalInitialValues));
259
283
  errors = {};
260
284
  globalError = null;
@@ -350,15 +374,16 @@ export function usePersistedForm(options) {
350
374
  throw new Error('Offline storage not initialized');
351
375
  }
352
376
  const storage = getOfflineStorage();
353
- // Filter out excluded fields
354
- const dataToPersist = { ...data };
377
+ // Snapshot the $state proxies (structured clone rejects them), then
378
+ // filter out excluded fields
379
+ const dataToPersist = $state.snapshot(data);
355
380
  for (const field of excludeFields) {
356
381
  delete dataToPersist[field];
357
382
  }
358
383
  const metadata = await storage.draftManager.createDraft(storageKey, {
359
384
  name,
360
385
  initialData: dataToPersist,
361
- initialFileRefs: fileRefs,
386
+ initialFileRefs: $state.snapshot(fileRefs),
362
387
  expirationMs,
363
388
  });
364
389
  // Switch to the new draft
@@ -393,9 +418,14 @@ export function usePersistedForm(options) {
393
418
  onDraftRestored?.();
394
419
  return true;
395
420
  }
396
- // Load draft on initialization
421
+ // Load draft on initialization. untrack: loadDraft reads currentDraftId
422
+ // (and isDirty), which the composable itself changes on autosave/clear;
423
+ // tracking them would reload and clobber in-progress edits.
397
424
  $effect(() => {
398
- void loadDraft();
425
+ untrack(() => {
426
+ void loadDraft();
427
+ });
428
+ return cancelPendingSave;
399
429
  });
400
430
  return {
401
431
  get data() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@classic-homes/offline-svelte",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Svelte bindings for offline persistence and caching",
5
5
  "type": "module",
6
6
  "svelte": "./dist/index.js",
@@ -34,8 +34,8 @@
34
34
  "scripts": {
35
35
  "build": "svelte-package -i src",
36
36
  "dev": "svelte-package -i src --watch",
37
- "clean": "rm -rf dist",
38
- "typecheck": "svelte-check --tsconfig ./tsconfig.json",
37
+ "clean": "node ../../scripts/rm.mjs dist",
38
+ "typecheck": "tsc --noEmit",
39
39
  "test": "vitest run",
40
40
  "test:watch": "vitest",
41
41
  "test:coverage": "vitest run --coverage"
@@ -71,15 +71,15 @@
71
71
  },
72
72
  "devDependencies": {
73
73
  "@sveltejs/package": "^2.3.0",
74
- "@sveltejs/vite-plugin-svelte": "^4.0.0",
74
+ "@sveltejs/vite-plugin-svelte": "^7.0.0",
75
75
  "@testing-library/svelte": "^5.0.0",
76
- "@vitest/coverage-v8": "^2.0.0",
76
+ "@vitest/coverage-v8": "^4.1.10",
77
77
  "fake-indexeddb": "^6.0.0",
78
78
  "jsdom": "^25.0.0",
79
79
  "svelte": "^5.0.0",
80
80
  "svelte-check": "^4.0.0",
81
81
  "typescript": "^5.3.0",
82
- "vitest": "^2.0.0",
82
+ "vitest": "^4.1.10",
83
83
  "zod": "^3.23.0"
84
84
  }
85
85
  }