@classic-homes/offline-svelte 0.1.1

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.
@@ -0,0 +1,265 @@
1
+ /**
2
+ * useDraftSync - Svelte composable for cloud sync management
3
+ *
4
+ * @example
5
+ * ```svelte
6
+ * <script lang="ts">
7
+ * import { useDraftSync } from '@classic-homes/offline-svelte';
8
+ *
9
+ * // Create a sync adapter (implement SyncAdapter interface)
10
+ * const adapter = createMySyncAdapter();
11
+ *
12
+ * const sync = useDraftSync({
13
+ * adapter,
14
+ * autoSync: true,
15
+ * });
16
+ * </script>
17
+ *
18
+ * <div>
19
+ * Status: {sync.isOnline ? 'Online' : 'Offline'}
20
+ * {#if sync.isSyncing}
21
+ * <span>Syncing...</span>
22
+ * {/if}
23
+ * {#if sync.pendingCount > 0}
24
+ * <span>{sync.pendingCount} pending</span>
25
+ * {/if}
26
+ * </div>
27
+ *
28
+ * {#if sync.conflicts.length > 0}
29
+ * <div>
30
+ * <h3>Conflicts</h3>
31
+ * {#each sync.conflicts as conflict}
32
+ * <div>
33
+ * <span>{conflict.localDraft.metadata.name}</span>
34
+ * <button onclick={() => sync.resolveConflict(conflict.localDraftId, 'keep-local')}>
35
+ * Keep Local
36
+ * </button>
37
+ * <button onclick={() => sync.resolveConflict(conflict.localDraftId, 'keep-remote')}>
38
+ * Keep Remote
39
+ * </button>
40
+ * </div>
41
+ * {/each}
42
+ * </div>
43
+ * {/if}
44
+ * ```
45
+ */
46
+ import { onDestroy } from 'svelte';
47
+ import { getOfflineStorage, isOfflineStorageInitialized, createSyncService, } from '@classic-homes/offline-core';
48
+ /**
49
+ * Create a draft sync composable
50
+ */
51
+ export function useDraftSync(options) {
52
+ const { adapter, autoSync = false, syncIntervalMs = 30000, autoSyncOnReconnect = true, onSyncComplete, onConflictDetected, onOnlineStatusChange, onSyncError, } = options;
53
+ // Reactive state
54
+ let isOnline = $state(typeof navigator !== 'undefined' ? navigator.onLine : true);
55
+ let isSyncing = $state(false);
56
+ let lastSyncAt = $state(null);
57
+ let conflicts = $state([]);
58
+ let pendingCount = $state(0);
59
+ let lastResult = $state(null);
60
+ let error = $state(null);
61
+ let isAutoSyncActive = $state(false);
62
+ // Sync service instance
63
+ let syncService = null;
64
+ /**
65
+ * Initialize the sync service
66
+ */
67
+ async function initSyncService() {
68
+ if (!isOfflineStorageInitialized()) {
69
+ return;
70
+ }
71
+ const storage = getOfflineStorage();
72
+ syncService = createSyncService(storage.adapter, {
73
+ adapter,
74
+ syncIntervalMs,
75
+ autoSyncOnReconnect,
76
+ onSyncComplete: (result) => {
77
+ isSyncing = false;
78
+ lastSyncAt = result.timestamp;
79
+ lastResult = result;
80
+ conflicts = result.conflicts;
81
+ error = result.error ?? null;
82
+ onSyncComplete?.(result);
83
+ },
84
+ onConflictDetected: (newConflicts) => {
85
+ conflicts = newConflicts;
86
+ onConflictDetected?.(newConflicts);
87
+ },
88
+ onOnlineStatusChange: (online) => {
89
+ isOnline = online;
90
+ onOnlineStatusChange?.(online);
91
+ },
92
+ onSyncError: (err) => {
93
+ isSyncing = false;
94
+ error = err.message;
95
+ onSyncError?.(err);
96
+ },
97
+ });
98
+ await syncService.initialize();
99
+ // Update state from service
100
+ isOnline = syncService.isOnline;
101
+ lastSyncAt = syncService.lastSyncAt;
102
+ pendingCount = syncService.pendingCount;
103
+ conflicts = syncService.getConflicts();
104
+ // Start auto-sync if enabled
105
+ if (autoSync) {
106
+ syncService.startAutoSync();
107
+ isAutoSyncActive = true;
108
+ }
109
+ }
110
+ /**
111
+ * Sync all drafts
112
+ */
113
+ async function syncAll() {
114
+ if (!syncService) {
115
+ return {
116
+ success: false,
117
+ uploaded: 0,
118
+ downloaded: 0,
119
+ deletedRemote: 0,
120
+ deletedLocal: 0,
121
+ conflicts: [],
122
+ error: 'Sync service not initialized',
123
+ timestamp: Date.now(),
124
+ durationMs: 0,
125
+ };
126
+ }
127
+ isSyncing = true;
128
+ error = null;
129
+ try {
130
+ const result = await syncService.syncAll();
131
+ pendingCount = syncService.pendingCount;
132
+ return result;
133
+ }
134
+ catch (err) {
135
+ const errorMsg = err instanceof Error ? err.message : 'Sync failed';
136
+ error = errorMsg;
137
+ return {
138
+ success: false,
139
+ uploaded: 0,
140
+ downloaded: 0,
141
+ deletedRemote: 0,
142
+ deletedLocal: 0,
143
+ conflicts: [],
144
+ error: errorMsg,
145
+ timestamp: Date.now(),
146
+ durationMs: 0,
147
+ };
148
+ }
149
+ finally {
150
+ isSyncing = false;
151
+ }
152
+ }
153
+ /**
154
+ * Sync a specific draft
155
+ */
156
+ async function syncDraft(draftId) {
157
+ if (!syncService) {
158
+ return {
159
+ success: false,
160
+ uploaded: 0,
161
+ downloaded: 0,
162
+ deletedRemote: 0,
163
+ deletedLocal: 0,
164
+ conflicts: [],
165
+ error: 'Sync service not initialized',
166
+ timestamp: Date.now(),
167
+ durationMs: 0,
168
+ };
169
+ }
170
+ return syncService.syncDraft(draftId);
171
+ }
172
+ /**
173
+ * Force push a draft
174
+ */
175
+ async function forcePush(draftId) {
176
+ if (!syncService) {
177
+ throw new Error('Sync service not initialized');
178
+ }
179
+ await syncService.forcePush(draftId);
180
+ conflicts = syncService.getConflicts();
181
+ }
182
+ /**
183
+ * Force pull a draft
184
+ */
185
+ async function forcePull(draftId) {
186
+ if (!syncService) {
187
+ throw new Error('Sync service not initialized');
188
+ }
189
+ await syncService.forcePull(draftId);
190
+ conflicts = syncService.getConflicts();
191
+ }
192
+ /**
193
+ * Resolve a conflict
194
+ */
195
+ async function resolveConflict(draftId, resolution) {
196
+ if (!syncService) {
197
+ throw new Error('Sync service not initialized');
198
+ }
199
+ await syncService.resolveConflict(draftId, resolution);
200
+ conflicts = syncService.getConflicts();
201
+ }
202
+ /**
203
+ * Start auto-sync
204
+ */
205
+ function startAutoSync() {
206
+ syncService?.startAutoSync();
207
+ isAutoSyncActive = true;
208
+ }
209
+ /**
210
+ * Stop auto-sync
211
+ */
212
+ function stopAutoSync() {
213
+ syncService?.stopAutoSync();
214
+ isAutoSyncActive = false;
215
+ }
216
+ /**
217
+ * Dispose the sync service
218
+ */
219
+ function dispose() {
220
+ syncService?.dispose();
221
+ syncService = null;
222
+ }
223
+ // Initialize on mount
224
+ $effect(() => {
225
+ void initSyncService();
226
+ });
227
+ // Cleanup on destroy
228
+ onDestroy(() => {
229
+ dispose();
230
+ });
231
+ return {
232
+ get isOnline() {
233
+ return isOnline;
234
+ },
235
+ get isSyncing() {
236
+ return isSyncing;
237
+ },
238
+ get lastSyncAt() {
239
+ return lastSyncAt;
240
+ },
241
+ get conflicts() {
242
+ return conflicts;
243
+ },
244
+ get pendingCount() {
245
+ return pendingCount;
246
+ },
247
+ get lastResult() {
248
+ return lastResult;
249
+ },
250
+ get error() {
251
+ return error;
252
+ },
253
+ get isAutoSyncActive() {
254
+ return isAutoSyncActive;
255
+ },
256
+ syncAll,
257
+ syncDraft,
258
+ forcePush,
259
+ forcePull,
260
+ resolveConflict,
261
+ startAutoSync,
262
+ stopAutoSync,
263
+ dispose,
264
+ };
265
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * useFileStorage - Svelte composable for file persistence
3
+ *
4
+ * Provides reactive file storage with validation, preview generation,
5
+ * and automatic cleanup.
6
+ *
7
+ * @example
8
+ * ```svelte
9
+ * <script lang="ts">
10
+ * import { useFileStorage } from '@classic-homes/offline-svelte';
11
+ *
12
+ * const documents = useFileStorage({
13
+ * formKey: 'contact-form',
14
+ * fieldName: 'documents',
15
+ * maxFiles: 5,
16
+ * maxSizeBytes: 10 * 1024 * 1024,
17
+ * acceptedTypes: ['application/pdf', 'image/*'],
18
+ * });
19
+ * </script>
20
+ *
21
+ * <FileUpload
22
+ * files={documents.files}
23
+ * onFilesAdded={(files) => documents.addFiles(files)}
24
+ * onFileRemoved={(id) => documents.removeFile(id)}
25
+ * />
26
+ * ```
27
+ */
28
+ import { type PersistedFile, type FileConstraints, type FileValidationError } from '@classic-homes/offline-core';
29
+ export interface UseFileStorageOptions extends FileConstraints {
30
+ /** Form key this field belongs to */
31
+ formKey: string;
32
+ /** Field name for this file input */
33
+ fieldName: string;
34
+ /** Custom expiration in milliseconds */
35
+ expirationMs?: number;
36
+ /** Generate preview URLs for images (default: true) */
37
+ generatePreviews?: boolean;
38
+ /** Callback when validation errors occur */
39
+ onValidationError?: (errors: FileValidationError[]) => void;
40
+ }
41
+ export interface UseFileStorageReturn {
42
+ /** Current files (reactive) */
43
+ readonly files: PersistedFile[];
44
+ /** File IDs for form submission */
45
+ readonly fileIds: string[];
46
+ /** Whether files are being loaded */
47
+ readonly isLoading: boolean;
48
+ /** Current error if any */
49
+ readonly error: Error | null;
50
+ /** Add files (validates and stores) */
51
+ addFiles: (files: File[]) => Promise<void>;
52
+ /** Remove a file by ID */
53
+ removeFile: (id: string) => Promise<void>;
54
+ /** Remove all files */
55
+ clearFiles: () => Promise<void>;
56
+ /** Reload files from storage */
57
+ reload: () => Promise<void>;
58
+ /** Get files as File objects for submission */
59
+ getFilesForSubmit: () => Promise<File[]>;
60
+ }
61
+ /**
62
+ * Create a file storage composable for a form field
63
+ */
64
+ export declare function useFileStorage(options: UseFileStorageOptions): UseFileStorageReturn;
@@ -0,0 +1,195 @@
1
+ /**
2
+ * useFileStorage - Svelte composable for file persistence
3
+ *
4
+ * Provides reactive file storage with validation, preview generation,
5
+ * and automatic cleanup.
6
+ *
7
+ * @example
8
+ * ```svelte
9
+ * <script lang="ts">
10
+ * import { useFileStorage } from '@classic-homes/offline-svelte';
11
+ *
12
+ * const documents = useFileStorage({
13
+ * formKey: 'contact-form',
14
+ * fieldName: 'documents',
15
+ * maxFiles: 5,
16
+ * maxSizeBytes: 10 * 1024 * 1024,
17
+ * acceptedTypes: ['application/pdf', 'image/*'],
18
+ * });
19
+ * </script>
20
+ *
21
+ * <FileUpload
22
+ * files={documents.files}
23
+ * onFilesAdded={(files) => documents.addFiles(files)}
24
+ * onFileRemoved={(id) => documents.removeFile(id)}
25
+ * />
26
+ * ```
27
+ */
28
+ import { getOfflineStorage, isOfflineStorageInitialized, } from '@classic-homes/offline-core';
29
+ /**
30
+ * Create a file storage composable for a form field
31
+ */
32
+ export function useFileStorage(options) {
33
+ const { formKey, fieldName, maxFiles, maxSizeBytes, acceptedTypes, expirationMs, generatePreviews = true, onValidationError, } = options;
34
+ // Reactive state
35
+ let files = $state([]);
36
+ let isLoading = $state(true);
37
+ let error = $state(null);
38
+ // Constraints for validation
39
+ const constraints = {
40
+ maxFiles,
41
+ maxSizeBytes,
42
+ acceptedTypes,
43
+ };
44
+ /**
45
+ * Load files from storage
46
+ */
47
+ async function loadFiles() {
48
+ if (!isOfflineStorageInitialized()) {
49
+ isLoading = false;
50
+ return;
51
+ }
52
+ try {
53
+ isLoading = true;
54
+ error = null;
55
+ const storage = getOfflineStorage();
56
+ const loaded = await storage.files.getFiles({
57
+ formKey,
58
+ fieldName,
59
+ includeBlobs: true,
60
+ generatePreviews,
61
+ });
62
+ files = loaded;
63
+ }
64
+ catch (err) {
65
+ error = err instanceof Error ? err : new Error(String(err));
66
+ files = [];
67
+ }
68
+ finally {
69
+ isLoading = false;
70
+ }
71
+ }
72
+ /**
73
+ * Add files with validation
74
+ */
75
+ async function addFiles(newFiles) {
76
+ if (!isOfflineStorageInitialized()) {
77
+ throw new Error('Offline storage not initialized');
78
+ }
79
+ const storage = getOfflineStorage();
80
+ // Validate files
81
+ const validationErrors = storage.files.validateFiles(newFiles, constraints, files.length);
82
+ if (validationErrors.length > 0) {
83
+ onValidationError?.(validationErrors);
84
+ // Filter out invalid files
85
+ const invalidFiles = new Set(validationErrors.map((e) => e.file));
86
+ newFiles = newFiles.filter((f) => !invalidFiles.has(f));
87
+ if (newFiles.length === 0) {
88
+ return;
89
+ }
90
+ }
91
+ try {
92
+ error = null;
93
+ // Store files
94
+ const stored = await storage.files.storeFiles(newFiles, {
95
+ formKey,
96
+ fieldName,
97
+ expirationMs,
98
+ });
99
+ // Add to reactive array with previews
100
+ for (const storedFile of stored) {
101
+ const persisted = await storage.files.getFile(storedFile.id, generatePreviews);
102
+ if (persisted) {
103
+ files = [...files, persisted];
104
+ }
105
+ }
106
+ }
107
+ catch (err) {
108
+ error = err instanceof Error ? err : new Error(String(err));
109
+ throw error;
110
+ }
111
+ }
112
+ /**
113
+ * Remove a file
114
+ */
115
+ async function removeFile(id) {
116
+ if (!isOfflineStorageInitialized()) {
117
+ return;
118
+ }
119
+ const storage = getOfflineStorage();
120
+ try {
121
+ // Revoke preview URL before removing
122
+ const fileToRemove = files.find((f) => f.id === id);
123
+ if (fileToRemove?.previewUrl) {
124
+ URL.revokeObjectURL(fileToRemove.previewUrl);
125
+ }
126
+ await storage.files.deleteFile(id);
127
+ files = files.filter((f) => f.id !== id);
128
+ }
129
+ catch (err) {
130
+ error = err instanceof Error ? err : new Error(String(err));
131
+ throw error;
132
+ }
133
+ }
134
+ /**
135
+ * Clear all files
136
+ */
137
+ async function clearFiles() {
138
+ if (!isOfflineStorageInitialized()) {
139
+ return;
140
+ }
141
+ const storage = getOfflineStorage();
142
+ try {
143
+ // Revoke all preview URLs
144
+ storage.files.revokePreviewUrls(files);
145
+ await storage.files.deleteFormFiles(formKey, fieldName);
146
+ files = [];
147
+ }
148
+ catch (err) {
149
+ error = err instanceof Error ? err : new Error(String(err));
150
+ throw error;
151
+ }
152
+ }
153
+ /**
154
+ * Get files as File objects for form submission
155
+ */
156
+ async function getFilesForSubmit() {
157
+ if (!isOfflineStorageInitialized()) {
158
+ return [];
159
+ }
160
+ const storage = getOfflineStorage();
161
+ const fileIds = files.map((f) => f.id);
162
+ const fileMap = await storage.files.getFilesAsFileObjects(fileIds);
163
+ return Array.from(fileMap.values());
164
+ }
165
+ // Load files on initialization
166
+ $effect(() => {
167
+ void loadFiles();
168
+ // Cleanup preview URLs on unmount
169
+ return () => {
170
+ if (isOfflineStorageInitialized()) {
171
+ const storage = getOfflineStorage();
172
+ storage.files.revokePreviewUrls(files);
173
+ }
174
+ };
175
+ });
176
+ return {
177
+ get files() {
178
+ return files;
179
+ },
180
+ get fileIds() {
181
+ return files.map((f) => f.id);
182
+ },
183
+ get isLoading() {
184
+ return isLoading;
185
+ },
186
+ get error() {
187
+ return error;
188
+ },
189
+ addFiles,
190
+ removeFile,
191
+ clearFiles,
192
+ reload: loadFiles,
193
+ getFilesForSubmit,
194
+ };
195
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * useOfflineCache - Svelte composable for caching data
3
+ *
4
+ * Provides reactive caching with TTL and stale-while-revalidate support.
5
+ *
6
+ * @example
7
+ * ```svelte
8
+ * <script lang="ts">
9
+ * import { useOfflineCache } from '@classic-homes/offline-svelte';
10
+ *
11
+ * const userCache = useOfflineCache<User>({
12
+ * key: 'current-user',
13
+ * ttl: 60 * 60 * 1000, // 1 hour
14
+ * staleWhileRevalidate: true,
15
+ * });
16
+ *
17
+ * // Load from cache or fetch
18
+ * $effect(() => {
19
+ * userCache.get(async () => {
20
+ * return await fetchCurrentUser();
21
+ * });
22
+ * });
23
+ * </script>
24
+ *
25
+ * {#if userCache.isLoading}
26
+ * <Spinner />
27
+ * {:else if userCache.data}
28
+ * <UserProfile user={userCache.data} />
29
+ * {/if}
30
+ * ```
31
+ */
32
+ export interface UseOfflineCacheOptions<T = unknown> {
33
+ /** Cache key */
34
+ key: string;
35
+ /** Time to live in milliseconds */
36
+ ttl?: number;
37
+ /** Tags for bulk invalidation */
38
+ tags?: string[];
39
+ /** Use stale data while revalidating */
40
+ staleWhileRevalidate?: boolean;
41
+ /** Time in ms that stale data is acceptable */
42
+ staleTime?: number;
43
+ /**
44
+ * Fetcher function for auto-fetch on initialization.
45
+ * If provided, the cache will automatically fetch data when created
46
+ * if no valid cached data exists.
47
+ */
48
+ fetcher?: () => Promise<T>;
49
+ }
50
+ export interface UseOfflineCacheReturn<T> {
51
+ /** Cached data (reactive) */
52
+ readonly data: T | null;
53
+ /** Whether data is being fetched */
54
+ readonly isLoading: boolean;
55
+ /** Whether current data is stale */
56
+ readonly isStale: boolean;
57
+ /** Current error if any */
58
+ readonly error: Error | null;
59
+ /** Time remaining until expiration */
60
+ readonly ttlRemaining: number | null;
61
+ /** Get cached value or fetch it */
62
+ get: (fetcher: () => Promise<T>) => Promise<T>;
63
+ /** Set cached value directly */
64
+ set: (value: T) => Promise<void>;
65
+ /** Invalidate the cache */
66
+ invalidate: () => Promise<void>;
67
+ /** Refresh the cache (re-fetch) */
68
+ refresh: (fetcher: () => Promise<T>) => Promise<T>;
69
+ /** Check if cache has a valid entry */
70
+ has: () => Promise<boolean>;
71
+ }
72
+ /**
73
+ * Create a cache composable for a specific key
74
+ */
75
+ 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>;