@anfenn/dync 1.0.3 → 1.0.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.
- package/README.md +32 -14
- package/dist/{chunk-66PSQW4D.js → chunk-YAAFAS64.js} +42 -42
- package/dist/chunk-YAAFAS64.js.map +1 -0
- package/dist/{dexie-Bv-fV10P.d.cts → dexie-1_xyU5MV.d.cts} +41 -38
- package/dist/{dexie-DJFApKsM.d.ts → dexie-ChZ0o0Sz.d.ts} +41 -38
- package/dist/dexie.cjs +40 -40
- package/dist/dexie.cjs.map +1 -1
- package/dist/dexie.d.cts +1 -1
- package/dist/dexie.d.ts +1 -1
- package/dist/dexie.js +40 -40
- package/dist/dexie.js.map +1 -1
- package/dist/index.cjs +41 -41
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{index.shared-CkYsQYyn.d.ts → index.shared-3gbnIINY.d.ts} +4 -4
- package/dist/{index.shared-BGwvMH8f.d.cts → index.shared-XsB8HrvX.d.cts} +4 -4
- package/dist/react/index.cjs +26 -26
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +2 -2
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +1 -1
- package/dist/wa-sqlite.cjs +2 -2
- package/dist/wa-sqlite.cjs.map +1 -1
- package/dist/wa-sqlite.d.cts +2 -2
- package/dist/wa-sqlite.d.ts +2 -2
- package/dist/wa-sqlite.js +2 -2
- package/dist/wa-sqlite.js.map +1 -1
- package/package.json +1 -1
- package/src/core/StateManager.ts +4 -4
- package/src/core/pullOperations.ts +3 -3
- package/src/core/pushOperations.ts +13 -13
- package/src/core/tableEnhancers.ts +20 -20
- package/src/helpers.ts +1 -1
- package/src/storage/dexie/DexieAdapter.ts +2 -2
- package/src/storage/dexie/{DexieStorageCollection.ts → DexieCollection.ts} +12 -12
- package/src/storage/dexie/DexieTable.ts +123 -0
- package/src/storage/dexie/{DexieStorageWhereClause.ts → DexieWhereClause.ts} +21 -21
- package/src/storage/dexie/index.ts +3 -3
- package/src/storage/memory/MemoryTable.ts +40 -40
- package/src/storage/sqlite/SQLiteTable.ts +34 -36
- package/src/storage/sqlite/drivers/WaSqliteDriver.ts +6 -6
- package/src/storage/types.ts +22 -19
- package/src/types.ts +4 -4
- package/dist/chunk-66PSQW4D.js.map +0 -1
- package/src/storage/dexie/DexieStorageTable.ts +0 -123
package/dist/react/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-
|
|
2
|
-
import { c as StorageAdapter } from '../dexie-
|
|
1
|
+
import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-XsB8HrvX.cjs';
|
|
2
|
+
import { c as StorageAdapter } from '../dexie-1_xyU5MV.cjs';
|
|
3
3
|
import '../types-CSbIAfu2.cjs';
|
|
4
4
|
import 'dexie';
|
|
5
5
|
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-
|
|
2
|
-
import { c as StorageAdapter } from '../dexie-
|
|
1
|
+
import { a as ApiFunctions, h as SyncOptions, B as BatchSync, D as Dync, i as SyncState } from '../index.shared-3gbnIINY.js';
|
|
2
|
+
import { c as StorageAdapter } from '../dexie-ChZ0o0Sz.js';
|
|
3
3
|
import '../types-CSbIAfu2.js';
|
|
4
4
|
import 'dexie';
|
|
5
5
|
|
package/dist/react/index.js
CHANGED
package/dist/wa-sqlite.cjs
CHANGED
|
@@ -267,9 +267,9 @@ var WaSqliteDriver = class {
|
|
|
267
267
|
}
|
|
268
268
|
/**
|
|
269
269
|
* Delete the database.
|
|
270
|
-
* This will close the database if open and
|
|
270
|
+
* This will close the database if open and delete all persisted data.
|
|
271
271
|
* For IndexedDB-based VFS, this deletes the IndexedDB database.
|
|
272
|
-
* For OPFS-based VFS, this
|
|
272
|
+
* For OPFS-based VFS, this deletes the files from OPFS.
|
|
273
273
|
*/
|
|
274
274
|
async delete() {
|
|
275
275
|
if (this.opened) {
|
package/dist/wa-sqlite.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wa-sqlite.ts","../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["// wa-sqlite Browser SQLite Driver\n// Import this entry point for browser/web builds with SQLite support\nexport { WaSqliteDriver, type WaSqliteDriverOptions, type WaSqliteVfsType } from './storage/sqlite/drivers/WaSqliteDriver';\nexport type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from './storage/sqlite/types';\n","import type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from '../types';\n\n/**\n * Virtual File System (VFS) options for wa-sqlite.\n * Each VFS has different trade-offs for performance, durability, and compatibility.\n *\n * @see https://github.com/rhashimoto/wa-sqlite/tree/master/src/examples#vfs-comparison\n */\nexport type WaSqliteVfsType =\n /**\n * IDBBatchAtomicVFS - IndexedDB-backed storage\n * - Works on ALL contexts (Window, Worker, SharedWorker, service worker)\n * - Supports multiple connections\n * - Full durability with batch atomic writes\n * - Good general-purpose choice for maximum compatibility\n * @recommended For apps that need to work in main thread and don't need OPFS\n */\n | 'IDBBatchAtomicVFS'\n /**\n * IDBMirrorVFS - IndexedDB with in-memory mirror\n * - Works on ALL contexts\n * - Supports multiple connections\n * - Much faster than IDBBatchAtomicVFS\n * - Database must fit in available memory\n * @recommended For small databases where performance is critical\n */\n | 'IDBMirrorVFS'\n /**\n * OPFSCoopSyncVFS - OPFS with cooperative synchronous access\n * - Requires Worker context\n * - Supports multiple connections\n * - Filesystem transparent (can import/export files)\n * - Good balance of performance and compatibility\n * @recommended For apps needing OPFS with multi-connection support\n */\n | 'OPFSCoopSyncVFS'\n /**\n * AccessHandlePoolVFS - OPFS-backed storage (fastest single connection)\n * - Requires Worker context\n * - Single connection only (no multi-tab support)\n * - Best performance, supports WAL mode\n * - NOT filesystem transparent\n * @recommended For single-tab apps where performance is critical\n */\n | 'AccessHandlePoolVFS';\n\n/**\n * Options for configuring the WaSqliteDriver.\n */\nexport interface WaSqliteDriverOptions {\n /**\n * Virtual File System to use for storage.\n * @default 'IDBBatchAtomicVFS'\n */\n vfs?: WaSqliteVfsType;\n\n /**\n * Directory path for the database in OPFS VFS modes.\n * Only used with OPFS-based VFS types.\n * @default '/'\n */\n directory?: string;\n\n /**\n * SQLite page size in bytes.\n * Larger pages can improve read performance for large BLOBs.\n * Cannot be changed after database creation for IDBBatchAtomicVFS/IDBMirrorVFS.\n * @default 4096\n */\n pageSize?: number;\n\n /**\n * SQLite cache size in pages (negative = KB, positive = pages).\n * Larger cache improves performance but uses more memory.\n * For IDBBatchAtomicVFS, must be large enough to hold journal for batch atomic mode.\n * @default -2000 (2MB)\n */\n cacheSize?: number;\n\n /**\n * Enable WAL (Write-Ahead Logging) mode.\n * Only supported with AccessHandlePoolVFS (with locking_mode=exclusive).\n * For other VFS types, this is ignored.\n * @default false\n */\n wal?: boolean;\n\n /**\n * Set synchronous pragma for durability vs performance trade-off.\n * - 'full': Maximum durability (default)\n * - 'normal': Relaxed durability, better performance (supported by IDBBatchAtomicVFS, IDBMirrorVFS, OPFSPermutedVFS)\n * - 'off': No sync, fastest but risks data loss on crash\n * @default 'full'\n */\n synchronous?: 'full' | 'normal' | 'off';\n}\n\n// Internal VFS interface for lifecycle management\ninterface WaSqliteVFS {\n close(): Promise<void>;\n name: string;\n}\n\n// VFS class type with static create method\ninterface VFSClass {\n create(name: string, module: any, options?: any): Promise<WaSqliteVFS>;\n}\n\n// Cached module factory and instance\nlet cachedModuleFactory: (() => Promise<any>) | null = null;\nlet cachedModule: any = null;\nlet cachedSqlite3: any = null;\n// Track VFS instances by name to avoid re-registering\nconst registeredVFS = new Map<string, WaSqliteVFS>();\n\n/**\n * SQLite driver for web browsers using wa-sqlite with IndexedDB or OPFS persistence.\n * Provides robust, persistent SQLite storage in the browser that prevents data loss.\n *\n * ## Data Safety Features\n *\n * - **IDBBatchAtomicVFS** (default): Uses IndexedDB batch atomic writes to ensure transactions\n * are either fully committed or not at all. Multi-tab safe.\n * - **IDBMirrorVFS**: IndexedDB with in-memory mirror. Much faster, database must fit in RAM.\n * - **OPFSCoopSyncVFS**: OPFS with cooperative sync. Multi-connection, filesystem transparent.\n * - **AccessHandlePoolVFS**: Uses OPFS Access Handles for high performance. Single-tab only.\n * - Full durability by default (`PRAGMA synchronous=full`)\n * - Automatic journal mode configuration for each VFS type\n *\n * ## VFS Selection Guide\n *\n * | VFS | Best For | Multi-Tab | Speed |\n * |-----|----------|-----------|-------|\n * | IDBBatchAtomicVFS | General use, main thread | ✅ | Good |\n * | IDBMirrorVFS | Small DBs, main thread | ✅ | Fast |\n * | OPFSCoopSyncVFS | Web Workers, file export | ✅ | Good |\n * | AccessHandlePoolVFS | Single-tab performance | ❌ | Fastest |\n *\n * @example\n * ```ts\n * import { WaSqliteDriver } from '@anfenn/dync/wa-sqlite';\n * import { SQLiteAdapter } from '@anfenn/dync';\n *\n * // Default: IDBBatchAtomicVFS (works in main thread, multi-tab safe)\n * const driver = new WaSqliteDriver('myapp.db');\n *\n * // For OPFS (faster, requires Worker, filesystem transparent)\n * const opfsDriver = new WaSqliteDriver('myapp.db', { vfs: 'OPFSCoopSyncVFS' });\n *\n * const adapter = new SQLiteAdapter('myapp', driver);\n * ```\n */\nexport class WaSqliteDriver implements SQLiteDatabaseDriver {\n readonly type = 'WaSqliteDriver';\n private db: number | null = null;\n private sqlite3: any = null;\n private readonly options: Required<WaSqliteDriverOptions>;\n private opened = false;\n private openPromise: Promise<void> | null = null;\n // Mutex to prevent concurrent database operations (critical for wa-sqlite)\n private executionLock: Promise<void> = Promise.resolve();\n readonly name: string;\n\n constructor(databaseName: string, options: WaSqliteDriverOptions = {}) {\n this.name = databaseName;\n this.options = {\n vfs: 'IDBBatchAtomicVFS',\n directory: '/',\n pageSize: 4096,\n cacheSize: -2000,\n wal: false,\n synchronous: 'full',\n ...options,\n };\n }\n\n /**\n * Execute a callback with exclusive database access.\n * This prevents concurrent operations which can corrupt the database.\n */\n private async withLock<T>(fn: () => Promise<T>): Promise<T> {\n // Chain onto the existing lock\n const previousLock = this.executionLock;\n let releaseLock: () => void;\n this.executionLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n try {\n // Wait for previous operation to complete\n await previousLock;\n // Execute our operation\n return await fn();\n } finally {\n // Release the lock\n releaseLock!();\n }\n }\n\n async open(): Promise<void> {\n if (this.opened) return;\n if (this.openPromise) return this.openPromise;\n\n this.openPromise = this._open();\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n private async _open(): Promise<void> {\n // Load wa-sqlite module (asyncify build for async VFS support)\n const module = await this.loadWasmModule();\n\n // Create SQLite API from module (cached - must only create once per module)\n if (!cachedSqlite3) {\n const { Factory } = await import('@journeyapps/wa-sqlite');\n cachedSqlite3 = Factory(module);\n }\n this.sqlite3 = cachedSqlite3;\n\n // For IDB-based VFS, the VFS name is also used as the IndexedDB database name\n // Use a unique name based on database name to avoid conflicts\n const vfsName = `dync_${this.options.vfs}_${this.name}`.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n // Reuse existing VFS instance or create and register a new one\n let existingVfs = registeredVFS.get(vfsName);\n if (!existingVfs) {\n existingVfs = await this.createVFS(module, vfsName);\n // Register VFS with SQLite as default (like PowerSync does)\n this.sqlite3.vfs_register(existingVfs, true);\n registeredVFS.set(vfsName, existingVfs);\n }\n\n // Build database path - for IDB VFS, this is the \"file\" path within the VFS\n const dbPath = this.buildDatabasePath();\n\n // Open database (VFS is registered as default)\n this.db = await this.sqlite3.open_v2(dbPath);\n\n // Configure database pragmas for performance and durability\n await this.configurePragmas();\n\n this.opened = true;\n }\n\n private async loadWasmModule(): Promise<any> {\n if (!cachedModule) {\n if (!cachedModuleFactory) {\n // Dynamically import the asyncify build for async VFS support\n const wasmModule = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n cachedModuleFactory = wasmModule.default;\n }\n // Cache the module instance - all VFS and sqlite3 APIs must share the same module\n cachedModule = await cachedModuleFactory();\n }\n return cachedModule;\n }\n\n private async createVFS(module: any, vfsName: string): Promise<WaSqliteVFS> {\n const vfsType = this.options.vfs;\n let VFSClass: VFSClass;\n let vfsOptions: any = undefined;\n\n // Dynamically import VFS implementation\n // Note: We cast to unknown first because the package types don't include the static create method\n switch (vfsType) {\n case 'IDBBatchAtomicVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n VFSClass = mod.IDBBatchAtomicVFS as unknown as VFSClass;\n // Use exclusive lock policy like PowerSync does\n vfsOptions = { lockPolicy: 'exclusive' };\n break;\n }\n case 'IDBMirrorVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBMirrorVFS.js');\n VFSClass = mod.IDBMirrorVFS as unknown as VFSClass;\n break;\n }\n case 'OPFSCoopSyncVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n VFSClass = mod.OPFSCoopSyncVFS as unknown as VFSClass;\n break;\n }\n case 'AccessHandlePoolVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n VFSClass = mod.AccessHandlePoolVFS as unknown as VFSClass;\n break;\n }\n default:\n throw new Error(`Unsupported VFS type: ${vfsType}`);\n }\n\n return VFSClass.create(vfsName, module, vfsOptions);\n }\n\n private buildDatabasePath(): string {\n const vfsType = this.options.vfs;\n\n // For IDB-based VFS, use database name directly\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n return this.name;\n }\n\n // For OPFS-based VFS, build full path\n const directory = this.options.directory.replace(/\\/$/, '');\n return `${directory}/${this.name}`;\n }\n\n private async configurePragmas(): Promise<void> {\n if (!this.db || !this.sqlite3) return;\n\n // Page size can only be set on new/empty databases\n // For IDBBatchAtomicVFS, it cannot be changed after creation\n // Try to set it, but ignore errors if the database already exists\n try {\n await this.sqlite3.exec(this.db, `PRAGMA page_size = ${this.options.pageSize}`);\n } catch {\n // Page size already set, ignore\n }\n\n // Cache size for performance\n await this.sqlite3.exec(this.db, `PRAGMA cache_size = ${this.options.cacheSize}`);\n\n // WAL mode only for AccessHandlePoolVFS with exclusive locking\n if (this.options.wal && this.options.vfs === 'AccessHandlePoolVFS') {\n await this.sqlite3.exec(this.db, 'PRAGMA locking_mode = exclusive');\n await this.sqlite3.exec(this.db, 'PRAGMA journal_mode = WAL');\n }\n // Note: For IDB-based VFS, we don't set journal_mode - let the VFS handle it\n }\n\n async close(): Promise<void> {\n if (!this.opened || !this.db || !this.sqlite3) return;\n\n // Wait for any pending operations to complete by acquiring the lock\n await this.withLock(async () => {\n // Ensure all data is flushed before closing\n // This is critical for IDB-based VFS which batch writes\n try {\n await this.sqlite3!.exec(this.db!, 'PRAGMA wal_checkpoint(TRUNCATE)');\n } catch {\n // Ignore if WAL mode not enabled\n }\n\n await this.sqlite3!.close(this.db!);\n\n // Don't close the shared VFS - it may be used by other connections\n // The VFS will be cleaned up when all references are gone\n this.db = null;\n this.opened = false;\n });\n }\n\n async execute(statement: string): Promise<void> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n await this.withLock(async () => {\n await this.sqlite3.exec(this.db, statement);\n });\n }\n\n async run(statement: string, values: unknown[] = []): Promise<SQLiteRunResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Execute the statement\n await this.sqlite3.step(stmt);\n }\n\n return {\n changes: this.sqlite3.changes(this.db),\n lastId: Number(this.sqlite3.last_insert_id(this.db)),\n };\n });\n }\n\n /**\n * Convert values for SQLite compatibility.\n * - Booleans must be converted to integers (SQLite has no boolean type)\n */\n private convertValues(values: unknown[]): unknown[] {\n return values.map((value) => {\n if (typeof value === 'boolean') {\n return value ? 1 : 0;\n }\n return value;\n });\n }\n\n async query(statement: string, values: unknown[] = []): Promise<SQLiteQueryResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n const { SQLITE_ROW } = await import('@journeyapps/wa-sqlite');\n const allRows: unknown[][] = [];\n let columns: string[] = [];\n\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Get column names\n if (columns.length === 0) {\n columns = this.sqlite3.column_names(stmt);\n }\n\n // Fetch all rows\n while ((await this.sqlite3.step(stmt)) === SQLITE_ROW) {\n const row = this.sqlite3.row(stmt);\n allRows.push(row);\n }\n }\n\n return { columns, values: allRows };\n });\n }\n\n /**\n * Check if the database is currently open.\n */\n isOpen(): boolean {\n return this.opened;\n }\n\n /**\n * Get the VFS type being used by this driver.\n */\n getVfsType(): WaSqliteVfsType {\n return this.options.vfs;\n }\n\n /**\n * Delete the database.\n * This will close the database if open and remove all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this removes the files from OPFS.\n */\n async delete(): Promise<void> {\n // Close if open\n if (this.opened) {\n await this.close();\n }\n\n const vfsType = this.options.vfs;\n\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n // Delete IndexedDB database\n await new Promise<void>((resolve, reject) => {\n const request = indexedDB.deleteDatabase(this.name);\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error);\n request.onblocked = () => {\n console.warn(`Database deletion blocked for ${this.name}. Close all connections and try again.`);\n };\n });\n } else {\n // For OPFS-based VFS, remove the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to remove the file/directory\n const pathParts = dbPath.split('/').filter(Boolean);\n let current = root;\n\n // Navigate to parent directory\n for (let i = 0; i < pathParts.length - 1; i++) {\n current = await current.getDirectoryHandle(pathParts[i]!);\n }\n\n // Remove the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to remove associated journal/wal files\n const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];\n for (const file of associatedFiles) {\n try {\n await current.removeEntry(file, { recursive: false });\n } catch {\n // Ignore if file doesn't exist\n }\n }\n } catch (error) {\n // Ignore if directory doesn't exist\n if ((error as Error).name !== 'NotFoundError') {\n throw error;\n }\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6GA,IAAI,sBAAmD;AACvD,IAAI,eAAoB;AACxB,IAAI,gBAAqB;AAEzB,IAAM,gBAAgB,oBAAI,IAAyB;AAuC5C,IAAM,iBAAN,MAAqD;AAAA,EAC/C,OAAO;AAAA,EACR,KAAoB;AAAA,EACpB,UAAe;AAAA,EACN;AAAA,EACT,SAAS;AAAA,EACT,cAAoC;AAAA;AAAA,EAEpC,gBAA+B,QAAQ,QAAQ;AAAA,EAC9C;AAAA,EAET,YAAY,cAAsB,UAAiC,CAAC,GAAG;AACnE,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACX,KAAK;AA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cAAM,kBAAkB,CAAC,GAAG,QAAQ,YAAY,GAAG,QAAQ,QAAQ,GAAG,QAAQ,MAAM;AACpF,mBAAW,QAAQ,iBAAiB;AAChC,cAAI;AACA,kBAAM,QAAQ,YAAY,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,UACxD,QAAQ;AAAA,UAER;AAAA,QACJ;AAAA,MACJ,SAAS,OAAO;AAEZ,YAAK,MAAgB,SAAS,iBAAiB;AAC3C,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":["module"]}
|
|
1
|
+
{"version":3,"sources":["../src/wa-sqlite.ts","../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["// wa-sqlite Browser SQLite Driver\n// Import this entry point for browser/web builds with SQLite support\nexport { WaSqliteDriver, type WaSqliteDriverOptions, type WaSqliteVfsType } from './storage/sqlite/drivers/WaSqliteDriver';\nexport type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from './storage/sqlite/types';\n","import type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from '../types';\n\n/**\n * Virtual File System (VFS) options for wa-sqlite.\n * Each VFS has different trade-offs for performance, durability, and compatibility.\n *\n * @see https://github.com/rhashimoto/wa-sqlite/tree/master/src/examples#vfs-comparison\n */\nexport type WaSqliteVfsType =\n /**\n * IDBBatchAtomicVFS - IndexedDB-backed storage\n * - Works on ALL contexts (Window, Worker, SharedWorker, service worker)\n * - Supports multiple connections\n * - Full durability with batch atomic writes\n * - Good general-purpose choice for maximum compatibility\n * @recommended For apps that need to work in main thread and don't need OPFS\n */\n | 'IDBBatchAtomicVFS'\n /**\n * IDBMirrorVFS - IndexedDB with in-memory mirror\n * - Works on ALL contexts\n * - Supports multiple connections\n * - Much faster than IDBBatchAtomicVFS\n * - Database must fit in available memory\n * @recommended For small databases where performance is critical\n */\n | 'IDBMirrorVFS'\n /**\n * OPFSCoopSyncVFS - OPFS with cooperative synchronous access\n * - Requires Worker context\n * - Supports multiple connections\n * - Filesystem transparent (can import/export files)\n * - Good balance of performance and compatibility\n * @recommended For apps needing OPFS with multi-connection support\n */\n | 'OPFSCoopSyncVFS'\n /**\n * AccessHandlePoolVFS - OPFS-backed storage (fastest single connection)\n * - Requires Worker context\n * - Single connection only (no multi-tab support)\n * - Best performance, supports WAL mode\n * - NOT filesystem transparent\n * @recommended For single-tab apps where performance is critical\n */\n | 'AccessHandlePoolVFS';\n\n/**\n * Options for configuring the WaSqliteDriver.\n */\nexport interface WaSqliteDriverOptions {\n /**\n * Virtual File System to use for storage.\n * @default 'IDBBatchAtomicVFS'\n */\n vfs?: WaSqliteVfsType;\n\n /**\n * Directory path for the database in OPFS VFS modes.\n * Only used with OPFS-based VFS types.\n * @default '/'\n */\n directory?: string;\n\n /**\n * SQLite page size in bytes.\n * Larger pages can improve read performance for large BLOBs.\n * Cannot be changed after database creation for IDBBatchAtomicVFS/IDBMirrorVFS.\n * @default 4096\n */\n pageSize?: number;\n\n /**\n * SQLite cache size in pages (negative = KB, positive = pages).\n * Larger cache improves performance but uses more memory.\n * For IDBBatchAtomicVFS, must be large enough to hold journal for batch atomic mode.\n * @default -2000 (2MB)\n */\n cacheSize?: number;\n\n /**\n * Enable WAL (Write-Ahead Logging) mode.\n * Only supported with AccessHandlePoolVFS (with locking_mode=exclusive).\n * For other VFS types, this is ignored.\n * @default false\n */\n wal?: boolean;\n\n /**\n * Set synchronous pragma for durability vs performance trade-off.\n * - 'full': Maximum durability (default)\n * - 'normal': Relaxed durability, better performance (supported by IDBBatchAtomicVFS, IDBMirrorVFS, OPFSPermutedVFS)\n * - 'off': No sync, fastest but risks data loss on crash\n * @default 'full'\n */\n synchronous?: 'full' | 'normal' | 'off';\n}\n\n// Internal VFS interface for lifecycle management\ninterface WaSqliteVFS {\n close(): Promise<void>;\n name: string;\n}\n\n// VFS class type with static create method\ninterface VFSClass {\n create(name: string, module: any, options?: any): Promise<WaSqliteVFS>;\n}\n\n// Cached module factory and instance\nlet cachedModuleFactory: (() => Promise<any>) | null = null;\nlet cachedModule: any = null;\nlet cachedSqlite3: any = null;\n// Track VFS instances by name to avoid re-registering\nconst registeredVFS = new Map<string, WaSqliteVFS>();\n\n/**\n * SQLite driver for web browsers using wa-sqlite with IndexedDB or OPFS persistence.\n * Provides robust, persistent SQLite storage in the browser that prevents data loss.\n *\n * ## Data Safety Features\n *\n * - **IDBBatchAtomicVFS** (default): Uses IndexedDB batch atomic writes to ensure transactions\n * are either fully committed or not at all. Multi-tab safe.\n * - **IDBMirrorVFS**: IndexedDB with in-memory mirror. Much faster, database must fit in RAM.\n * - **OPFSCoopSyncVFS**: OPFS with cooperative sync. Multi-connection, filesystem transparent.\n * - **AccessHandlePoolVFS**: Uses OPFS Access Handles for high performance. Single-tab only.\n * - Full durability by default (`PRAGMA synchronous=full`)\n * - Automatic journal mode configuration for each VFS type\n *\n * ## VFS Selection Guide\n *\n * | VFS | Best For | Multi-Tab | Speed |\n * |-----|----------|-----------|-------|\n * | IDBBatchAtomicVFS | General use, main thread | ✅ | Good |\n * | IDBMirrorVFS | Small DBs, main thread | ✅ | Fast |\n * | OPFSCoopSyncVFS | Web Workers, file export | ✅ | Good |\n * | AccessHandlePoolVFS | Single-tab performance | ❌ | Fastest |\n *\n * @example\n * ```ts\n * import { WaSqliteDriver } from '@anfenn/dync/wa-sqlite';\n * import { SQLiteAdapter } from '@anfenn/dync';\n *\n * // Default: IDBBatchAtomicVFS (works in main thread, multi-tab safe)\n * const driver = new WaSqliteDriver('myapp.db');\n *\n * // For OPFS (faster, requires Worker, filesystem transparent)\n * const opfsDriver = new WaSqliteDriver('myapp.db', { vfs: 'OPFSCoopSyncVFS' });\n *\n * const adapter = new SQLiteAdapter('myapp', driver);\n * ```\n */\nexport class WaSqliteDriver implements SQLiteDatabaseDriver {\n readonly type = 'WaSqliteDriver';\n private db: number | null = null;\n private sqlite3: any = null;\n private readonly options: Required<WaSqliteDriverOptions>;\n private opened = false;\n private openPromise: Promise<void> | null = null;\n // Mutex to prevent concurrent database operations (critical for wa-sqlite)\n private executionLock: Promise<void> = Promise.resolve();\n readonly name: string;\n\n constructor(databaseName: string, options: WaSqliteDriverOptions = {}) {\n this.name = databaseName;\n this.options = {\n vfs: 'IDBBatchAtomicVFS',\n directory: '/',\n pageSize: 4096,\n cacheSize: -2000,\n wal: false,\n synchronous: 'full',\n ...options,\n };\n }\n\n /**\n * Execute a callback with exclusive database access.\n * This prevents concurrent operations which can corrupt the database.\n */\n private async withLock<T>(fn: () => Promise<T>): Promise<T> {\n // Chain onto the existing lock\n const previousLock = this.executionLock;\n let releaseLock: () => void;\n this.executionLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n try {\n // Wait for previous operation to complete\n await previousLock;\n // Execute our operation\n return await fn();\n } finally {\n // Release the lock\n releaseLock!();\n }\n }\n\n async open(): Promise<void> {\n if (this.opened) return;\n if (this.openPromise) return this.openPromise;\n\n this.openPromise = this._open();\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n private async _open(): Promise<void> {\n // Load wa-sqlite module (asyncify build for async VFS support)\n const module = await this.loadWasmModule();\n\n // Create SQLite API from module (cached - must only create once per module)\n if (!cachedSqlite3) {\n const { Factory } = await import('@journeyapps/wa-sqlite');\n cachedSqlite3 = Factory(module);\n }\n this.sqlite3 = cachedSqlite3;\n\n // For IDB-based VFS, the VFS name is also used as the IndexedDB database name\n // Use a unique name based on database name to avoid conflicts\n const vfsName = `dync_${this.options.vfs}_${this.name}`.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n // Reuse existing VFS instance or create and register a new one\n let existingVfs = registeredVFS.get(vfsName);\n if (!existingVfs) {\n existingVfs = await this.createVFS(module, vfsName);\n // Register VFS with SQLite as default (like PowerSync does)\n this.sqlite3.vfs_register(existingVfs, true);\n registeredVFS.set(vfsName, existingVfs);\n }\n\n // Build database path - for IDB VFS, this is the \"file\" path within the VFS\n const dbPath = this.buildDatabasePath();\n\n // Open database (VFS is registered as default)\n this.db = await this.sqlite3.open_v2(dbPath);\n\n // Configure database pragmas for performance and durability\n await this.configurePragmas();\n\n this.opened = true;\n }\n\n private async loadWasmModule(): Promise<any> {\n if (!cachedModule) {\n if (!cachedModuleFactory) {\n // Dynamically import the asyncify build for async VFS support\n const wasmModule = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n cachedModuleFactory = wasmModule.default;\n }\n // Cache the module instance - all VFS and sqlite3 APIs must share the same module\n cachedModule = await cachedModuleFactory();\n }\n return cachedModule;\n }\n\n private async createVFS(module: any, vfsName: string): Promise<WaSqliteVFS> {\n const vfsType = this.options.vfs;\n let VFSClass: VFSClass;\n let vfsOptions: any = undefined;\n\n // Dynamically import VFS implementation\n // Note: We cast to unknown first because the package types don't include the static create method\n switch (vfsType) {\n case 'IDBBatchAtomicVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n VFSClass = mod.IDBBatchAtomicVFS as unknown as VFSClass;\n // Use exclusive lock policy like PowerSync does\n vfsOptions = { lockPolicy: 'exclusive' };\n break;\n }\n case 'IDBMirrorVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBMirrorVFS.js');\n VFSClass = mod.IDBMirrorVFS as unknown as VFSClass;\n break;\n }\n case 'OPFSCoopSyncVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n VFSClass = mod.OPFSCoopSyncVFS as unknown as VFSClass;\n break;\n }\n case 'AccessHandlePoolVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n VFSClass = mod.AccessHandlePoolVFS as unknown as VFSClass;\n break;\n }\n default:\n throw new Error(`Unsupported VFS type: ${vfsType}`);\n }\n\n return VFSClass.create(vfsName, module, vfsOptions);\n }\n\n private buildDatabasePath(): string {\n const vfsType = this.options.vfs;\n\n // For IDB-based VFS, use database name directly\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n return this.name;\n }\n\n // For OPFS-based VFS, build full path\n const directory = this.options.directory.replace(/\\/$/, '');\n return `${directory}/${this.name}`;\n }\n\n private async configurePragmas(): Promise<void> {\n if (!this.db || !this.sqlite3) return;\n\n // Page size can only be set on new/empty databases\n // For IDBBatchAtomicVFS, it cannot be changed after creation\n // Try to set it, but ignore errors if the database already exists\n try {\n await this.sqlite3.exec(this.db, `PRAGMA page_size = ${this.options.pageSize}`);\n } catch {\n // Page size already set, ignore\n }\n\n // Cache size for performance\n await this.sqlite3.exec(this.db, `PRAGMA cache_size = ${this.options.cacheSize}`);\n\n // WAL mode only for AccessHandlePoolVFS with exclusive locking\n if (this.options.wal && this.options.vfs === 'AccessHandlePoolVFS') {\n await this.sqlite3.exec(this.db, 'PRAGMA locking_mode = exclusive');\n await this.sqlite3.exec(this.db, 'PRAGMA journal_mode = WAL');\n }\n // Note: For IDB-based VFS, we don't set journal_mode - let the VFS handle it\n }\n\n async close(): Promise<void> {\n if (!this.opened || !this.db || !this.sqlite3) return;\n\n // Wait for any pending operations to complete by acquiring the lock\n await this.withLock(async () => {\n // Ensure all data is flushed before closing\n // This is critical for IDB-based VFS which batch writes\n try {\n await this.sqlite3!.exec(this.db!, 'PRAGMA wal_checkpoint(TRUNCATE)');\n } catch {\n // Ignore if WAL mode not enabled\n }\n\n await this.sqlite3!.close(this.db!);\n\n // Don't close the shared VFS - it may be used by other connections\n // The VFS will be cleaned up when all references are gone\n this.db = null;\n this.opened = false;\n });\n }\n\n async execute(statement: string): Promise<void> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n await this.withLock(async () => {\n await this.sqlite3.exec(this.db, statement);\n });\n }\n\n async run(statement: string, values: unknown[] = []): Promise<SQLiteRunResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Execute the statement\n await this.sqlite3.step(stmt);\n }\n\n return {\n changes: this.sqlite3.changes(this.db),\n lastId: Number(this.sqlite3.last_insert_id(this.db)),\n };\n });\n }\n\n /**\n * Convert values for SQLite compatibility.\n * - Booleans must be converted to integers (SQLite has no boolean type)\n */\n private convertValues(values: unknown[]): unknown[] {\n return values.map((value) => {\n if (typeof value === 'boolean') {\n return value ? 1 : 0;\n }\n return value;\n });\n }\n\n async query(statement: string, values: unknown[] = []): Promise<SQLiteQueryResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n const { SQLITE_ROW } = await import('@journeyapps/wa-sqlite');\n const allRows: unknown[][] = [];\n let columns: string[] = [];\n\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Get column names\n if (columns.length === 0) {\n columns = this.sqlite3.column_names(stmt);\n }\n\n // Fetch all rows\n while ((await this.sqlite3.step(stmt)) === SQLITE_ROW) {\n const row = this.sqlite3.row(stmt);\n allRows.push(row);\n }\n }\n\n return { columns, values: allRows };\n });\n }\n\n /**\n * Check if the database is currently open.\n */\n isOpen(): boolean {\n return this.opened;\n }\n\n /**\n * Get the VFS type being used by this driver.\n */\n getVfsType(): WaSqliteVfsType {\n return this.options.vfs;\n }\n\n /**\n * Delete the database.\n * This will close the database if open and delete all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this deletes the files from OPFS.\n */\n async delete(): Promise<void> {\n // Close if open\n if (this.opened) {\n await this.close();\n }\n\n const vfsType = this.options.vfs;\n\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n // Delete IndexedDB database\n await new Promise<void>((resolve, reject) => {\n const request = indexedDB.deleteDatabase(this.name);\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error);\n request.onblocked = () => {\n console.warn(`Database deletion blocked for ${this.name}. Close all connections and try again.`);\n };\n });\n } else {\n // For OPFS-based VFS, delete the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to delete the file/directory\n const pathParts = dbPath.split('/').filter(Boolean);\n let current = root;\n\n // Navigate to parent directory\n for (let i = 0; i < pathParts.length - 1; i++) {\n current = await current.getDirectoryHandle(pathParts[i]!);\n }\n\n // Delete the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to delete associated journal/wal files\n const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];\n for (const file of associatedFiles) {\n try {\n await current.removeEntry(file, { recursive: false });\n } catch {\n // Ignore if file doesn't exist\n }\n }\n } catch (error) {\n // Ignore if directory doesn't exist\n if ((error as Error).name !== 'NotFoundError') {\n throw error;\n }\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC6GA,IAAI,sBAAmD;AACvD,IAAI,eAAoB;AACxB,IAAI,gBAAqB;AAEzB,IAAM,gBAAgB,oBAAI,IAAyB;AAuC5C,IAAM,iBAAN,MAAqD;AAAA,EAC/C,OAAO;AAAA,EACR,KAAoB;AAAA,EACpB,UAAe;AAAA,EACN;AAAA,EACT,SAAS;AAAA,EACT,cAAoC;AAAA;AAAA,EAEpC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AAU,CAAC,CAAE;AAAA,QAC5D;AAGA,cAAM,WAAW,UAAU,UAAU,SAAS,CAAC;AAC/C,cAAM,QAAQ,YAAY,UAAU,EAAE,WAAW,KAAK,CAAC;AAGvD,cAAM,kBAAkB,CAAC,GAAG,QAAQ,YAAY,GAAG,QAAQ,QAAQ,GAAG,QAAQ,MAAM;AACpF,mBAAW,QAAQ,iBAAiB;AAChC,cAAI;AACA,kBAAM,QAAQ,YAAY,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,UACxD,QAAQ;AAAA,UAER;AAAA,QACJ;AAAA,MACJ,SAAS,OAAO;AAEZ,YAAK,MAAgB,SAAS,iBAAiB;AAC3C,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":["module"]}
|
package/dist/wa-sqlite.d.cts
CHANGED
|
@@ -165,9 +165,9 @@ declare class WaSqliteDriver implements SQLiteDatabaseDriver {
|
|
|
165
165
|
getVfsType(): WaSqliteVfsType;
|
|
166
166
|
/**
|
|
167
167
|
* Delete the database.
|
|
168
|
-
* This will close the database if open and
|
|
168
|
+
* This will close the database if open and delete all persisted data.
|
|
169
169
|
* For IndexedDB-based VFS, this deletes the IndexedDB database.
|
|
170
|
-
* For OPFS-based VFS, this
|
|
170
|
+
* For OPFS-based VFS, this deletes the files from OPFS.
|
|
171
171
|
*/
|
|
172
172
|
delete(): Promise<void>;
|
|
173
173
|
}
|
package/dist/wa-sqlite.d.ts
CHANGED
|
@@ -165,9 +165,9 @@ declare class WaSqliteDriver implements SQLiteDatabaseDriver {
|
|
|
165
165
|
getVfsType(): WaSqliteVfsType;
|
|
166
166
|
/**
|
|
167
167
|
* Delete the database.
|
|
168
|
-
* This will close the database if open and
|
|
168
|
+
* This will close the database if open and delete all persisted data.
|
|
169
169
|
* For IndexedDB-based VFS, this deletes the IndexedDB database.
|
|
170
|
-
* For OPFS-based VFS, this
|
|
170
|
+
* For OPFS-based VFS, this deletes the files from OPFS.
|
|
171
171
|
*/
|
|
172
172
|
delete(): Promise<void>;
|
|
173
173
|
}
|
package/dist/wa-sqlite.js
CHANGED
|
@@ -231,9 +231,9 @@ var WaSqliteDriver = class {
|
|
|
231
231
|
}
|
|
232
232
|
/**
|
|
233
233
|
* Delete the database.
|
|
234
|
-
* This will close the database if open and
|
|
234
|
+
* This will close the database if open and delete all persisted data.
|
|
235
235
|
* For IndexedDB-based VFS, this deletes the IndexedDB database.
|
|
236
|
-
* For OPFS-based VFS, this
|
|
236
|
+
* For OPFS-based VFS, this deletes the files from OPFS.
|
|
237
237
|
*/
|
|
238
238
|
async delete() {
|
|
239
239
|
if (this.opened) {
|
package/dist/wa-sqlite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["import type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from '../types';\n\n/**\n * Virtual File System (VFS) options for wa-sqlite.\n * Each VFS has different trade-offs for performance, durability, and compatibility.\n *\n * @see https://github.com/rhashimoto/wa-sqlite/tree/master/src/examples#vfs-comparison\n */\nexport type WaSqliteVfsType =\n /**\n * IDBBatchAtomicVFS - IndexedDB-backed storage\n * - Works on ALL contexts (Window, Worker, SharedWorker, service worker)\n * - Supports multiple connections\n * - Full durability with batch atomic writes\n * - Good general-purpose choice for maximum compatibility\n * @recommended For apps that need to work in main thread and don't need OPFS\n */\n | 'IDBBatchAtomicVFS'\n /**\n * IDBMirrorVFS - IndexedDB with in-memory mirror\n * - Works on ALL contexts\n * - Supports multiple connections\n * - Much faster than IDBBatchAtomicVFS\n * - Database must fit in available memory\n * @recommended For small databases where performance is critical\n */\n | 'IDBMirrorVFS'\n /**\n * OPFSCoopSyncVFS - OPFS with cooperative synchronous access\n * - Requires Worker context\n * - Supports multiple connections\n * - Filesystem transparent (can import/export files)\n * - Good balance of performance and compatibility\n * @recommended For apps needing OPFS with multi-connection support\n */\n | 'OPFSCoopSyncVFS'\n /**\n * AccessHandlePoolVFS - OPFS-backed storage (fastest single connection)\n * - Requires Worker context\n * - Single connection only (no multi-tab support)\n * - Best performance, supports WAL mode\n * - NOT filesystem transparent\n * @recommended For single-tab apps where performance is critical\n */\n | 'AccessHandlePoolVFS';\n\n/**\n * Options for configuring the WaSqliteDriver.\n */\nexport interface WaSqliteDriverOptions {\n /**\n * Virtual File System to use for storage.\n * @default 'IDBBatchAtomicVFS'\n */\n vfs?: WaSqliteVfsType;\n\n /**\n * Directory path for the database in OPFS VFS modes.\n * Only used with OPFS-based VFS types.\n * @default '/'\n */\n directory?: string;\n\n /**\n * SQLite page size in bytes.\n * Larger pages can improve read performance for large BLOBs.\n * Cannot be changed after database creation for IDBBatchAtomicVFS/IDBMirrorVFS.\n * @default 4096\n */\n pageSize?: number;\n\n /**\n * SQLite cache size in pages (negative = KB, positive = pages).\n * Larger cache improves performance but uses more memory.\n * For IDBBatchAtomicVFS, must be large enough to hold journal for batch atomic mode.\n * @default -2000 (2MB)\n */\n cacheSize?: number;\n\n /**\n * Enable WAL (Write-Ahead Logging) mode.\n * Only supported with AccessHandlePoolVFS (with locking_mode=exclusive).\n * For other VFS types, this is ignored.\n * @default false\n */\n wal?: boolean;\n\n /**\n * Set synchronous pragma for durability vs performance trade-off.\n * - 'full': Maximum durability (default)\n * - 'normal': Relaxed durability, better performance (supported by IDBBatchAtomicVFS, IDBMirrorVFS, OPFSPermutedVFS)\n * - 'off': No sync, fastest but risks data loss on crash\n * @default 'full'\n */\n synchronous?: 'full' | 'normal' | 'off';\n}\n\n// Internal VFS interface for lifecycle management\ninterface WaSqliteVFS {\n close(): Promise<void>;\n name: string;\n}\n\n// VFS class type with static create method\ninterface VFSClass {\n create(name: string, module: any, options?: any): Promise<WaSqliteVFS>;\n}\n\n// Cached module factory and instance\nlet cachedModuleFactory: (() => Promise<any>) | null = null;\nlet cachedModule: any = null;\nlet cachedSqlite3: any = null;\n// Track VFS instances by name to avoid re-registering\nconst registeredVFS = new Map<string, WaSqliteVFS>();\n\n/**\n * SQLite driver for web browsers using wa-sqlite with IndexedDB or OPFS persistence.\n * Provides robust, persistent SQLite storage in the browser that prevents data loss.\n *\n * ## Data Safety Features\n *\n * - **IDBBatchAtomicVFS** (default): Uses IndexedDB batch atomic writes to ensure transactions\n * are either fully committed or not at all. Multi-tab safe.\n * - **IDBMirrorVFS**: IndexedDB with in-memory mirror. Much faster, database must fit in RAM.\n * - **OPFSCoopSyncVFS**: OPFS with cooperative sync. Multi-connection, filesystem transparent.\n * - **AccessHandlePoolVFS**: Uses OPFS Access Handles for high performance. Single-tab only.\n * - Full durability by default (`PRAGMA synchronous=full`)\n * - Automatic journal mode configuration for each VFS type\n *\n * ## VFS Selection Guide\n *\n * | VFS | Best For | Multi-Tab | Speed |\n * |-----|----------|-----------|-------|\n * | IDBBatchAtomicVFS | General use, main thread | ✅ | Good |\n * | IDBMirrorVFS | Small DBs, main thread | ✅ | Fast |\n * | OPFSCoopSyncVFS | Web Workers, file export | ✅ | Good |\n * | AccessHandlePoolVFS | Single-tab performance | ❌ | Fastest |\n *\n * @example\n * ```ts\n * import { WaSqliteDriver } from '@anfenn/dync/wa-sqlite';\n * import { SQLiteAdapter } from '@anfenn/dync';\n *\n * // Default: IDBBatchAtomicVFS (works in main thread, multi-tab safe)\n * const driver = new WaSqliteDriver('myapp.db');\n *\n * // For OPFS (faster, requires Worker, filesystem transparent)\n * const opfsDriver = new WaSqliteDriver('myapp.db', { vfs: 'OPFSCoopSyncVFS' });\n *\n * const adapter = new SQLiteAdapter('myapp', driver);\n * ```\n */\nexport class WaSqliteDriver implements SQLiteDatabaseDriver {\n readonly type = 'WaSqliteDriver';\n private db: number | null = null;\n private sqlite3: any = null;\n private readonly options: Required<WaSqliteDriverOptions>;\n private opened = false;\n private openPromise: Promise<void> | null = null;\n // Mutex to prevent concurrent database operations (critical for wa-sqlite)\n private executionLock: Promise<void> = Promise.resolve();\n readonly name: string;\n\n constructor(databaseName: string, options: WaSqliteDriverOptions = {}) {\n this.name = databaseName;\n this.options = {\n vfs: 'IDBBatchAtomicVFS',\n directory: '/',\n pageSize: 4096,\n cacheSize: -2000,\n wal: false,\n synchronous: 'full',\n ...options,\n };\n }\n\n /**\n * Execute a callback with exclusive database access.\n * This prevents concurrent operations which can corrupt the database.\n */\n private async withLock<T>(fn: () => Promise<T>): Promise<T> {\n // Chain onto the existing lock\n const previousLock = this.executionLock;\n let releaseLock: () => void;\n this.executionLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n try {\n // Wait for previous operation to complete\n await previousLock;\n // Execute our operation\n return await fn();\n } finally {\n // Release the lock\n releaseLock!();\n }\n }\n\n async open(): Promise<void> {\n if (this.opened) return;\n if (this.openPromise) return this.openPromise;\n\n this.openPromise = this._open();\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n private async _open(): Promise<void> {\n // Load wa-sqlite module (asyncify build for async VFS support)\n const module = await this.loadWasmModule();\n\n // Create SQLite API from module (cached - must only create once per module)\n if (!cachedSqlite3) {\n const { Factory } = await import('@journeyapps/wa-sqlite');\n cachedSqlite3 = Factory(module);\n }\n this.sqlite3 = cachedSqlite3;\n\n // For IDB-based VFS, the VFS name is also used as the IndexedDB database name\n // Use a unique name based on database name to avoid conflicts\n const vfsName = `dync_${this.options.vfs}_${this.name}`.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n // Reuse existing VFS instance or create and register a new one\n let existingVfs = registeredVFS.get(vfsName);\n if (!existingVfs) {\n existingVfs = await this.createVFS(module, vfsName);\n // Register VFS with SQLite as default (like PowerSync does)\n this.sqlite3.vfs_register(existingVfs, true);\n registeredVFS.set(vfsName, existingVfs);\n }\n\n // Build database path - for IDB VFS, this is the \"file\" path within the VFS\n const dbPath = this.buildDatabasePath();\n\n // Open database (VFS is registered as default)\n this.db = await this.sqlite3.open_v2(dbPath);\n\n // Configure database pragmas for performance and durability\n await this.configurePragmas();\n\n this.opened = true;\n }\n\n private async loadWasmModule(): Promise<any> {\n if (!cachedModule) {\n if (!cachedModuleFactory) {\n // Dynamically import the asyncify build for async VFS support\n const wasmModule = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n cachedModuleFactory = wasmModule.default;\n }\n // Cache the module instance - all VFS and sqlite3 APIs must share the same module\n cachedModule = await cachedModuleFactory();\n }\n return cachedModule;\n }\n\n private async createVFS(module: any, vfsName: string): Promise<WaSqliteVFS> {\n const vfsType = this.options.vfs;\n let VFSClass: VFSClass;\n let vfsOptions: any = undefined;\n\n // Dynamically import VFS implementation\n // Note: We cast to unknown first because the package types don't include the static create method\n switch (vfsType) {\n case 'IDBBatchAtomicVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n VFSClass = mod.IDBBatchAtomicVFS as unknown as VFSClass;\n // Use exclusive lock policy like PowerSync does\n vfsOptions = { lockPolicy: 'exclusive' };\n break;\n }\n case 'IDBMirrorVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBMirrorVFS.js');\n VFSClass = mod.IDBMirrorVFS as unknown as VFSClass;\n break;\n }\n case 'OPFSCoopSyncVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n VFSClass = mod.OPFSCoopSyncVFS as unknown as VFSClass;\n break;\n }\n case 'AccessHandlePoolVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n VFSClass = mod.AccessHandlePoolVFS as unknown as VFSClass;\n break;\n }\n default:\n throw new Error(`Unsupported VFS type: ${vfsType}`);\n }\n\n return VFSClass.create(vfsName, module, vfsOptions);\n }\n\n private buildDatabasePath(): string {\n const vfsType = this.options.vfs;\n\n // For IDB-based VFS, use database name directly\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n return this.name;\n }\n\n // For OPFS-based VFS, build full path\n const directory = this.options.directory.replace(/\\/$/, '');\n return `${directory}/${this.name}`;\n }\n\n private async configurePragmas(): Promise<void> {\n if (!this.db || !this.sqlite3) return;\n\n // Page size can only be set on new/empty databases\n // For IDBBatchAtomicVFS, it cannot be changed after creation\n // Try to set it, but ignore errors if the database already exists\n try {\n await this.sqlite3.exec(this.db, `PRAGMA page_size = ${this.options.pageSize}`);\n } catch {\n // Page size already set, ignore\n }\n\n // Cache size for performance\n await this.sqlite3.exec(this.db, `PRAGMA cache_size = ${this.options.cacheSize}`);\n\n // WAL mode only for AccessHandlePoolVFS with exclusive locking\n if (this.options.wal && this.options.vfs === 'AccessHandlePoolVFS') {\n await this.sqlite3.exec(this.db, 'PRAGMA locking_mode = exclusive');\n await this.sqlite3.exec(this.db, 'PRAGMA journal_mode = WAL');\n }\n // Note: For IDB-based VFS, we don't set journal_mode - let the VFS handle it\n }\n\n async close(): Promise<void> {\n if (!this.opened || !this.db || !this.sqlite3) return;\n\n // Wait for any pending operations to complete by acquiring the lock\n await this.withLock(async () => {\n // Ensure all data is flushed before closing\n // This is critical for IDB-based VFS which batch writes\n try {\n await this.sqlite3!.exec(this.db!, 'PRAGMA wal_checkpoint(TRUNCATE)');\n } catch {\n // Ignore if WAL mode not enabled\n }\n\n await this.sqlite3!.close(this.db!);\n\n // Don't close the shared VFS - it may be used by other connections\n // The VFS will be cleaned up when all references are gone\n this.db = null;\n this.opened = false;\n });\n }\n\n async execute(statement: string): Promise<void> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n await this.withLock(async () => {\n await this.sqlite3.exec(this.db, statement);\n });\n }\n\n async run(statement: string, values: unknown[] = []): Promise<SQLiteRunResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Execute the statement\n await this.sqlite3.step(stmt);\n }\n\n return {\n changes: this.sqlite3.changes(this.db),\n lastId: Number(this.sqlite3.last_insert_id(this.db)),\n };\n });\n }\n\n /**\n * Convert values for SQLite compatibility.\n * - Booleans must be converted to integers (SQLite has no boolean type)\n */\n private convertValues(values: unknown[]): unknown[] {\n return values.map((value) => {\n if (typeof value === 'boolean') {\n return value ? 1 : 0;\n }\n return value;\n });\n }\n\n async query(statement: string, values: unknown[] = []): Promise<SQLiteQueryResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n const { SQLITE_ROW } = await import('@journeyapps/wa-sqlite');\n const allRows: unknown[][] = [];\n let columns: string[] = [];\n\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Get column names\n if (columns.length === 0) {\n columns = this.sqlite3.column_names(stmt);\n }\n\n // Fetch all rows\n while ((await this.sqlite3.step(stmt)) === SQLITE_ROW) {\n const row = this.sqlite3.row(stmt);\n allRows.push(row);\n }\n }\n\n return { columns, values: allRows };\n });\n }\n\n /**\n * Check if the database is currently open.\n */\n isOpen(): boolean {\n return this.opened;\n }\n\n /**\n * Get the VFS type being used by this driver.\n */\n getVfsType(): WaSqliteVfsType {\n return this.options.vfs;\n }\n\n /**\n * Delete the database.\n * This will close the database if open and remove all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this removes the files from OPFS.\n */\n async delete(): Promise<void> {\n // Close if open\n if (this.opened) {\n await this.close();\n }\n\n const vfsType = this.options.vfs;\n\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n // Delete IndexedDB database\n await new Promise<void>((resolve, reject) => {\n const request = indexedDB.deleteDatabase(this.name);\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error);\n request.onblocked = () => {\n console.warn(`Database deletion blocked for ${this.name}. Close all connections and try again.`);\n };\n });\n } else {\n // For OPFS-based VFS, remove the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to remove the file/directory\n const pathParts = dbPath.split('/').filter(Boolean);\n let current = root;\n\n // Navigate to parent directory\n for (let i = 0; i < pathParts.length - 1; i++) {\n current = await current.getDirectoryHandle(pathParts[i]!);\n }\n\n // Remove the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to remove associated journal/wal files\n const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];\n for (const file of associatedFiles) {\n try {\n await current.removeEntry(file, { recursive: false });\n } catch {\n // Ignore if file doesn't exist\n }\n }\n } catch (error) {\n // Ignore if directory doesn't exist\n if ((error as Error).name !== 'NotFoundError') {\n throw error;\n }\n }\n }\n }\n}\n"],"mappings":";AA6GA,IAAI,sBAAmD;AACvD,IAAI,eAAoB;AACxB,IAAI,gBAAqB;AAEzB,IAAM,gBAAgB,oBAAI,IAAyB;AAuC5C,IAAM,iBAAN,MAAqD;AAAA,EAC/C,OAAO;AAAA,EACR,KAAoB;AAAA,EACpB,UAAe;AAAA,EACN;AAAA,EACT,SAAS;AAAA,EACT,cAAoC;AAAA;AAAA,EAEpC,gBAA+B,QAAQ,QAAQ;AAAA,EAC9C;AAAA,EAET,YAAY,cAAsB,UAAiC,CAAC,GAAG;AACnE,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACX,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAU;AAAA,MACV,WAAW;AA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AAQ,GAAG,QAAQ,MAAM;AACpF,mBAAW,QAAQ,iBAAiB;AAChC,cAAI;AACA,kBAAM,QAAQ,YAAY,MAAM,EAAE,WAAW,MAAM,CAAC;AAAA,UACxD,QAAQ;AAAA,UAER;AAAA,QACJ;AAAA,MACJ,SAAS,OAAO;AAEZ,YAAK,MAAgB,SAAS,iBAAiB;AAC3C,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/storage/sqlite/drivers/WaSqliteDriver.ts"],"sourcesContent":["import type { SQLiteDatabaseDriver, SQLiteQueryResult, SQLiteRunResult } from '../types';\n\n/**\n * Virtual File System (VFS) options for wa-sqlite.\n * Each VFS has different trade-offs for performance, durability, and compatibility.\n *\n * @see https://github.com/rhashimoto/wa-sqlite/tree/master/src/examples#vfs-comparison\n */\nexport type WaSqliteVfsType =\n /**\n * IDBBatchAtomicVFS - IndexedDB-backed storage\n * - Works on ALL contexts (Window, Worker, SharedWorker, service worker)\n * - Supports multiple connections\n * - Full durability with batch atomic writes\n * - Good general-purpose choice for maximum compatibility\n * @recommended For apps that need to work in main thread and don't need OPFS\n */\n | 'IDBBatchAtomicVFS'\n /**\n * IDBMirrorVFS - IndexedDB with in-memory mirror\n * - Works on ALL contexts\n * - Supports multiple connections\n * - Much faster than IDBBatchAtomicVFS\n * - Database must fit in available memory\n * @recommended For small databases where performance is critical\n */\n | 'IDBMirrorVFS'\n /**\n * OPFSCoopSyncVFS - OPFS with cooperative synchronous access\n * - Requires Worker context\n * - Supports multiple connections\n * - Filesystem transparent (can import/export files)\n * - Good balance of performance and compatibility\n * @recommended For apps needing OPFS with multi-connection support\n */\n | 'OPFSCoopSyncVFS'\n /**\n * AccessHandlePoolVFS - OPFS-backed storage (fastest single connection)\n * - Requires Worker context\n * - Single connection only (no multi-tab support)\n * - Best performance, supports WAL mode\n * - NOT filesystem transparent\n * @recommended For single-tab apps where performance is critical\n */\n | 'AccessHandlePoolVFS';\n\n/**\n * Options for configuring the WaSqliteDriver.\n */\nexport interface WaSqliteDriverOptions {\n /**\n * Virtual File System to use for storage.\n * @default 'IDBBatchAtomicVFS'\n */\n vfs?: WaSqliteVfsType;\n\n /**\n * Directory path for the database in OPFS VFS modes.\n * Only used with OPFS-based VFS types.\n * @default '/'\n */\n directory?: string;\n\n /**\n * SQLite page size in bytes.\n * Larger pages can improve read performance for large BLOBs.\n * Cannot be changed after database creation for IDBBatchAtomicVFS/IDBMirrorVFS.\n * @default 4096\n */\n pageSize?: number;\n\n /**\n * SQLite cache size in pages (negative = KB, positive = pages).\n * Larger cache improves performance but uses more memory.\n * For IDBBatchAtomicVFS, must be large enough to hold journal for batch atomic mode.\n * @default -2000 (2MB)\n */\n cacheSize?: number;\n\n /**\n * Enable WAL (Write-Ahead Logging) mode.\n * Only supported with AccessHandlePoolVFS (with locking_mode=exclusive).\n * For other VFS types, this is ignored.\n * @default false\n */\n wal?: boolean;\n\n /**\n * Set synchronous pragma for durability vs performance trade-off.\n * - 'full': Maximum durability (default)\n * - 'normal': Relaxed durability, better performance (supported by IDBBatchAtomicVFS, IDBMirrorVFS, OPFSPermutedVFS)\n * - 'off': No sync, fastest but risks data loss on crash\n * @default 'full'\n */\n synchronous?: 'full' | 'normal' | 'off';\n}\n\n// Internal VFS interface for lifecycle management\ninterface WaSqliteVFS {\n close(): Promise<void>;\n name: string;\n}\n\n// VFS class type with static create method\ninterface VFSClass {\n create(name: string, module: any, options?: any): Promise<WaSqliteVFS>;\n}\n\n// Cached module factory and instance\nlet cachedModuleFactory: (() => Promise<any>) | null = null;\nlet cachedModule: any = null;\nlet cachedSqlite3: any = null;\n// Track VFS instances by name to avoid re-registering\nconst registeredVFS = new Map<string, WaSqliteVFS>();\n\n/**\n * SQLite driver for web browsers using wa-sqlite with IndexedDB or OPFS persistence.\n * Provides robust, persistent SQLite storage in the browser that prevents data loss.\n *\n * ## Data Safety Features\n *\n * - **IDBBatchAtomicVFS** (default): Uses IndexedDB batch atomic writes to ensure transactions\n * are either fully committed or not at all. Multi-tab safe.\n * - **IDBMirrorVFS**: IndexedDB with in-memory mirror. Much faster, database must fit in RAM.\n * - **OPFSCoopSyncVFS**: OPFS with cooperative sync. Multi-connection, filesystem transparent.\n * - **AccessHandlePoolVFS**: Uses OPFS Access Handles for high performance. Single-tab only.\n * - Full durability by default (`PRAGMA synchronous=full`)\n * - Automatic journal mode configuration for each VFS type\n *\n * ## VFS Selection Guide\n *\n * | VFS | Best For | Multi-Tab | Speed |\n * |-----|----------|-----------|-------|\n * | IDBBatchAtomicVFS | General use, main thread | ✅ | Good |\n * | IDBMirrorVFS | Small DBs, main thread | ✅ | Fast |\n * | OPFSCoopSyncVFS | Web Workers, file export | ✅ | Good |\n * | AccessHandlePoolVFS | Single-tab performance | ❌ | Fastest |\n *\n * @example\n * ```ts\n * import { WaSqliteDriver } from '@anfenn/dync/wa-sqlite';\n * import { SQLiteAdapter } from '@anfenn/dync';\n *\n * // Default: IDBBatchAtomicVFS (works in main thread, multi-tab safe)\n * const driver = new WaSqliteDriver('myapp.db');\n *\n * // For OPFS (faster, requires Worker, filesystem transparent)\n * const opfsDriver = new WaSqliteDriver('myapp.db', { vfs: 'OPFSCoopSyncVFS' });\n *\n * const adapter = new SQLiteAdapter('myapp', driver);\n * ```\n */\nexport class WaSqliteDriver implements SQLiteDatabaseDriver {\n readonly type = 'WaSqliteDriver';\n private db: number | null = null;\n private sqlite3: any = null;\n private readonly options: Required<WaSqliteDriverOptions>;\n private opened = false;\n private openPromise: Promise<void> | null = null;\n // Mutex to prevent concurrent database operations (critical for wa-sqlite)\n private executionLock: Promise<void> = Promise.resolve();\n readonly name: string;\n\n constructor(databaseName: string, options: WaSqliteDriverOptions = {}) {\n this.name = databaseName;\n this.options = {\n vfs: 'IDBBatchAtomicVFS',\n directory: '/',\n pageSize: 4096,\n cacheSize: -2000,\n wal: false,\n synchronous: 'full',\n ...options,\n };\n }\n\n /**\n * Execute a callback with exclusive database access.\n * This prevents concurrent operations which can corrupt the database.\n */\n private async withLock<T>(fn: () => Promise<T>): Promise<T> {\n // Chain onto the existing lock\n const previousLock = this.executionLock;\n let releaseLock: () => void;\n this.executionLock = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n\n try {\n // Wait for previous operation to complete\n await previousLock;\n // Execute our operation\n return await fn();\n } finally {\n // Release the lock\n releaseLock!();\n }\n }\n\n async open(): Promise<void> {\n if (this.opened) return;\n if (this.openPromise) return this.openPromise;\n\n this.openPromise = this._open();\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n private async _open(): Promise<void> {\n // Load wa-sqlite module (asyncify build for async VFS support)\n const module = await this.loadWasmModule();\n\n // Create SQLite API from module (cached - must only create once per module)\n if (!cachedSqlite3) {\n const { Factory } = await import('@journeyapps/wa-sqlite');\n cachedSqlite3 = Factory(module);\n }\n this.sqlite3 = cachedSqlite3;\n\n // For IDB-based VFS, the VFS name is also used as the IndexedDB database name\n // Use a unique name based on database name to avoid conflicts\n const vfsName = `dync_${this.options.vfs}_${this.name}`.replace(/[^a-zA-Z0-9_-]/g, '_');\n\n // Reuse existing VFS instance or create and register a new one\n let existingVfs = registeredVFS.get(vfsName);\n if (!existingVfs) {\n existingVfs = await this.createVFS(module, vfsName);\n // Register VFS with SQLite as default (like PowerSync does)\n this.sqlite3.vfs_register(existingVfs, true);\n registeredVFS.set(vfsName, existingVfs);\n }\n\n // Build database path - for IDB VFS, this is the \"file\" path within the VFS\n const dbPath = this.buildDatabasePath();\n\n // Open database (VFS is registered as default)\n this.db = await this.sqlite3.open_v2(dbPath);\n\n // Configure database pragmas for performance and durability\n await this.configurePragmas();\n\n this.opened = true;\n }\n\n private async loadWasmModule(): Promise<any> {\n if (!cachedModule) {\n if (!cachedModuleFactory) {\n // Dynamically import the asyncify build for async VFS support\n const wasmModule = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');\n cachedModuleFactory = wasmModule.default;\n }\n // Cache the module instance - all VFS and sqlite3 APIs must share the same module\n cachedModule = await cachedModuleFactory();\n }\n return cachedModule;\n }\n\n private async createVFS(module: any, vfsName: string): Promise<WaSqliteVFS> {\n const vfsType = this.options.vfs;\n let VFSClass: VFSClass;\n let vfsOptions: any = undefined;\n\n // Dynamically import VFS implementation\n // Note: We cast to unknown first because the package types don't include the static create method\n switch (vfsType) {\n case 'IDBBatchAtomicVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');\n VFSClass = mod.IDBBatchAtomicVFS as unknown as VFSClass;\n // Use exclusive lock policy like PowerSync does\n vfsOptions = { lockPolicy: 'exclusive' };\n break;\n }\n case 'IDBMirrorVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/IDBMirrorVFS.js');\n VFSClass = mod.IDBMirrorVFS as unknown as VFSClass;\n break;\n }\n case 'OPFSCoopSyncVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');\n VFSClass = mod.OPFSCoopSyncVFS as unknown as VFSClass;\n break;\n }\n case 'AccessHandlePoolVFS': {\n const mod = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');\n VFSClass = mod.AccessHandlePoolVFS as unknown as VFSClass;\n break;\n }\n default:\n throw new Error(`Unsupported VFS type: ${vfsType}`);\n }\n\n return VFSClass.create(vfsName, module, vfsOptions);\n }\n\n private buildDatabasePath(): string {\n const vfsType = this.options.vfs;\n\n // For IDB-based VFS, use database name directly\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n return this.name;\n }\n\n // For OPFS-based VFS, build full path\n const directory = this.options.directory.replace(/\\/$/, '');\n return `${directory}/${this.name}`;\n }\n\n private async configurePragmas(): Promise<void> {\n if (!this.db || !this.sqlite3) return;\n\n // Page size can only be set on new/empty databases\n // For IDBBatchAtomicVFS, it cannot be changed after creation\n // Try to set it, but ignore errors if the database already exists\n try {\n await this.sqlite3.exec(this.db, `PRAGMA page_size = ${this.options.pageSize}`);\n } catch {\n // Page size already set, ignore\n }\n\n // Cache size for performance\n await this.sqlite3.exec(this.db, `PRAGMA cache_size = ${this.options.cacheSize}`);\n\n // WAL mode only for AccessHandlePoolVFS with exclusive locking\n if (this.options.wal && this.options.vfs === 'AccessHandlePoolVFS') {\n await this.sqlite3.exec(this.db, 'PRAGMA locking_mode = exclusive');\n await this.sqlite3.exec(this.db, 'PRAGMA journal_mode = WAL');\n }\n // Note: For IDB-based VFS, we don't set journal_mode - let the VFS handle it\n }\n\n async close(): Promise<void> {\n if (!this.opened || !this.db || !this.sqlite3) return;\n\n // Wait for any pending operations to complete by acquiring the lock\n await this.withLock(async () => {\n // Ensure all data is flushed before closing\n // This is critical for IDB-based VFS which batch writes\n try {\n await this.sqlite3!.exec(this.db!, 'PRAGMA wal_checkpoint(TRUNCATE)');\n } catch {\n // Ignore if WAL mode not enabled\n }\n\n await this.sqlite3!.close(this.db!);\n\n // Don't close the shared VFS - it may be used by other connections\n // The VFS will be cleaned up when all references are gone\n this.db = null;\n this.opened = false;\n });\n }\n\n async execute(statement: string): Promise<void> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n await this.withLock(async () => {\n await this.sqlite3.exec(this.db, statement);\n });\n }\n\n async run(statement: string, values: unknown[] = []): Promise<SQLiteRunResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Execute the statement\n await this.sqlite3.step(stmt);\n }\n\n return {\n changes: this.sqlite3.changes(this.db),\n lastId: Number(this.sqlite3.last_insert_id(this.db)),\n };\n });\n }\n\n /**\n * Convert values for SQLite compatibility.\n * - Booleans must be converted to integers (SQLite has no boolean type)\n */\n private convertValues(values: unknown[]): unknown[] {\n return values.map((value) => {\n if (typeof value === 'boolean') {\n return value ? 1 : 0;\n }\n return value;\n });\n }\n\n async query(statement: string, values: unknown[] = []): Promise<SQLiteQueryResult> {\n await this.open();\n\n if (!this.db || !this.sqlite3) {\n throw new Error('Database not initialized');\n }\n\n return this.withLock(async () => {\n const { SQLITE_ROW } = await import('@journeyapps/wa-sqlite');\n const allRows: unknown[][] = [];\n let columns: string[] = [];\n\n // Convert values for SQLite (booleans -> integers)\n const convertedValues = this.convertValues(values);\n\n // Use statements() generator with proper binding\n for await (const stmt of this.sqlite3.statements(this.db, statement)) {\n if (stmt === null) {\n break;\n }\n\n // Reset statement before binding (critical for wa-sqlite)\n this.sqlite3.reset(stmt);\n\n // Bind parameters if any\n if (convertedValues.length > 0) {\n this.sqlite3.bind_collection(stmt, convertedValues);\n }\n\n // Get column names\n if (columns.length === 0) {\n columns = this.sqlite3.column_names(stmt);\n }\n\n // Fetch all rows\n while ((await this.sqlite3.step(stmt)) === SQLITE_ROW) {\n const row = this.sqlite3.row(stmt);\n allRows.push(row);\n }\n }\n\n return { columns, values: allRows };\n });\n }\n\n /**\n * Check if the database is currently open.\n */\n isOpen(): boolean {\n return this.opened;\n }\n\n /**\n * Get the VFS type being used by this driver.\n */\n getVfsType(): WaSqliteVfsType {\n return this.options.vfs;\n }\n\n /**\n * Delete the database.\n * This will close the database if open and delete all persisted data.\n * For IndexedDB-based VFS, this deletes the IndexedDB database.\n * For OPFS-based VFS, this deletes the files from OPFS.\n */\n async delete(): Promise<void> {\n // Close if open\n if (this.opened) {\n await this.close();\n }\n\n const vfsType = this.options.vfs;\n\n if (vfsType === 'IDBBatchAtomicVFS' || vfsType === 'IDBMirrorVFS') {\n // Delete IndexedDB database\n await new Promise<void>((resolve, reject) => {\n const request = indexedDB.deleteDatabase(this.name);\n request.onsuccess = () => resolve();\n request.onerror = () => reject(request.error);\n request.onblocked = () => {\n console.warn(`Database deletion blocked for ${this.name}. Close all connections and try again.`);\n };\n });\n } else {\n // For OPFS-based VFS, delete the directory\n const dbPath = this.buildDatabasePath();\n const root = await navigator.storage.getDirectory();\n\n try {\n // Try to delete the file/directory\n const pathParts = dbPath.split('/').filter(Boolean);\n let current = root;\n\n // Navigate to parent directory\n for (let i = 0; i < pathParts.length - 1; i++) {\n current = await current.getDirectoryHandle(pathParts[i]!);\n }\n\n // Delete the database file\n const filename = pathParts[pathParts.length - 1]!;\n await current.removeEntry(filename, { recursive: true });\n\n // Also try to delete associated journal/wal files\n const associatedFiles = [`${filename}-journal`, `${filename}-wal`, `${filename}-shm`];\n for (const file of associatedFiles) {\n try {\n await current.removeEntry(file, { recursive: false });\n } catch {\n // Ignore if file doesn't exist\n }\n }\n } catch (error) {\n // Ignore if directory doesn't exist\n if ((error as Error).name !== 'NotFoundError') {\n throw error;\n }\n }\n }\n }\n}\n"],"mappings":";AA6GA,IAAI,sBAAmD;AACvD,IAAI,eAAoB;AACxB,IAAI,gBAAqB;AAEzB,IAAM,gBAAgB,oBAAI,IAAyB;AAuC5C,IAAM,iBAAN,MAAqD;AAAA,EAC/C,OAAO;AAAA,EACR,KAAoB;AAAA,EACpB,UAAe;AAAA,EACN;AAAA,EACT,SAAS;AAAA,EACT,cAAoC;AAAA;AAAA,EAEpC,gBAA+B,QAAQ,QAAQ;AAAA,EAC9C;AAAA,EAET,YAAY,cAAsB,UAAiC,CAAC,GAAG;AACnE,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACX,KAAK;AAAA,MACL,WAAW;AAAA,MACX,UAAU;AAAA,MACV,WAAW;AAAA,MACX,KAAK;AAAA,MACL,aAAa;AAAA,MACb,GAAG;AAAA,IACP;AAAA,EACJ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAc,SAAY,IAAkC;AAExD,UAAM,eAAe,KAA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AER;AAAA,QACJ;AAAA,MACJ,SAAS,OAAO;AAEZ,YAAK,MAAgB,SAAS,iBAAiB;AAC3C,gBAAM;AAAA,QACV;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;","names":[]}
|
package/package.json
CHANGED
package/src/core/StateManager.ts
CHANGED
|
@@ -120,19 +120,19 @@ export class StateManager implements StateHelpers {
|
|
|
120
120
|
const action = change.action;
|
|
121
121
|
|
|
122
122
|
if (queueItem) {
|
|
123
|
-
if (queueItem.action === SyncAction.
|
|
123
|
+
if (queueItem.action === SyncAction.Delete) {
|
|
124
124
|
return Promise.resolve();
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
queueItem.version += 1;
|
|
128
128
|
|
|
129
|
-
if (action === SyncAction.
|
|
130
|
-
queueItem.action = SyncAction.
|
|
129
|
+
if (action === SyncAction.Delete) {
|
|
130
|
+
queueItem.action = SyncAction.Delete;
|
|
131
131
|
} else if (hasChanges) {
|
|
132
132
|
queueItem.changes = { ...queueItem.changes, ...omittedChanges };
|
|
133
133
|
queueItem.after = { ...queueItem.after, ...omittedAfter };
|
|
134
134
|
}
|
|
135
|
-
} else if (action === SyncAction.
|
|
135
|
+
} else if (action === SyncAction.Delete || hasChanges) {
|
|
136
136
|
next.pendingChanges = [...next.pendingChanges];
|
|
137
137
|
next.pendingChanges.push({
|
|
138
138
|
action,
|
|
@@ -162,7 +162,7 @@ async function processPullData(tableName: string, serverData: SyncedRecord[], si
|
|
|
162
162
|
const pendingRemovalById = new Set(
|
|
163
163
|
ctx.state
|
|
164
164
|
.getState()
|
|
165
|
-
.pendingChanges.filter((p) => p.tableName === tableName && p.action === SyncAction.
|
|
165
|
+
.pendingChanges.filter((p) => p.tableName === tableName && p.action === SyncAction.Delete)
|
|
166
166
|
.map((p) => p.id),
|
|
167
167
|
);
|
|
168
168
|
|
|
@@ -171,7 +171,7 @@ async function processPullData(tableName: string, serverData: SyncedRecord[], si
|
|
|
171
171
|
if (remoteUpdated > newest) newest = remoteUpdated;
|
|
172
172
|
|
|
173
173
|
if (pendingRemovalById.has(remote.id)) {
|
|
174
|
-
ctx.logger.debug(`[dync] pull:skip-pending-
|
|
174
|
+
ctx.logger.debug(`[dync] pull:skip-pending-delete tableName=${tableName} id=${remote.id}`);
|
|
175
175
|
continue;
|
|
176
176
|
}
|
|
177
177
|
|
|
@@ -180,7 +180,7 @@ async function processPullData(tableName: string, serverData: SyncedRecord[], si
|
|
|
180
180
|
if (remote.deleted) {
|
|
181
181
|
if (localItem) {
|
|
182
182
|
await txTable.raw.delete(localItem._localId);
|
|
183
|
-
ctx.logger.debug(`[dync] pull:
|
|
183
|
+
ctx.logger.debug(`[dync] pull:delete tableName=${tableName} id=${remote.id}`);
|
|
184
184
|
hasChanges = true;
|
|
185
185
|
}
|
|
186
186
|
continue;
|
|
@@ -22,9 +22,9 @@ export interface PushAllBatchContext extends PushContext {
|
|
|
22
22
|
batchSync: BatchSync;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
async function
|
|
25
|
+
async function handleDeleteSuccess(change: PendingChange, ctx: PushContext): Promise<void> {
|
|
26
26
|
const { tableName, localId, id } = change;
|
|
27
|
-
ctx.logger.debug(`[dync] push:
|
|
27
|
+
ctx.logger.debug(`[dync] push:delete:success tableName=${tableName} localId=${localId} id=${id}`);
|
|
28
28
|
await ctx.state.removePendingChange(localId, tableName);
|
|
29
29
|
}
|
|
30
30
|
|
|
@@ -49,9 +49,9 @@ async function handleCreateSuccess(change: PendingChange, serverResult: { id: un
|
|
|
49
49
|
if (wasChanged && ctx.state.samePendingVersion(tableName, localId, version)) {
|
|
50
50
|
await ctx.state.removePendingChange(localId, tableName);
|
|
51
51
|
} else {
|
|
52
|
-
const nextAction = wasChanged ? SyncAction.Update : SyncAction.
|
|
52
|
+
const nextAction = wasChanged ? SyncAction.Update : SyncAction.Delete;
|
|
53
53
|
await ctx.state.updatePendingChange(tableName, localId, nextAction, serverResult.id);
|
|
54
|
-
if (nextAction === SyncAction.
|
|
54
|
+
if (nextAction === SyncAction.Delete) return;
|
|
55
55
|
}
|
|
56
56
|
});
|
|
57
57
|
|
|
@@ -83,14 +83,14 @@ async function pushOne(change: PendingChange, ctx: PushAllContext): Promise<void
|
|
|
83
83
|
const { action, tableName, localId, id, changes, after } = change;
|
|
84
84
|
|
|
85
85
|
switch (action) {
|
|
86
|
-
case SyncAction.
|
|
86
|
+
case SyncAction.Delete:
|
|
87
87
|
if (!id) {
|
|
88
|
-
ctx.logger.warn(`[dync] push:
|
|
88
|
+
ctx.logger.warn(`[dync] push:delete:no-id tableName=${tableName} localId=${localId}`);
|
|
89
89
|
await ctx.state.removePendingChange(localId, tableName);
|
|
90
90
|
return;
|
|
91
91
|
}
|
|
92
|
-
await api.
|
|
93
|
-
await
|
|
92
|
+
await api.delete(id);
|
|
93
|
+
await handleDeleteSuccess(change, ctx);
|
|
94
94
|
break;
|
|
95
95
|
|
|
96
96
|
case SyncAction.Update: {
|
|
@@ -216,10 +216,10 @@ export async function pushAllBatch(ctx: PushAllBatchContext): Promise<Error | un
|
|
|
216
216
|
// Build batch payload
|
|
217
217
|
const payloads: BatchPushPayload[] = changesToPush.map((change) => ({
|
|
218
218
|
table: change.tableName,
|
|
219
|
-
action: change.action === SyncAction.Create ? 'add' : change.action === SyncAction.Update ? 'update' : '
|
|
219
|
+
action: change.action === SyncAction.Create ? 'add' : change.action === SyncAction.Update ? 'update' : 'delete',
|
|
220
220
|
localId: change.localId,
|
|
221
221
|
id: change.id,
|
|
222
|
-
data: change.action === SyncAction.
|
|
222
|
+
data: change.action === SyncAction.Delete ? undefined : change.changes,
|
|
223
223
|
}));
|
|
224
224
|
|
|
225
225
|
ctx.logger.debug(`[dync] push:batch:start count=${payloads.length}`);
|
|
@@ -270,12 +270,12 @@ async function processBatchPushResult(change: PendingChange, result: BatchPushRe
|
|
|
270
270
|
}
|
|
271
271
|
|
|
272
272
|
switch (action) {
|
|
273
|
-
case SyncAction.
|
|
274
|
-
|
|
273
|
+
case SyncAction.Delete:
|
|
274
|
+
await handleDeleteSuccess(change, ctx);
|
|
275
275
|
break;
|
|
276
276
|
|
|
277
277
|
case SyncAction.Update:
|
|
278
|
-
handleUpdateSuccess(change, ctx);
|
|
278
|
+
await handleUpdateSuccess(change, ctx);
|
|
279
279
|
break;
|
|
280
280
|
|
|
281
281
|
case SyncAction.Create: {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createLocalId } from '../helpers';
|
|
2
2
|
import { SyncAction, type MutationEvent, type SyncedRecord } from '../types';
|
|
3
|
-
import type { StorageTable } from '../storage/types';
|
|
3
|
+
import type { AddItem, StorageTable } from '../storage/types';
|
|
4
4
|
import { DYNC_STATE_TABLE, type StateHelpers } from './StateManager';
|
|
5
5
|
import type { WithTransaction } from './types';
|
|
6
6
|
export type EmitMutation = (event: MutationEvent) => void;
|
|
@@ -20,8 +20,8 @@ export function wrapWithMutationEmitter<T>(table: StorageTable<T>, tableName: st
|
|
|
20
20
|
const rawBulkDelete = table.raw.bulkDelete;
|
|
21
21
|
const rawClear = table.raw.clear;
|
|
22
22
|
|
|
23
|
-
table.add = async (item: T) => {
|
|
24
|
-
const result = await rawAdd(item);
|
|
23
|
+
table.add = async (item: AddItem<T>) => {
|
|
24
|
+
const result = await rawAdd(item as T);
|
|
25
25
|
emitMutation({ type: 'add', tableName, keys: [result] });
|
|
26
26
|
return result;
|
|
27
27
|
};
|
|
@@ -32,7 +32,7 @@ export function wrapWithMutationEmitter<T>(table: StorageTable<T>, tableName: st
|
|
|
32
32
|
return result;
|
|
33
33
|
};
|
|
34
34
|
|
|
35
|
-
table.update = async (key:
|
|
35
|
+
table.update = async (key: string, changes: Partial<T>) => {
|
|
36
36
|
const result = await rawUpdate(key, changes);
|
|
37
37
|
if (result > 0) {
|
|
38
38
|
emitMutation({ type: 'update', tableName, keys: [key] });
|
|
@@ -40,13 +40,13 @@ export function wrapWithMutationEmitter<T>(table: StorageTable<T>, tableName: st
|
|
|
40
40
|
return result;
|
|
41
41
|
};
|
|
42
42
|
|
|
43
|
-
table.delete = async (key:
|
|
43
|
+
table.delete = async (key: string) => {
|
|
44
44
|
await rawDelete(key);
|
|
45
45
|
emitMutation({ type: 'delete', tableName, keys: [key] });
|
|
46
46
|
};
|
|
47
47
|
|
|
48
|
-
table.bulkAdd = async (items: T[]) => {
|
|
49
|
-
const result = await rawBulkAdd(items);
|
|
48
|
+
table.bulkAdd = async (items: AddItem<T>[]) => {
|
|
49
|
+
const result = await rawBulkAdd(items as T[]);
|
|
50
50
|
if (items.length > 0) {
|
|
51
51
|
emitMutation({ type: 'add', tableName });
|
|
52
52
|
}
|
|
@@ -61,7 +61,7 @@ export function wrapWithMutationEmitter<T>(table: StorageTable<T>, tableName: st
|
|
|
61
61
|
return result;
|
|
62
62
|
};
|
|
63
63
|
|
|
64
|
-
table.bulkUpdate = async (keysAndChanges: Array<{ key:
|
|
64
|
+
table.bulkUpdate = async (keysAndChanges: Array<{ key: string; changes: Partial<T> }>) => {
|
|
65
65
|
const result = await rawBulkUpdate(keysAndChanges);
|
|
66
66
|
if (result > 0) {
|
|
67
67
|
emitMutation({ type: 'update', tableName, keys: keysAndChanges.map((kc) => kc.key) });
|
|
@@ -69,7 +69,7 @@ export function wrapWithMutationEmitter<T>(table: StorageTable<T>, tableName: st
|
|
|
69
69
|
return result;
|
|
70
70
|
};
|
|
71
71
|
|
|
72
|
-
table.bulkDelete = async (keys:
|
|
72
|
+
table.bulkDelete = async (keys: string[]) => {
|
|
73
73
|
await rawBulkDelete(keys);
|
|
74
74
|
if (keys.length > 0) {
|
|
75
75
|
emitMutation({ type: 'delete', tableName });
|
|
@@ -134,7 +134,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
134
134
|
updated_at: new Date().toISOString(),
|
|
135
135
|
};
|
|
136
136
|
|
|
137
|
-
let result
|
|
137
|
+
let result!: string;
|
|
138
138
|
await withTransaction('rw', [tableName, DYNC_STATE_TABLE], async () => {
|
|
139
139
|
result = await rawAdd(syncedItem);
|
|
140
140
|
|
|
@@ -162,7 +162,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
162
162
|
updated_at: new Date().toISOString(),
|
|
163
163
|
};
|
|
164
164
|
|
|
165
|
-
let result
|
|
165
|
+
let result!: string;
|
|
166
166
|
let isUpdate = false;
|
|
167
167
|
let existingRecord: any;
|
|
168
168
|
|
|
@@ -233,7 +233,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
233
233
|
if (record) {
|
|
234
234
|
deletedLocalId = record._localId;
|
|
235
235
|
await state.addPendingChange({
|
|
236
|
-
action: SyncAction.
|
|
236
|
+
action: SyncAction.Delete,
|
|
237
237
|
tableName,
|
|
238
238
|
localId: record._localId,
|
|
239
239
|
id: record.id,
|
|
@@ -248,8 +248,8 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
248
248
|
}
|
|
249
249
|
};
|
|
250
250
|
|
|
251
|
-
const wrappedBulkAdd = async (items: any[]) => {
|
|
252
|
-
if (items.length === 0) return;
|
|
251
|
+
const wrappedBulkAdd = async (items: any[]): Promise<string[]> => {
|
|
252
|
+
if (items.length === 0) return [];
|
|
253
253
|
|
|
254
254
|
const now = new Date().toISOString();
|
|
255
255
|
const syncedItems = items.map((item) => {
|
|
@@ -261,7 +261,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
261
261
|
};
|
|
262
262
|
});
|
|
263
263
|
|
|
264
|
-
let result
|
|
264
|
+
let result!: string[];
|
|
265
265
|
await withTransaction('rw', [tableName, DYNC_STATE_TABLE], async () => {
|
|
266
266
|
result = await rawBulkAdd(syncedItems);
|
|
267
267
|
|
|
@@ -281,8 +281,8 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
281
281
|
return result;
|
|
282
282
|
};
|
|
283
283
|
|
|
284
|
-
const wrappedBulkPut = async (items: any[]) => {
|
|
285
|
-
if (items.length === 0) return;
|
|
284
|
+
const wrappedBulkPut = async (items: any[]): Promise<string[]> => {
|
|
285
|
+
if (items.length === 0) return [];
|
|
286
286
|
|
|
287
287
|
const now = new Date().toISOString();
|
|
288
288
|
const syncedItems = items.map((item) => {
|
|
@@ -295,7 +295,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
295
295
|
});
|
|
296
296
|
const localIds = syncedItems.map((i) => i._localId);
|
|
297
297
|
|
|
298
|
-
let result
|
|
298
|
+
let result!: string[];
|
|
299
299
|
await withTransaction('rw', [tableName, DYNC_STATE_TABLE], async (tables) => {
|
|
300
300
|
const txTable = tables[tableName]!;
|
|
301
301
|
|
|
@@ -397,7 +397,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
397
397
|
if (record) {
|
|
398
398
|
deletedLocalIds.push(record._localId);
|
|
399
399
|
await state.addPendingChange({
|
|
400
|
-
action: SyncAction.
|
|
400
|
+
action: SyncAction.Delete,
|
|
401
401
|
tableName,
|
|
402
402
|
localId: record._localId,
|
|
403
403
|
id: record.id,
|
|
@@ -427,7 +427,7 @@ export function enhanceSyncTable<T>({ table, tableName, withTransaction, state,
|
|
|
427
427
|
if (record._localId) {
|
|
428
428
|
deletedLocalIds.push(record._localId);
|
|
429
429
|
await state.addPendingChange({
|
|
430
|
-
action: SyncAction.
|
|
430
|
+
action: SyncAction.Delete,
|
|
431
431
|
tableName,
|
|
432
432
|
localId: record._localId,
|
|
433
433
|
id: record.id,
|