@classic-homes/offline-core 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,100 @@
1
+ // src/utils/expiration.ts
2
+ var CleanupScheduler = class {
3
+ constructor(intervalMs = 6e4) {
4
+ this.intervalId = null;
5
+ this.adapters = [];
6
+ this.isRunning = false;
7
+ this.intervalMs = intervalMs;
8
+ }
9
+ /**
10
+ * Register an adapter for automatic cleanup
11
+ */
12
+ registerAdapter(adapter) {
13
+ if (!this.adapters.includes(adapter)) {
14
+ this.adapters.push(adapter);
15
+ }
16
+ }
17
+ /**
18
+ * Unregister an adapter
19
+ */
20
+ unregisterAdapter(adapter) {
21
+ const index = this.adapters.indexOf(adapter);
22
+ if (index !== -1) {
23
+ this.adapters.splice(index, 1);
24
+ }
25
+ }
26
+ /**
27
+ * Start the cleanup scheduler
28
+ */
29
+ start() {
30
+ if (this.intervalId !== null || this.intervalMs <= 0) {
31
+ return;
32
+ }
33
+ this.intervalId = setInterval(() => {
34
+ void this.runCleanup();
35
+ }, this.intervalMs);
36
+ void this.runCleanup();
37
+ }
38
+ /**
39
+ * Stop the cleanup scheduler
40
+ */
41
+ stop() {
42
+ if (this.intervalId !== null) {
43
+ clearInterval(this.intervalId);
44
+ this.intervalId = null;
45
+ }
46
+ }
47
+ /**
48
+ * Run cleanup on all registered adapters
49
+ */
50
+ async runCleanup() {
51
+ if (this.isRunning) {
52
+ return { totalDeleted: 0, totalFreed: 0 };
53
+ }
54
+ this.isRunning = true;
55
+ let totalDeleted = 0;
56
+ let totalFreed = 0;
57
+ try {
58
+ for (const adapter of this.adapters) {
59
+ try {
60
+ const result = await adapter.cleanup();
61
+ totalDeleted += result.deletedCount;
62
+ totalFreed += result.freedBytes;
63
+ } catch (error) {
64
+ console.warn(`Cleanup failed for adapter ${adapter.name}:`, error);
65
+ }
66
+ }
67
+ } finally {
68
+ this.isRunning = false;
69
+ }
70
+ return { totalDeleted, totalFreed };
71
+ }
72
+ /**
73
+ * Check if scheduler is active
74
+ */
75
+ isActive() {
76
+ return this.intervalId !== null;
77
+ }
78
+ };
79
+ function calculateExpiration(ttlMs) {
80
+ if (ttlMs === void 0 || ttlMs <= 0) {
81
+ return null;
82
+ }
83
+ return Date.now() + ttlMs;
84
+ }
85
+ function isExpired(expiresAt) {
86
+ if (expiresAt === null || expiresAt === void 0) {
87
+ return false;
88
+ }
89
+ return Date.now() > expiresAt;
90
+ }
91
+ var DEFAULT_EXPIRATIONS = {
92
+ /** Form draft expiration: 7 days */
93
+ DRAFT: 7 * 24 * 60 * 60 * 1e3,
94
+ /** File attachment expiration: 24 hours */
95
+ FILE: 24 * 60 * 60 * 1e3,
96
+ /** Cache entry expiration: 1 hour */
97
+ CACHE: 60 * 60 * 1e3
98
+ };
99
+
100
+ export { CleanupScheduler, DEFAULT_EXPIRATIONS, calculateExpiration, isExpired };
@@ -0,0 +1,203 @@
1
+ import { a as SaveDraftOptions, L as LoadDraftOptions, b as LoadDraftResult, C as CreateDraftOptions, d as DraftMetadata, e as StoredDraftV2, f as ListDraftsOptions, c as DraftSyncStatus } from '../types-B2FJpQuN.js';
2
+ export { j as CURRENT_DRAFT_PREFIX, D as DRAFT_PREFIX, g as DRAFT_V2_PREFIX, S as StoredDraft, h as generateDraftId, n as getCurrentDraftKey, k as getDraftKey, m as getDraftV2Key, l as getFormKeyFromDraftKey, i as getOrCreateDeviceId, q as isDraftV2Key, o as isLegacyDraftKey, p as parseDraftV2Key } from '../types-B2FJpQuN.js';
3
+ import { S as StorageAdapter } from '../types-CWuauHAr.js';
4
+
5
+ /**
6
+ * Form draft persistence service
7
+ *
8
+ * Provides saving and restoring form drafts with optional
9
+ * file attachment references.
10
+ */
11
+
12
+ /**
13
+ * File validator function type for checking file existence
14
+ */
15
+ type FileExistsValidator = (fileId: string) => Promise<boolean>;
16
+ /**
17
+ * Draft storage service
18
+ */
19
+ declare class DraftStorageService {
20
+ private readonly adapter;
21
+ private fileExistsValidator?;
22
+ constructor(adapter: StorageAdapter);
23
+ /**
24
+ * Set a function to validate file existence
25
+ * Used when validateFileRefs option is enabled
26
+ */
27
+ setFileValidator(validator: FileExistsValidator): void;
28
+ /**
29
+ * Validate file references and log warnings for missing files
30
+ */
31
+ private validateFileReferences;
32
+ /**
33
+ * Save a form draft
34
+ */
35
+ saveDraft<T extends Record<string, unknown>>(formKey: string, data: Partial<T>, fileRefs?: Record<string, string[]>, options?: SaveDraftOptions): Promise<void>;
36
+ /**
37
+ * Load a form draft
38
+ */
39
+ loadDraft<T extends Record<string, unknown>>(formKey: string, _options?: LoadDraftOptions): Promise<LoadDraftResult<T>>;
40
+ /**
41
+ * Clear a form draft
42
+ */
43
+ clearDraft(formKey: string): Promise<void>;
44
+ /**
45
+ * Check if a draft exists
46
+ */
47
+ hasDraft(formKey: string): Promise<boolean>;
48
+ /**
49
+ * List all draft form keys
50
+ */
51
+ listDraftFormKeys(): Promise<string[]>;
52
+ /**
53
+ * Clear all drafts
54
+ */
55
+ clearAllDrafts(): Promise<number>;
56
+ /**
57
+ * Get draft metadata without full data (for listing)
58
+ */
59
+ getDraftInfo(formKey: string): Promise<{
60
+ exists: boolean;
61
+ timestamp: number | null;
62
+ expiresAt: number | null;
63
+ hasFiles: boolean;
64
+ }>;
65
+ /**
66
+ * Update file references in a draft
67
+ * Useful when files are added/removed without full draft save
68
+ *
69
+ * @param formKey - The form key
70
+ * @param fieldName - The field name to update
71
+ * @param fileIds - Array of file IDs to set
72
+ * @param options - Optional settings including validateFileRefs
73
+ */
74
+ updateFileRefs(formKey: string, fieldName: string, fileIds: string[], options?: {
75
+ validateFileRefs?: boolean;
76
+ }): Promise<boolean>;
77
+ /**
78
+ * Merge data into an existing draft
79
+ */
80
+ mergeDraft<T extends Record<string, unknown>>(formKey: string, partialData: Partial<T>, options?: SaveDraftOptions): Promise<void>;
81
+ }
82
+ /**
83
+ * Create a draft storage service
84
+ */
85
+ declare function createDraftStorageService(adapter: StorageAdapter): DraftStorageService;
86
+
87
+ /**
88
+ * Multi-draft management service
89
+ *
90
+ * Provides CRUD operations for managing multiple drafts per form type.
91
+ * Supports legacy draft migration and backward compatibility.
92
+ */
93
+
94
+ /**
95
+ * Draft manager service for multi-draft support
96
+ */
97
+ declare class DraftManagerService {
98
+ private readonly adapter;
99
+ private readonly deviceId;
100
+ constructor(adapter: StorageAdapter);
101
+ /**
102
+ * Create a new draft
103
+ */
104
+ createDraft<T = Record<string, unknown>>(formKey: string, options?: CreateDraftOptions): Promise<DraftMetadata>;
105
+ /**
106
+ * Get a draft by ID
107
+ */
108
+ getDraft<T = Record<string, unknown>>(draftId: string): Promise<StoredDraftV2<T> | null>;
109
+ /**
110
+ * Get a draft by form key and draft ID (more efficient)
111
+ */
112
+ getDraftByFormKey<T = Record<string, unknown>>(formKey: string, draftId: string): Promise<StoredDraftV2<T> | null>;
113
+ /**
114
+ * Get draft metadata only
115
+ */
116
+ getDraftMetadata(draftId: string): Promise<DraftMetadata | null>;
117
+ /**
118
+ * List all drafts with optional filtering
119
+ */
120
+ listDrafts(options?: ListDraftsOptions): Promise<DraftMetadata[]>;
121
+ /**
122
+ * List drafts by form key (convenience method)
123
+ */
124
+ listDraftsByFormKey(formKey: string): Promise<DraftMetadata[]>;
125
+ /**
126
+ * Get count of drafts
127
+ */
128
+ getDraftCount(formKey?: string): Promise<number>;
129
+ /**
130
+ * Update draft data
131
+ */
132
+ updateDraft<T = Record<string, unknown>>(draftId: string, data: Partial<T>, fileRefs?: Record<string, string[]>): Promise<boolean>;
133
+ /**
134
+ * Update draft metadata only
135
+ */
136
+ updateDraftMetadata(draftId: string, updates: Partial<Pick<DraftMetadata, 'name' | 'syncStatus' | 'remoteId' | 'lastSyncedAt'>>): Promise<boolean>;
137
+ /**
138
+ * Delete a draft
139
+ */
140
+ deleteDraft(draftId: string, deleteFiles?: boolean): Promise<boolean>;
141
+ /**
142
+ * Delete all drafts for a form key
143
+ */
144
+ deleteDraftsByFormKey(formKey: string): Promise<number>;
145
+ /**
146
+ * Duplicate a draft
147
+ */
148
+ duplicateDraft(draftId: string, newName?: string): Promise<DraftMetadata | null>;
149
+ /**
150
+ * Get the current draft for a form (auto-migrates legacy drafts)
151
+ */
152
+ getCurrentDraft<T = Record<string, unknown>>(formKey: string): Promise<StoredDraftV2<T> | null>;
153
+ /**
154
+ * Set the current draft for a form
155
+ */
156
+ setCurrentDraft(formKey: string, draftId: string): Promise<void>;
157
+ /**
158
+ * Clear the current draft for a form
159
+ */
160
+ clearCurrentDraft(formKey: string): Promise<void>;
161
+ /**
162
+ * Get drafts by sync status
163
+ */
164
+ getDraftsBySyncStatus(status: DraftSyncStatus): Promise<DraftMetadata[]>;
165
+ /**
166
+ * Get all drafts pending sync
167
+ */
168
+ getPendingSyncDrafts(): Promise<DraftMetadata[]>;
169
+ /**
170
+ * Mark a draft as synced
171
+ */
172
+ markAsSynced(draftId: string, remoteId: string): Promise<boolean>;
173
+ /**
174
+ * Mark a draft as having a conflict
175
+ */
176
+ markAsConflict(draftId: string): Promise<boolean>;
177
+ /**
178
+ * Migrate a legacy draft to V2 format
179
+ */
180
+ private migrateLegacyDraft;
181
+ /**
182
+ * Check if there are any legacy drafts
183
+ */
184
+ hasLegacyDrafts(): Promise<boolean>;
185
+ /**
186
+ * Migrate all legacy drafts
187
+ */
188
+ migrateAllLegacyDrafts(): Promise<number>;
189
+ /**
190
+ * Generate a default draft name
191
+ */
192
+ private generateDefaultDraftName;
193
+ /**
194
+ * Format a form key for display
195
+ */
196
+ private formatFormKey;
197
+ }
198
+ /**
199
+ * Create a draft manager service
200
+ */
201
+ declare function createDraftManagerService(adapter: StorageAdapter): DraftManagerService;
202
+
203
+ export { CreateDraftOptions, DraftManagerService, DraftMetadata, DraftStorageService, DraftSyncStatus, type FileExistsValidator, ListDraftsOptions, LoadDraftOptions, LoadDraftResult, SaveDraftOptions, StoredDraftV2, createDraftManagerService, createDraftStorageService };
@@ -0,0 +1,3 @@
1
+ export { DraftStorageService, createDraftStorageService } from '../chunk-IIG4QLLN.js';
2
+ export { CURRENT_DRAFT_PREFIX, DRAFT_PREFIX, DRAFT_V2_PREFIX, DraftManagerService, createDraftManagerService, generateDraftId, getCurrentDraftKey, getDraftKey, getDraftV2Key, getFormKeyFromDraftKey, getOrCreateDeviceId, isDraftV2Key, isLegacyDraftKey, parseDraftV2Key } from '../chunk-4QWZX3LM.js';
3
+ import '../chunk-ZC7F2HDV.js';
@@ -0,0 +1,181 @@
1
+ import { B as BlobMetadata, S as StorageAdapter } from '../types-CWuauHAr.js';
2
+
3
+ /**
4
+ * Types for file storage service
5
+ */
6
+
7
+ /**
8
+ * Stored file metadata (without the blob data)
9
+ */
10
+ interface StoredFile {
11
+ /** Unique file identifier */
12
+ id: string;
13
+ /** Associated form key */
14
+ formKey: string;
15
+ /** Field name in the form */
16
+ fieldName: string;
17
+ /** Original filename */
18
+ filename: string;
19
+ /** MIME content type */
20
+ contentType: string;
21
+ /** File size in bytes */
22
+ size: number;
23
+ /** Timestamp when file was stored */
24
+ createdAt: number;
25
+ /** Timestamp when file will expire */
26
+ expiresAt: number;
27
+ }
28
+ /**
29
+ * File with blob data for retrieval
30
+ */
31
+ interface PersistedFile extends StoredFile {
32
+ /** The actual file blob */
33
+ blob: Blob;
34
+ /** Object URL for preview (images) - caller must revoke */
35
+ previewUrl?: string;
36
+ }
37
+ /**
38
+ * Options for storing files
39
+ */
40
+ interface StoreFileOptions {
41
+ /** Form key this file belongs to */
42
+ formKey: string;
43
+ /** Field name in the form */
44
+ fieldName: string;
45
+ /** Custom expiration in milliseconds */
46
+ expirationMs?: number;
47
+ /** Custom metadata to store with file */
48
+ metadata?: Record<string, unknown>;
49
+ }
50
+ /**
51
+ * Options for retrieving files
52
+ */
53
+ interface GetFilesOptions {
54
+ /** Form key to filter by */
55
+ formKey?: string;
56
+ /** Field name to filter by */
57
+ fieldName?: string;
58
+ /** Include blob data (default: true) */
59
+ includeBlobs?: boolean;
60
+ /** Generate preview URLs for images (default: false) */
61
+ generatePreviews?: boolean;
62
+ }
63
+ /**
64
+ * Error that occurred during file deletion
65
+ */
66
+ interface DeleteFileError {
67
+ /** ID of the file that failed to delete */
68
+ id: string;
69
+ /** Error message */
70
+ error: string;
71
+ }
72
+ /**
73
+ * Result of file deletion
74
+ */
75
+ interface DeleteFilesResult {
76
+ /** Number of files deleted */
77
+ deletedCount: number;
78
+ /** Total bytes freed */
79
+ freedBytes: number;
80
+ /** IDs of files that were successfully deleted */
81
+ deleted: string[];
82
+ /** Files that failed to delete with error details */
83
+ failed: DeleteFileError[];
84
+ }
85
+ /**
86
+ * File validation constraints
87
+ */
88
+ interface FileConstraints {
89
+ /** Maximum file size in bytes */
90
+ maxSizeBytes?: number;
91
+ /** Maximum number of files */
92
+ maxFiles?: number;
93
+ /** Allowed MIME types (supports wildcards like 'image/*') */
94
+ acceptedTypes?: string[];
95
+ }
96
+ /**
97
+ * File validation error
98
+ */
99
+ interface FileValidationError {
100
+ /** The file that failed validation */
101
+ file: File;
102
+ /** Error code */
103
+ code: 'TOO_LARGE' | 'INVALID_TYPE' | 'TOO_MANY_FILES';
104
+ /** Human-readable message */
105
+ message: string;
106
+ }
107
+ /**
108
+ * Convert StoredFile metadata to BlobMetadata
109
+ */
110
+ declare function storedFileToBlobMetadata(file: StoredFile): BlobMetadata;
111
+ /**
112
+ * Convert BlobMetadata to StoredFile
113
+ */
114
+ declare function blobMetadataToStoredFile(id: string, metadata: BlobMetadata): StoredFile | null;
115
+
116
+ /**
117
+ * File storage service
118
+ *
119
+ * Provides high-level API for storing and managing file attachments
120
+ * associated with forms.
121
+ */
122
+
123
+ /**
124
+ * File storage service
125
+ */
126
+ declare class FileStorageService {
127
+ private readonly adapter;
128
+ constructor(adapter: StorageAdapter);
129
+ /**
130
+ * Validate files against constraints
131
+ */
132
+ validateFiles(files: File[], constraints: FileConstraints, existingCount?: number): FileValidationError[];
133
+ /**
134
+ * Store a file
135
+ */
136
+ storeFile(file: File, options: StoreFileOptions): Promise<StoredFile>;
137
+ /**
138
+ * Store multiple files
139
+ */
140
+ storeFiles(files: File[], options: StoreFileOptions): Promise<StoredFile[]>;
141
+ /**
142
+ * Get a single file by ID
143
+ */
144
+ getFile(id: string, generatePreview?: boolean): Promise<PersistedFile | null>;
145
+ /**
146
+ * Get files matching options
147
+ */
148
+ getFiles(options?: GetFilesOptions): Promise<PersistedFile[]>;
149
+ /**
150
+ * Get file IDs for a form/field
151
+ */
152
+ getFileIds(formKey: string, fieldName?: string): Promise<string[]>;
153
+ /**
154
+ * Delete a single file
155
+ * @returns true if file was deleted, false if file didn't exist
156
+ * @throws Error if deletion fails for other reasons
157
+ */
158
+ deleteFile(id: string): Promise<boolean>;
159
+ /**
160
+ * Delete multiple files
161
+ */
162
+ deleteFiles(ids: string[]): Promise<DeleteFilesResult>;
163
+ /**
164
+ * Delete all files for a form
165
+ */
166
+ deleteFormFiles(formKey: string, fieldName?: string): Promise<DeleteFilesResult>;
167
+ /**
168
+ * Convert stored files back to File objects for submission
169
+ */
170
+ getFilesAsFileObjects(ids: string[]): Promise<Map<string, File>>;
171
+ /**
172
+ * Revoke preview URLs to free memory
173
+ */
174
+ revokePreviewUrls(files: PersistedFile[]): void;
175
+ }
176
+ /**
177
+ * Create a file storage service
178
+ */
179
+ declare function createFileStorageService(adapter: StorageAdapter): FileStorageService;
180
+
181
+ export { type DeleteFileError, type DeleteFilesResult, type FileConstraints, FileStorageService, type FileValidationError, type GetFilesOptions, type PersistedFile, type StoreFileOptions, type StoredFile, blobMetadataToStoredFile, createFileStorageService, storedFileToBlobMetadata };
@@ -0,0 +1,2 @@
1
+ export { FileStorageService, blobMetadataToStoredFile, createFileStorageService, storedFileToBlobMetadata } from '../chunk-U27TKOYZ.js';
2
+ import '../chunk-ZC7F2HDV.js';