@korajs/store 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/adapters/better-sqlite3.d.cts +1 -1
  2. package/dist/adapters/better-sqlite3.d.ts +1 -1
  3. package/dist/adapters/indexeddb.cjs +410 -17
  4. package/dist/adapters/indexeddb.cjs.map +1 -1
  5. package/dist/adapters/indexeddb.d.cts +23 -5
  6. package/dist/adapters/indexeddb.d.ts +23 -5
  7. package/dist/adapters/indexeddb.js +163 -18
  8. package/dist/adapters/indexeddb.js.map +1 -1
  9. package/dist/adapters/sqlite-wasm-shared-host.cjs +68 -0
  10. package/dist/adapters/sqlite-wasm-shared-host.cjs.map +1 -0
  11. package/dist/adapters/sqlite-wasm-shared-host.d.cts +2 -0
  12. package/dist/adapters/sqlite-wasm-shared-host.d.ts +2 -0
  13. package/dist/adapters/sqlite-wasm-shared-host.js +66 -0
  14. package/dist/adapters/sqlite-wasm-shared-host.js.map +1 -0
  15. package/dist/adapters/sqlite-wasm-worker.cjs +34 -5
  16. package/dist/adapters/sqlite-wasm-worker.cjs.map +1 -1
  17. package/dist/adapters/sqlite-wasm-worker.js +34 -5
  18. package/dist/adapters/sqlite-wasm-worker.js.map +1 -1
  19. package/dist/adapters/sqlite-wasm.cjs +249 -2
  20. package/dist/adapters/sqlite-wasm.cjs.map +1 -1
  21. package/dist/adapters/sqlite-wasm.d.cts +15 -3
  22. package/dist/adapters/sqlite-wasm.d.ts +15 -3
  23. package/dist/adapters/sqlite-wasm.js +2 -2
  24. package/dist/audit-trace-store-AM4EWQNZ.js +15 -0
  25. package/dist/backup-JN3LB4YT.js +14 -0
  26. package/dist/backup-JN3LB4YT.js.map +1 -0
  27. package/dist/chunk-56LL4XP6.js +205 -0
  28. package/dist/chunk-56LL4XP6.js.map +1 -0
  29. package/dist/chunk-6AHYGQQT.js +425 -0
  30. package/dist/chunk-6AHYGQQT.js.map +1 -0
  31. package/dist/chunk-7BPETY5Y.js +570 -0
  32. package/dist/chunk-7BPETY5Y.js.map +1 -0
  33. package/dist/chunk-AGN3CIPB.js +188 -0
  34. package/dist/chunk-AGN3CIPB.js.map +1 -0
  35. package/dist/chunk-EZSTD2XC.js +380 -0
  36. package/dist/chunk-EZSTD2XC.js.map +1 -0
  37. package/dist/chunk-MYSJN3DF.js +117 -0
  38. package/dist/chunk-MYSJN3DF.js.map +1 -0
  39. package/dist/{chunk-DXKLAQ6P.js → chunk-XO4LMPAH.js} +1 -1
  40. package/dist/chunk-XO4LMPAH.js.map +1 -0
  41. package/dist/export-audit-5GV6VRDZ.js +15 -0
  42. package/dist/export-audit-5GV6VRDZ.js.map +1 -0
  43. package/dist/index.cjs +2662 -577
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.cts +565 -187
  46. package/dist/index.d.ts +565 -187
  47. package/dist/index.js +1381 -739
  48. package/dist/index.js.map +1 -1
  49. package/dist/internal.cjs +789 -0
  50. package/dist/internal.cjs.map +1 -0
  51. package/dist/internal.d.cts +154 -0
  52. package/dist/internal.d.ts +154 -0
  53. package/dist/internal.js +48 -0
  54. package/dist/internal.js.map +1 -0
  55. package/dist/{sqlite-wasm-channel-46AOWNPM.js → sqlite-wasm-channel-HDDW6UBH.js} +2 -2
  56. package/dist/sqlite-wasm-channel-HDDW6UBH.js.map +1 -0
  57. package/dist/{sqlite-wasm-channel-Lakjuk2E.d.cts → sqlite-wasm-channel-I9y_jObg.d.cts} +1 -0
  58. package/dist/{sqlite-wasm-channel-Lakjuk2E.d.ts → sqlite-wasm-channel-I9y_jObg.d.ts} +1 -0
  59. package/dist/types-BMyHmwvn.d.ts +163 -0
  60. package/dist/types-CTr00g_d.d.cts +163 -0
  61. package/dist/types-DepnRDk_.d.cts +212 -0
  62. package/dist/types-DepnRDk_.d.ts +212 -0
  63. package/package.json +23 -2
  64. package/dist/chunk-DXKLAQ6P.js.map +0 -1
  65. package/dist/chunk-ZP5AXQ3Z.js +0 -179
  66. package/dist/chunk-ZP5AXQ3Z.js.map +0 -1
  67. package/dist/types-DF-KDSK1.d.cts +0 -106
  68. package/dist/types-DF-KDSK1.d.ts +0 -106
  69. /package/dist/{sqlite-wasm-channel-46AOWNPM.js.map → audit-trace-store-AM4EWQNZ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/sqlite-wasm-adapter.ts","../src/multi-tab/shared-worker-bridge.ts","../src/multi-tab/tab-storage.ts"],"sourcesContent":["import { generateFullDDL } from '@korajs/core'\nimport type { SchemaDefinition } from '@korajs/core'\nimport { AdapterError, StoreNotOpenError } from '../errors'\nimport { SharedWorkerClientBridge } from '../multi-tab/shared-worker-bridge'\nimport {\n\tFollowerBroadcastBridge,\n\tacquireTabStorageSession,\n\tisSharedWorkerStorageSupported,\n\tstartLeaderRpcRelay,\n} from '../multi-tab/tab-storage'\nimport type { MigrationPlan, StorageAdapter, Transaction } from '../types'\nimport { Mutex } from './sqlite-wasm-channel'\nimport type { WorkerBridge, WorkerRequest, WorkerResponse } from './sqlite-wasm-channel'\n\n/**\n * Options for creating a SqliteWasmAdapter.\n */\nexport interface SqliteWasmAdapterOptions {\n\t/**\n\t * Injected WorkerBridge for testing. If omitted, a WebWorkerBridge is created\n\t * in browser environments.\n\t */\n\tbridge?: WorkerBridge\n\n\t/**\n\t * Database name for persistence. Used as the OPFS file name or IDB key.\n\t */\n\tdbName?: string\n\n\t/**\n\t * URL to the sqlite-wasm-worker script. Required in browsers if no bridge is provided.\n\t */\n\tworkerUrl?: string | URL\n\n\t/** Timeout for worker / follower RPC responses. Defaults to 30000ms. */\n\tworkerResponseTimeoutMs?: number\n\n\t/**\n\t * Optional SharedWorker host script (`sqlite-wasm-shared-host`). When set and\n\t * {@link isSharedWorkerStorageSupported}, one DedicatedWorker per `dbName` is pooled per origin.\n\t * Requires `workerUrl` for the inner SQLite worker. Falls back to leader election when omitted.\n\t */\n\tsharedWorkerUrl?: string | URL\n}\n\n/**\n * SQLite WASM adapter that communicates with a SQLite instance through a WorkerBridge.\n *\n * In browsers, the bridge is backed by a Web Worker running SQLite WASM with OPFS persistence.\n * In Node.js tests, the bridge is backed by MockWorkerBridge wrapping better-sqlite3.\n *\n * @example\n * ```typescript\n * // Browser usage\n * const adapter = new SqliteWasmAdapter({ workerUrl: '/sqlite-wasm-worker.js' })\n *\n * // Test usage with MockWorkerBridge\n * import { MockWorkerBridge } from './sqlite-wasm-mock-bridge'\n * const adapter = new SqliteWasmAdapter({ bridge: new MockWorkerBridge() })\n * ```\n */\nexport class SqliteWasmAdapter implements StorageAdapter {\n\tprivate bridge: WorkerBridge | null = null\n\tprivate opened = false\n\tprivate readonly mutex = new Mutex()\n\tprivate readonly injectedBridge: WorkerBridge | undefined\n\tprivate readonly workerUrl: string | URL | undefined\n\tprivate readonly sharedWorkerUrl: string | URL | undefined\n\tprivate readonly workerResponseTimeoutMs: number\n\tprivate readonly dbName: string\n\tprivate tabSession: Awaited<ReturnType<typeof acquireTabStorageSession>> | null = null\n\tprivate sharedWorker: SharedWorker | null = null\n\n\tconstructor(options: SqliteWasmAdapterOptions = {}) {\n\t\tthis.injectedBridge = options.bridge\n\t\tthis.workerUrl = options.workerUrl\n\t\tthis.sharedWorkerUrl = options.sharedWorkerUrl\n\t\tthis.workerResponseTimeoutMs = options.workerResponseTimeoutMs ?? 30_000\n\t\tthis.dbName = options.dbName ?? 'kora-db'\n\t}\n\n\tasync open(schema: SchemaDefinition): Promise<void> {\n\t\tif (this.opened) return\n\n\t\tif (this.injectedBridge) {\n\t\t\tthis.bridge = this.injectedBridge\n\t\t} else if (this.sharedWorkerUrl && this.workerUrl && isSharedWorkerStorageSupported()) {\n\t\t\tconst workerUrlString =\n\t\t\t\ttypeof this.workerUrl === 'string' ? this.workerUrl : this.workerUrl.href\n\t\t\tconst sharedUrl =\n\t\t\t\ttypeof this.sharedWorkerUrl === 'string' ? this.sharedWorkerUrl : this.sharedWorkerUrl.href\n\t\t\tthis.sharedWorker = new SharedWorker(sharedUrl, { name: `kora-sw-${this.dbName}` })\n\t\t\tthis.bridge = new SharedWorkerClientBridge(this.sharedWorker, this.dbName, workerUrlString)\n\t\t} else if (this.workerUrl) {\n\t\t\tthis.tabSession = await acquireTabStorageSession(this.dbName)\n\t\t\tconst { WebWorkerBridge } = await import('./sqlite-wasm-channel')\n\n\t\t\tif (this.tabSession.role === 'leader') {\n\t\t\t\tconst workerBridge = new WebWorkerBridge(this.workerUrl, this.workerResponseTimeoutMs)\n\t\t\t\tthis.tabSession.stopRelay = startLeaderRpcRelay(this.tabSession.channelName, workerBridge)\n\t\t\t\tthis.bridge = workerBridge\n\t\t\t} else {\n\t\t\t\tthis.bridge = new FollowerBroadcastBridge(\n\t\t\t\t\tthis.tabSession.channelName,\n\t\t\t\t\tthis.workerResponseTimeoutMs,\n\t\t\t\t)\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new AdapterError(\n\t\t\t\t'SqliteWasmAdapter requires either a bridge (for testing) or a workerUrl (for browsers). ' +\n\t\t\t\t\t'Pass { bridge: new MockWorkerBridge() } for tests, or { workerUrl: \"/worker.js\" } for browsers.',\n\t\t\t)\n\t\t}\n\n\t\tconst ddlStatements = generateFullDDL(schema)\n\t\tconst response = await this.sendRequest({\n\t\t\tid: 0,\n\t\t\ttype: 'open',\n\t\t\tddlStatements,\n\t\t\tdbName: this.dbName,\n\t\t})\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Failed to open database: ${response.message}`, {\n\t\t\t\tcode: response.code,\n\t\t\t\tdbName: this.dbName,\n\t\t\t})\n\t\t}\n\t\tthis.opened = true\n\t}\n\n\tasync close(): Promise<void> {\n\t\tif (!this.bridge) return\n\n\t\ttry {\n\t\t\tawait this.sendRequest({ id: 0, type: 'close' })\n\t\t} finally {\n\t\t\tthis.tabSession?.stopRelay?.()\n\t\t\tif (this.tabSession?.releaseLock) {\n\t\t\t\tawait this.tabSession.releaseLock()\n\t\t\t}\n\t\t\tthis.tabSession = null\n\t\t\tthis.sharedWorker = null\n\t\t\tthis.bridge.terminate()\n\t\t\tthis.bridge = null\n\t\t\tthis.opened = false\n\t\t}\n\t}\n\n\tasync execute(sql: string, params?: unknown[]): Promise<void> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'execute', sql, params })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Execute failed: ${response.message}`, { sql, params })\n\t\t}\n\t}\n\n\tasync query<T>(sql: string, params?: unknown[]): Promise<T[]> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'query', sql, params })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Query failed: ${response.message}`, { sql, params })\n\t\t}\n\t\treturn (response.data as T[]) ?? []\n\t}\n\n\tasync transaction(fn: (tx: Transaction) => Promise<void>): Promise<void> {\n\t\tthis.guardOpen()\n\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tawait this.sendChecked({ id: 0, type: 'begin' }, 'BEGIN transaction')\n\n\t\t\tconst tx: Transaction = {\n\t\t\t\texecute: async (sql: string, params?: unknown[]): Promise<void> => {\n\t\t\t\t\tconst response = await this.sendRequest({ id: 0, type: 'execute', sql, params })\n\t\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t\tthrow new AdapterError(`Transaction execute failed: ${response.message}`, {\n\t\t\t\t\t\t\tsql,\n\t\t\t\t\t\t\tparams,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tquery: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {\n\t\t\t\t\tconst response = await this.sendRequest({ id: 0, type: 'query', sql, params })\n\t\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\t\tthrow new AdapterError(`Transaction query failed: ${response.message}`, { sql, params })\n\t\t\t\t\t}\n\t\t\t\t\treturn (response.data as T[]) ?? []\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tawait fn(tx)\n\t\t\tawait this.sendChecked({ id: 0, type: 'commit' }, 'COMMIT transaction')\n\t\t} catch (error) {\n\t\t\t// Attempt rollback, but don't mask the original error\n\t\t\ttry {\n\t\t\t\tawait this.sendRequest({ id: 0, type: 'rollback' })\n\t\t\t} catch {\n\t\t\t\t// Rollback failure is secondary to the original error\n\t\t\t}\n\t\t\tthrow error\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\tasync migrate(from: number, to: number, migration: MigrationPlan): Promise<void> {\n\t\tthis.guardOpen()\n\n\t\tconst release = await this.mutex.acquire()\n\t\ttry {\n\t\t\tawait this.sendChecked({ id: 0, type: 'begin' }, 'BEGIN migration')\n\n\t\t\tfor (const sql of migration.statements) {\n\t\t\t\tconst response = await this.sendRequest({ id: 0, type: 'execute', sql })\n\t\t\t\tif (response.type === 'error') {\n\t\t\t\t\tthrow new AdapterError(`Migration from v${from} to v${to} failed: ${response.message}`, {\n\t\t\t\t\t\tfrom,\n\t\t\t\t\t\tto,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait this.sendChecked({ id: 0, type: 'commit' }, 'COMMIT migration')\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait this.sendRequest({ id: 0, type: 'rollback' })\n\t\t\t} catch {\n\t\t\t\t// Rollback failure is secondary\n\t\t\t}\n\t\t\tif (error instanceof AdapterError) throw error\n\t\t\tthrow new AdapterError(\n\t\t\t\t`Migration from v${from} to v${to} failed: ${(error as Error).message}`,\n\t\t\t\t{ from, to },\n\t\t\t)\n\t\t} finally {\n\t\t\trelease()\n\t\t}\n\t}\n\n\t/**\n\t * Export the database as a Uint8Array (for IndexedDB persistence).\n\t * Only available when the database is open.\n\t */\n\tasync exportDatabase(): Promise<Uint8Array> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'export' })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Export failed: ${response.message}`)\n\t\t}\n\t\treturn response.data as Uint8Array\n\t}\n\n\t/**\n\t * Import a serialized database snapshot.\n\t */\n\tasync importDatabase(data: Uint8Array): Promise<void> {\n\t\tthis.guardOpen()\n\t\tconst response = await this.sendRequest({ id: 0, type: 'import', data })\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`Import failed: ${response.message}`)\n\t\t}\n\t}\n\n\tprivate guardOpen(): void {\n\t\tif (!this.opened || !this.bridge) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t}\n\n\tprivate async sendRequest(request: WorkerRequest): Promise<WorkerResponse> {\n\t\t// guardOpen() is always called before sendRequest, so bridge is guaranteed non-null\n\t\tconst bridge = this.bridge\n\t\tif (!bridge) {\n\t\t\tthrow new StoreNotOpenError()\n\t\t}\n\t\treturn bridge.send(request)\n\t}\n\n\tprivate async sendChecked(request: WorkerRequest, description: string): Promise<void> {\n\t\tconst response = await this.sendRequest(request)\n\t\tif (response.type === 'error') {\n\t\t\tthrow new AdapterError(`${description} failed: ${response.message}`)\n\t\t}\n\t}\n}\n","/// <reference lib=\"dom\" />\nimport type { WorkerBridge, WorkerRequest, WorkerResponse } from '../adapters/sqlite-wasm-channel'\nimport { WorkerTimeoutError } from '../errors'\n\nconst SW_REQUEST = 'kora-sw-request'\nconst SW_RESPONSE = 'kora-sw-response'\n\nexport interface SharedWorkerRpcRequest {\n\ttype: typeof SW_REQUEST\n\trequestId: string\n\tdbName: string\n\tworkerUrl: string\n\trequest: WorkerRequest\n}\n\nexport interface SharedWorkerRpcResponse {\n\ttype: typeof SW_RESPONSE\n\trequestId: string\n\tresponse: WorkerResponse\n}\n\n/**\n * Forwards {@link WorkerBridge} RPC to a SharedWorker that hosts one DedicatedWorker per `dbName`.\n * Pair with the bundled `sqlite-wasm-shared-host` worker script.\n */\nexport class SharedWorkerClientBridge implements WorkerBridge {\n\tprivate readonly port: MessagePort\n\tprivate readonly pending = new Map<\n\t\tstring,\n\t\t{ resolve: (r: WorkerResponse) => void; reject: (e: Error) => void }\n\t>()\n\tprivate readonly timeoutMs: number\n\tprivate terminated = false\n\n\tconstructor(\n\t\tsharedWorker: SharedWorker,\n\t\tprivate readonly dbName: string,\n\t\tprivate readonly workerUrl: string,\n\t\ttimeoutMs = 30000,\n\t) {\n\t\tthis.timeoutMs = timeoutMs\n\t\tthis.port = sharedWorker.port\n\t\tthis.port.start()\n\t\tthis.port.addEventListener('message', (event: MessageEvent<SharedWorkerRpcResponse>) => {\n\t\t\tconst data = event.data\n\t\t\tif (data?.type !== SW_RESPONSE) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst entry = this.pending.get(data.requestId)\n\t\t\tif (entry) {\n\t\t\t\tthis.pending.delete(data.requestId)\n\t\t\t\tentry.resolve(data.response)\n\t\t\t}\n\t\t})\n\t}\n\n\tasync send(request: WorkerRequest): Promise<WorkerResponse> {\n\t\tif (this.terminated) {\n\t\t\treturn {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'SharedWorker bridge terminated',\n\t\t\t\tcode: 'BRIDGE_TERMINATED',\n\t\t\t}\n\t\t}\n\n\t\tconst requestId = crypto.randomUUID()\n\t\tconst msg: SharedWorkerRpcRequest = {\n\t\t\ttype: SW_REQUEST,\n\t\t\trequestId,\n\t\t\tdbName: this.dbName,\n\t\t\tworkerUrl: this.workerUrl,\n\t\t\trequest,\n\t\t}\n\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(requestId)\n\t\t\t\treject(new WorkerTimeoutError(`shared-worker:${request.type}`, this.timeoutMs))\n\t\t\t}, this.timeoutMs)\n\n\t\t\tthis.pending.set(requestId, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tresolve(response)\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\treject(error)\n\t\t\t\t},\n\t\t\t})\n\n\t\t\tthis.port.postMessage(msg)\n\t\t})\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.port.close()\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tentry.reject(new Error('SharedWorker bridge terminated'))\n\t\t}\n\t\tthis.pending.clear()\n\t}\n}\n","/**\n * Multi-tab SQLite storage coordination via `navigator.locks` and `BroadcastChannel`.\n *\n * One tab holds the exclusive `kora-leader-${dbName}` lock and owns the SQLite worker.\n * Other tabs send worker RPC over a named broadcast channel.\n */\n\nimport type { WorkerBridge, WorkerRequest, WorkerResponse } from '../adapters/sqlite-wasm-channel'\nimport { WorkerTimeoutError } from '../errors'\n\nconst RPC_REQUEST = 'kora-worker-request'\nconst RPC_RESPONSE = 'kora-worker-response'\n\ninterface RpcRequestMessage {\n\ttype: typeof RPC_REQUEST\n\trequestId: string\n\trequest: WorkerRequest\n}\n\ninterface RpcResponseMessage {\n\ttype: typeof RPC_RESPONSE\n\trequestId: string\n\tresponse: WorkerResponse\n}\n\nexport type TabStorageRole = 'leader' | 'follower'\n\nexport interface TabStorageSession {\n\trole: TabStorageRole\n\tchannelName: string\n\t/** Leader only: release the navigator lock when closing the database. */\n\treleaseLock?: () => Promise<void>\n\t/** Leader only: stop the broadcast RPC relay. */\n\tstopRelay?: () => void\n}\n\n/**\n * Returns whether a SharedWorker could host a single SQLite WASM instance per origin.\n * Not implemented yet — use {@link isMultiTabStorageSupported} + leader election today.\n */\nexport function isSharedWorkerStorageSupported(): boolean {\n\treturn typeof globalThis !== 'undefined' && typeof SharedWorker !== 'undefined'\n}\n\n/**\n * Returns whether multi-tab coordination APIs exist in this runtime.\n */\nexport function isMultiTabStorageSupported(): boolean {\n\treturn (\n\t\ttypeof globalThis !== 'undefined' &&\n\t\ttypeof BroadcastChannel !== 'undefined' &&\n\t\ttypeof navigator !== 'undefined' &&\n\t\ttypeof navigator.locks?.request === 'function'\n\t)\n}\n\n/**\n * Resolve leader vs follower for a database name.\n * Without lock APIs, every instance is treated as leader (single-tab / Node).\n */\nexport async function acquireTabStorageSession(dbName: string): Promise<TabStorageSession> {\n\tconst channelName = `kora-storage-${dbName}`\n\n\tif (!isMultiTabStorageSupported()) {\n\t\treturn { role: 'leader', channelName }\n\t}\n\n\treturn new Promise<TabStorageSession>((resolve) => {\n\t\tlet releaseHeld: (() => void) | undefined\n\n\t\tvoid navigator.locks.request(\n\t\t\t`kora-leader-${dbName}`,\n\t\t\t{ mode: 'exclusive', ifAvailable: true },\n\t\t\t(lock) => {\n\t\t\t\tif (lock === null) {\n\t\t\t\t\tresolve({ role: 'follower', channelName })\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tresolve({\n\t\t\t\t\trole: 'leader',\n\t\t\t\t\tchannelName,\n\t\t\t\t\treleaseLock: async () => {\n\t\t\t\t\t\treleaseHeld?.()\n\t\t\t\t\t},\n\t\t\t\t})\n\n\t\t\t\treturn new Promise<void>((release) => {\n\t\t\t\t\treleaseHeld = release\n\t\t\t\t})\n\t\t\t},\n\t\t)\n\t})\n}\n\n/**\n * Leader tab: forward follower RPC to the real worker bridge.\n */\nexport function startLeaderRpcRelay(channelName: string, bridge: WorkerBridge): () => void {\n\tconst channel = new BroadcastChannel(channelName)\n\n\tconst onMessage = (event: MessageEvent<RpcRequestMessage>): void => {\n\t\tconst data = event.data\n\t\tif (data?.type !== RPC_REQUEST) {\n\t\t\treturn\n\t\t}\n\n\t\tvoid bridge\n\t\t\t.send(data.request)\n\t\t\t.then((response) => {\n\t\t\t\tconst msg: RpcResponseMessage = {\n\t\t\t\t\ttype: RPC_RESPONSE,\n\t\t\t\t\trequestId: data.requestId,\n\t\t\t\t\tresponse,\n\t\t\t\t}\n\t\t\t\tchannel.postMessage(msg)\n\t\t\t})\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tconst message = error instanceof Error ? error.message : 'Worker RPC failed'\n\t\t\t\tconst msg: RpcResponseMessage = {\n\t\t\t\t\ttype: RPC_RESPONSE,\n\t\t\t\t\trequestId: data.requestId,\n\t\t\t\t\tresponse: {\n\t\t\t\t\t\tid: data.request.id,\n\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tcode: 'LEADER_RPC_ERROR',\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tchannel.postMessage(msg)\n\t\t\t})\n\t}\n\n\tchannel.addEventListener('message', onMessage)\n\treturn () => {\n\t\tchannel.removeEventListener('message', onMessage)\n\t\tchannel.close()\n\t}\n}\n\n/**\n * Follower tab: proxy {@link WorkerBridge} over BroadcastChannel to the leader.\n */\nexport class FollowerBroadcastBridge implements WorkerBridge {\n\tprivate readonly channel: BroadcastChannel\n\tprivate readonly pending = new Map<\n\t\tstring,\n\t\t{ resolve: (r: WorkerResponse) => void; reject: (e: Error) => void }\n\t>()\n\tprivate readonly timeoutMs: number\n\tprivate terminated = false\n\n\tconstructor(channelName: string, timeoutMs = 30000) {\n\t\tthis.timeoutMs = timeoutMs\n\t\tthis.channel = new BroadcastChannel(channelName)\n\t\tthis.channel.addEventListener('message', (event: MessageEvent<RpcResponseMessage>) => {\n\t\t\tconst data = event.data\n\t\t\tif (data?.type !== RPC_RESPONSE) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst entry = this.pending.get(data.requestId)\n\t\t\tif (entry) {\n\t\t\t\tthis.pending.delete(data.requestId)\n\t\t\t\tentry.resolve(data.response)\n\t\t\t}\n\t\t})\n\t}\n\n\tasync send(request: WorkerRequest): Promise<WorkerResponse> {\n\t\tif (this.terminated) {\n\t\t\treturn {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'Follower bridge terminated',\n\t\t\t\tcode: 'BRIDGE_TERMINATED',\n\t\t\t}\n\t\t}\n\n\t\tconst requestId = crypto.randomUUID()\n\t\tconst msg: RpcRequestMessage = { type: RPC_REQUEST, requestId, request }\n\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(requestId)\n\t\t\t\treject(new WorkerTimeoutError(`follower-rpc:${request.type}`, this.timeoutMs))\n\t\t\t}, this.timeoutMs)\n\n\t\t\tthis.pending.set(requestId, {\n\t\t\t\tresolve: (response) => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\tresolve(response)\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t\treject(error)\n\t\t\t\t},\n\t\t\t})\n\n\t\t\tthis.channel.postMessage(msg)\n\t\t})\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.channel.close()\n\t\tfor (const [, entry] of this.pending) {\n\t\t\tentry.reject(new Error('Follower bridge terminated'))\n\t\t}\n\t\tthis.pending.clear()\n\t}\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,uBAAuB;;;ACIhC,IAAM,aAAa;AACnB,IAAM,cAAc;AAoBb,IAAM,2BAAN,MAAuD;AAAA,EAS7D,YACC,cACiB,QACA,WACjB,YAAY,KACX;AAHgB;AACA;AAGjB,SAAK,YAAY;AACjB,SAAK,OAAO,aAAa;AACzB,SAAK,KAAK,MAAM;AAChB,SAAK,KAAK,iBAAiB,WAAW,CAAC,UAAiD;AACvF,YAAM,OAAO,MAAM;AACnB,UAAI,MAAM,SAAS,aAAa;AAC/B;AAAA,MACD;AACA,YAAM,QAAQ,KAAK,QAAQ,IAAI,KAAK,SAAS;AAC7C,UAAI,OAAO;AACV,aAAK,QAAQ,OAAO,KAAK,SAAS;AAClC,cAAM,QAAQ,KAAK,QAAQ;AAAA,MAC5B;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EAlBkB;AAAA,EACA;AAAA,EAXD;AAAA,EACA,UAAU,oBAAI,IAG7B;AAAA,EACe;AAAA,EACT,aAAa;AAAA,EAwBrB,MAAM,KAAK,SAAiD;AAC3D,QAAI,KA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iBAAsC;AAC3C,SAAK,UAAU;AACf,UAAM,WAAW,MAAM,KAAK,YAAY,EAAE,IAAI,GAAG,MAAM,SAAS,CAAC;AACjE,QAAI,SAAS,SAAS,SAAS;AAC9B,YAAM,IAAI,aAAa,kBAAkB,SAAS,OAAO,EAAE;AAAA,IAC5D;AACA,WAAO,SAAS;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,eAAe,MAAiC;AACrD,SAAK,UAAU;AACf,UAAM,WAAW,MAAM,KAAK,YAAY,EAAE,IAAI,GAAG,MAAM,UAAU,KAAK,CAAC;AACvE,QAAI,SAAS,SAAS,SAAS;AAC9B,YAAM,IAAI,aAAa,kBAAkB,SAAS,OAAO,EAAE;AAAA,IAC5D;AAAA,EACD;AAAA,EAEQ,YAAkB;AACzB,QAAI,CAAC,KAAK,UAAU,CAAC,KAAK,QAAQ;AACjC,YAAM,IAAI,kBAAkB;AAAA,IAC7B;AAAA,EACD;AAAA,EAEA,MAAc,YAAY,SAAiD;AAE1E,UAAM,SAAS,KAAK;AACpB,QAAI,CAAC,QAAQ;AACZ,YAAM,IAAI,kBAAkB;AAAA,IAC7B;AACA,WAAO,OAAO,KAAK,OAAO;AAAA,EAC3B;AAAA,EAEA,MAAc,YAAY,SAAwB,aAAoC;AACrF,UAAM,WAAW,MAAM,KAAK,YAAY,OAAO;AAC/C,QAAI,SAAS,SAAS,SAAS;AAC9B,YAAM,IAAI,aAAa,GAAG,WAAW,YAAY,SAAS,OAAO,EAAE;AAAA,IACpE;AAAA,EACD;AACD;","names":[]}
@@ -0,0 +1,570 @@
1
+ import {
2
+ QueryError,
3
+ RecordNotFoundError
4
+ } from "./chunk-LAWV6CFH.js";
5
+ import {
6
+ deserializeRecord,
7
+ serializeOperation,
8
+ serializeRecord
9
+ } from "./chunk-56LL4XP6.js";
10
+
11
+ // src/lww/row-version.ts
12
+ import { HybridLogicalClock } from "@korajs/core";
13
+ var EMPTY_ROW_VERSION = "";
14
+ function serializeRowVersion(timestamp) {
15
+ return HybridLogicalClock.serialize(timestamp);
16
+ }
17
+ function rowVersionFromRecord(row) {
18
+ const version = row._version;
19
+ if (typeof version === "string" && version.length > 0) {
20
+ return HybridLogicalClock.deserialize(version);
21
+ }
22
+ return { wallTime: row._updated_at, logical: 0, nodeId: "" };
23
+ }
24
+ function isIncomingNewerThanRow(incoming, row) {
25
+ return HybridLogicalClock.compare(incoming, rowVersionFromRecord(row)) > 0;
26
+ }
27
+ function lwwVersionWhereClause(remoteVersion) {
28
+ return {
29
+ sql: "(_version = ? OR _version < ?)",
30
+ params: [EMPTY_ROW_VERSION, remoteVersion]
31
+ };
32
+ }
33
+
34
+ // src/query/sql-builder.ts
35
+ function buildSelectQuery(descriptor, fields) {
36
+ const params = [];
37
+ const parts = [`SELECT * FROM ${descriptor.collection}`];
38
+ const whereClause = buildWhereClauseParts(descriptor.where, fields, params);
39
+ const deletedFilter = "_deleted = 0";
40
+ if (whereClause) {
41
+ parts.push(`WHERE ${deletedFilter} AND ${whereClause}`);
42
+ } else {
43
+ parts.push(`WHERE ${deletedFilter}`);
44
+ }
45
+ if (descriptor.orderBy.length > 0) {
46
+ const orderParts = descriptor.orderBy.map((o) => {
47
+ validateFieldName(o.field, fields);
48
+ return `${o.field} ${o.direction.toUpperCase()}`;
49
+ });
50
+ parts.push(`ORDER BY ${orderParts.join(", ")}`);
51
+ }
52
+ if (descriptor.limit !== void 0) {
53
+ parts.push(`LIMIT ${descriptor.limit}`);
54
+ }
55
+ if (descriptor.offset !== void 0) {
56
+ parts.push(`OFFSET ${descriptor.offset}`);
57
+ }
58
+ return { sql: parts.join(" "), params };
59
+ }
60
+ function buildCountQuery(descriptor, fields) {
61
+ const params = [];
62
+ const parts = [`SELECT COUNT(*) as count FROM ${descriptor.collection}`];
63
+ const whereClause = buildWhereClauseParts(descriptor.where, fields, params);
64
+ const deletedFilter = "_deleted = 0";
65
+ if (whereClause) {
66
+ parts.push(`WHERE ${deletedFilter} AND ${whereClause}`);
67
+ } else {
68
+ parts.push(`WHERE ${deletedFilter}`);
69
+ }
70
+ return { sql: parts.join(" "), params };
71
+ }
72
+ function buildInsertQuery(collection, record) {
73
+ const columns = Object.keys(record);
74
+ const placeholders = columns.map(() => "?");
75
+ const params = Object.values(record);
76
+ const sql = `INSERT INTO ${collection} (${columns.join(", ")}) VALUES (${placeholders.join(", ")})`;
77
+ return { sql, params };
78
+ }
79
+ function buildUpdateQuery(collection, id, changes) {
80
+ const setClauses = Object.keys(changes).map((col) => `${col} = ?`);
81
+ const params = [...Object.values(changes), id];
82
+ const sql = `UPDATE ${collection} SET ${setClauses.join(", ")} WHERE id = ?`;
83
+ return { sql, params };
84
+ }
85
+ function buildSoftDeleteQuery(collection, id, updatedAt, version) {
86
+ if (version !== void 0) {
87
+ return {
88
+ sql: `UPDATE ${collection} SET _deleted = 1, _updated_at = ?, _version = ? WHERE id = ?`,
89
+ params: [updatedAt, version, id]
90
+ };
91
+ }
92
+ return {
93
+ sql: `UPDATE ${collection} SET _deleted = 1, _updated_at = ? WHERE id = ?`,
94
+ params: [updatedAt, id]
95
+ };
96
+ }
97
+ function buildLwwUpdateQuery(collection, id, changes, remoteVersion) {
98
+ const setClauses = Object.keys(changes).map((col) => `${col} = ?`);
99
+ const lww = lwwVersionWhereClause(remoteVersion);
100
+ const sql = `UPDATE ${collection} SET ${setClauses.join(", ")} WHERE id = ? AND ${lww.sql}`;
101
+ const params = [...Object.values(changes), id, ...lww.params];
102
+ return { sql, params };
103
+ }
104
+ function buildLwwSoftDeleteQuery(collection, id, updatedAt, version) {
105
+ const lww = lwwVersionWhereClause(version);
106
+ return {
107
+ sql: `UPDATE ${collection} SET _deleted = 1, _updated_at = ?, _version = ? WHERE id = ? AND ${lww.sql}`,
108
+ params: [updatedAt, version, id, ...lww.params]
109
+ };
110
+ }
111
+ function buildWhereClause(where, fields) {
112
+ const params = [];
113
+ const result = buildWhereClauseParts(where, fields, params);
114
+ if (!result) return null;
115
+ return { sql: result, params };
116
+ }
117
+ var VALID_OPERATORS = /* @__PURE__ */ new Set(["$eq", "$ne", "$gt", "$gte", "$lt", "$lte", "$in"]);
118
+ function buildWhereClauseParts(where, fields, params) {
119
+ const conditions = [];
120
+ for (const [fieldName, value] of Object.entries(where)) {
121
+ validateFieldName(fieldName, fields);
122
+ const descriptor = fields[fieldName];
123
+ if (value !== null && typeof value === "object" && !Array.isArray(value)) {
124
+ const ops = value;
125
+ for (const [op, opValue] of Object.entries(ops)) {
126
+ if (!VALID_OPERATORS.has(op)) {
127
+ throw new QueryError(`Unknown operator "${op}" on field "${fieldName}"`, {
128
+ field: fieldName,
129
+ operator: op,
130
+ validOperators: [...VALID_OPERATORS]
131
+ });
132
+ }
133
+ conditions.push(buildOperatorCondition(fieldName, op, opValue, descriptor, params));
134
+ }
135
+ } else {
136
+ conditions.push(buildOperatorCondition(fieldName, "$eq", value, descriptor, params));
137
+ }
138
+ }
139
+ if (conditions.length === 0) return null;
140
+ return conditions.join(" AND ");
141
+ }
142
+ function buildOperatorCondition(fieldName, operator, value, descriptor, params) {
143
+ const sqlValue = descriptor?.kind === "boolean" && typeof value === "boolean" ? value ? 1 : 0 : value;
144
+ switch (operator) {
145
+ case "$eq":
146
+ if (sqlValue === null) {
147
+ return `${fieldName} IS NULL`;
148
+ }
149
+ params.push(sqlValue);
150
+ return `${fieldName} = ?`;
151
+ case "$ne":
152
+ if (sqlValue === null) {
153
+ return `${fieldName} IS NOT NULL`;
154
+ }
155
+ params.push(sqlValue);
156
+ return `${fieldName} != ?`;
157
+ case "$gt":
158
+ params.push(sqlValue);
159
+ return `${fieldName} > ?`;
160
+ case "$gte":
161
+ params.push(sqlValue);
162
+ return `${fieldName} >= ?`;
163
+ case "$lt":
164
+ params.push(sqlValue);
165
+ return `${fieldName} < ?`;
166
+ case "$lte":
167
+ params.push(sqlValue);
168
+ return `${fieldName} <= ?`;
169
+ case "$in": {
170
+ if (!Array.isArray(sqlValue)) {
171
+ throw new QueryError(`$in operator requires an array value for field "${fieldName}"`, {
172
+ field: fieldName,
173
+ received: typeof sqlValue
174
+ });
175
+ }
176
+ const placeholders = sqlValue.map(() => "?");
177
+ for (const item of sqlValue) {
178
+ params.push(
179
+ descriptor?.kind === "boolean" && typeof item === "boolean" ? item ? 1 : 0 : item
180
+ );
181
+ }
182
+ return `${fieldName} IN (${placeholders.join(", ")})`;
183
+ }
184
+ default:
185
+ throw new QueryError(`Unknown operator "${operator}"`, { operator });
186
+ }
187
+ }
188
+ function validateFieldName(fieldName, fields) {
189
+ const allowedFields = /* @__PURE__ */ new Set([
190
+ ...Object.keys(fields),
191
+ "id",
192
+ "createdAt",
193
+ "updatedAt",
194
+ "_created_at",
195
+ "_updated_at"
196
+ ]);
197
+ if (!allowedFields.has(fieldName)) {
198
+ throw new QueryError(
199
+ `Unknown field "${fieldName}" in query. Available fields: ${[...allowedFields].join(", ")}`,
200
+ { field: fieldName }
201
+ );
202
+ }
203
+ }
204
+
205
+ // src/mutations/resolve-causal-deps.ts
206
+ function resolveCausalDeps(ctx) {
207
+ const merged = [];
208
+ for (const id of ctx.extraCausalDeps ?? []) {
209
+ if (!merged.includes(id)) {
210
+ merged.push(id);
211
+ }
212
+ }
213
+ for (const id of ctx.causalTracker?.nextCausalDeps(ctx.collection, ctx.inTransaction) ?? []) {
214
+ if (!merged.includes(id)) {
215
+ merged.push(id);
216
+ }
217
+ }
218
+ return merged;
219
+ }
220
+
221
+ // src/mutations/execute-delete.ts
222
+ import { createOperation } from "@korajs/core";
223
+
224
+ // src/store/sequence-allocator.ts
225
+ async function allocateNextSequenceNumber(adapter, nodeId) {
226
+ const rows = await adapter.query(
227
+ `INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, 1)
228
+ ON CONFLICT(node_id) DO UPDATE SET sequence_number = sequence_number + 1
229
+ RETURNING sequence_number`,
230
+ [nodeId]
231
+ );
232
+ const seq = rows[0]?.sequence_number;
233
+ if (seq === void 0) {
234
+ throw new Error(`Failed to allocate sequence number for node "${nodeId}"`);
235
+ }
236
+ return seq;
237
+ }
238
+ async function allocateNextSequenceInTransaction(tx, nodeId) {
239
+ const rows = await tx.query(
240
+ `INSERT INTO _kora_version_vector (node_id, sequence_number) VALUES (?, 1)
241
+ ON CONFLICT(node_id) DO UPDATE SET sequence_number = sequence_number + 1
242
+ RETURNING sequence_number`,
243
+ [nodeId]
244
+ );
245
+ const seq = rows[0]?.sequence_number;
246
+ if (seq === void 0) {
247
+ throw new Error(`Failed to allocate sequence number for node "${nodeId}" in transaction`);
248
+ }
249
+ return seq;
250
+ }
251
+ async function readSequenceNumber(adapter, nodeId) {
252
+ const rows = await adapter.query(
253
+ "SELECT sequence_number FROM _kora_version_vector WHERE node_id = ?",
254
+ [nodeId]
255
+ );
256
+ return rows[0]?.sequence_number ?? 0;
257
+ }
258
+
259
+ // src/mutations/execute-delete.ts
260
+ async function executeDelete(ctx, id, options) {
261
+ const currentRows = await ctx.adapter.query(
262
+ `SELECT * FROM ${ctx.collection} WHERE id = ? AND _deleted = 0`,
263
+ [id]
264
+ );
265
+ if (!currentRows[0]) {
266
+ throw new RecordNotFoundError(ctx.collection, id);
267
+ }
268
+ const causalDeps = resolveCausalDeps(ctx);
269
+ let operation = options?.operation;
270
+ const cascadedOps = [];
271
+ await ctx.adapter.transaction(async (tx) => {
272
+ if (!operation) {
273
+ const sequenceNumber = await allocateNextSequenceInTransaction(tx, ctx.nodeId);
274
+ operation = await createOperation(
275
+ {
276
+ nodeId: ctx.nodeId,
277
+ type: "delete",
278
+ collection: ctx.collection,
279
+ recordId: id,
280
+ data: null,
281
+ previousData: null,
282
+ sequenceNumber,
283
+ causalDeps,
284
+ schemaVersion: ctx.schema.version
285
+ },
286
+ ctx.clock
287
+ );
288
+ ctx.causalTracker?.afterOperation(ctx.collection, operation.id, ctx.inTransaction);
289
+ }
290
+ if (ctx.relationEnforcer && !options?.skipReferentialEnforcement) {
291
+ const enforcementResult = await ctx.relationEnforcer.enforceDelete(ctx.collection, id, tx, [
292
+ operation.id
293
+ ]);
294
+ cascadedOps.push(...enforcementResult.operations);
295
+ }
296
+ const version = serializeRowVersion(operation.timestamp);
297
+ const deleteQuery = buildSoftDeleteQuery(
298
+ ctx.collection,
299
+ id,
300
+ operation.timestamp.wallTime,
301
+ version
302
+ );
303
+ const opInsert = buildInsertQuery(
304
+ `_kora_ops_${ctx.collection}`,
305
+ serializeOperation(operation)
306
+ );
307
+ await tx.execute(deleteQuery.sql, deleteQuery.params);
308
+ await tx.execute(opInsert.sql, opInsert.params);
309
+ });
310
+ if (!operation) {
311
+ throw new Error("Delete operation was not created");
312
+ }
313
+ ctx.onMutation(ctx.collection, operation);
314
+ for (const cascadedOp of cascadedOps) {
315
+ ctx.onMutation(cascadedOp.collection, cascadedOp);
316
+ }
317
+ return [operation, ...cascadedOps];
318
+ }
319
+
320
+ // src/mutations/execute-insert.ts
321
+ import { createOperation as createOperation2, generateUUIDv7, validateRecord } from "@korajs/core";
322
+ async function executeInsert(ctx, data) {
323
+ const validated = validateRecord(ctx.collection, ctx.definition, data, "insert");
324
+ const recordId = generateUUIDv7();
325
+ for (const [fieldName, descriptor] of Object.entries(ctx.definition.fields)) {
326
+ if (descriptor.auto && descriptor.kind === "timestamp") {
327
+ validated[fieldName] = Date.now();
328
+ }
329
+ }
330
+ const causalDeps = resolveCausalDeps(ctx);
331
+ let operation;
332
+ let record;
333
+ await ctx.adapter.transaction(async (tx) => {
334
+ const sequenceNumber = await allocateNextSequenceInTransaction(tx, ctx.nodeId);
335
+ operation = await createOperation2(
336
+ {
337
+ nodeId: ctx.nodeId,
338
+ type: "insert",
339
+ collection: ctx.collection,
340
+ recordId,
341
+ data: { ...validated },
342
+ previousData: null,
343
+ sequenceNumber,
344
+ causalDeps,
345
+ schemaVersion: ctx.schema.version
346
+ },
347
+ ctx.clock
348
+ );
349
+ ctx.causalTracker?.afterOperation(ctx.collection, operation.id, ctx.inTransaction);
350
+ const serializedData = serializeRecord(validated, ctx.definition.fields);
351
+ const version = serializeRowVersion(operation.timestamp);
352
+ record = {
353
+ id: recordId,
354
+ ...serializedData,
355
+ _created_at: operation.timestamp.wallTime,
356
+ _updated_at: operation.timestamp.wallTime,
357
+ _version: version
358
+ };
359
+ const builtInsert = buildInsertQuery(ctx.collection, record);
360
+ const opInsert = buildInsertQuery(
361
+ `_kora_ops_${ctx.collection}`,
362
+ serializeOperation(operation)
363
+ );
364
+ await tx.execute(builtInsert.sql, builtInsert.params);
365
+ await tx.execute(opInsert.sql, opInsert.params);
366
+ });
367
+ ctx.onMutation(ctx.collection, operation);
368
+ return {
369
+ id: recordId,
370
+ ...validated,
371
+ createdAt: operation.timestamp.wallTime,
372
+ updatedAt: operation.timestamp.wallTime
373
+ };
374
+ }
375
+
376
+ // src/state-machine/state-validator.ts
377
+ import { KoraError, validateTransition } from "@korajs/core";
378
+ var InvalidStateTransitionError = class extends KoraError {
379
+ constructor(collection, recordId, field, fromState, toState, allowedStates) {
380
+ super(
381
+ `Invalid state transition in collection "${collection}": cannot transition field "${field}" from "${fromState}" to "${toState}". Allowed transitions from "${fromState}": ${allowedStates.length > 0 ? allowedStates.join(", ") : "(none -- terminal state)"}`,
382
+ "INVALID_STATE_TRANSITION",
383
+ { collection, recordId, field, fromState, toState, allowedStates }
384
+ );
385
+ this.collection = collection;
386
+ this.recordId = recordId;
387
+ this.field = field;
388
+ this.fromState = fromState;
389
+ this.toState = toState;
390
+ this.allowedStates = allowedStates;
391
+ this.name = "InvalidStateTransitionError";
392
+ }
393
+ collection;
394
+ recordId;
395
+ field;
396
+ fromState;
397
+ toState;
398
+ allowedStates;
399
+ };
400
+ function validateStateTransition(collectionName, recordId, stateMachine, currentState, newState) {
401
+ if (currentState === null) {
402
+ return { valid: true, allowedStates: [] };
403
+ }
404
+ if (currentState === newState) {
405
+ return { valid: true, allowedStates: stateMachine.transitions[currentState] ?? [] };
406
+ }
407
+ const constraint = {
408
+ field: stateMachine.field,
409
+ collection: collectionName,
410
+ transitions: stateMachine.transitions
411
+ };
412
+ const transitionResult = validateTransition(constraint, currentState, newState);
413
+ if (transitionResult.valid) {
414
+ return { valid: true, allowedStates: transitionResult.allowedTargets };
415
+ }
416
+ const allowedStates = transitionResult.allowedTargets;
417
+ if (stateMachine.onInvalidTransition === "reject") {
418
+ throw new InvalidStateTransitionError(
419
+ collectionName,
420
+ recordId,
421
+ stateMachine.field,
422
+ currentState,
423
+ newState,
424
+ allowedStates
425
+ );
426
+ }
427
+ return { valid: false, allowedStates };
428
+ }
429
+ function validateUpdateStateMachine(collectionName, recordId, collectionDef, currentRecord, updateData) {
430
+ const stateMachine = collectionDef.stateMachine;
431
+ if (stateMachine === void 0) {
432
+ return updateData;
433
+ }
434
+ const stateField = stateMachine.field;
435
+ if (!(stateField in updateData)) {
436
+ return updateData;
437
+ }
438
+ const currentState = currentRecord[stateField];
439
+ const newState = updateData[stateField];
440
+ if (typeof currentState !== "string" || typeof newState !== "string") {
441
+ return updateData;
442
+ }
443
+ const result = validateStateTransition(
444
+ collectionName,
445
+ recordId,
446
+ stateMachine,
447
+ currentState,
448
+ newState
449
+ );
450
+ if (result.valid) {
451
+ return updateData;
452
+ }
453
+ const filtered = { ...updateData };
454
+ delete filtered[stateField];
455
+ return filtered;
456
+ }
457
+
458
+ // src/mutations/execute-update.ts
459
+ import {
460
+ createOperation as createOperation3,
461
+ isAtomicOp,
462
+ resolveAtomicOp,
463
+ toAtomicOp,
464
+ validateRecord as validateRecord2
465
+ } from "@korajs/core";
466
+ async function executeUpdate(ctx, id, data) {
467
+ const currentRows = await ctx.adapter.query(
468
+ `SELECT * FROM ${ctx.collection} WHERE id = ? AND _deleted = 0`,
469
+ [id]
470
+ );
471
+ const currentRow = currentRows[0];
472
+ if (!currentRow) {
473
+ throw new RecordNotFoundError(ctx.collection, id);
474
+ }
475
+ let validated = validateRecord2(ctx.collection, ctx.definition, data, "update");
476
+ const currentRecord = deserializeRecord(currentRow, ctx.definition.fields);
477
+ validated = validateUpdateStateMachine(
478
+ ctx.collection,
479
+ id,
480
+ ctx.definition,
481
+ currentRecord,
482
+ validated
483
+ );
484
+ if (Object.keys(validated).length === 0) {
485
+ return { ...currentRecord };
486
+ }
487
+ const previousData = {};
488
+ const resolvedData = {};
489
+ const atomicOps = {};
490
+ for (const key of Object.keys(validated)) {
491
+ const value = validated[key];
492
+ previousData[key] = currentRecord[key];
493
+ if (isAtomicOp(value)) {
494
+ resolvedData[key] = resolveAtomicOp(currentRecord[key], value);
495
+ atomicOps[key] = toAtomicOp(value);
496
+ } else {
497
+ resolvedData[key] = value;
498
+ }
499
+ }
500
+ const hasAtomicOps = Object.keys(atomicOps).length > 0;
501
+ const causalDeps = resolveCausalDeps(ctx);
502
+ let operation;
503
+ await ctx.adapter.transaction(async (tx) => {
504
+ const sequenceNumber = await allocateNextSequenceInTransaction(tx, ctx.nodeId);
505
+ operation = await createOperation3(
506
+ {
507
+ nodeId: ctx.nodeId,
508
+ type: "update",
509
+ collection: ctx.collection,
510
+ recordId: id,
511
+ data: { ...resolvedData },
512
+ previousData,
513
+ sequenceNumber,
514
+ causalDeps,
515
+ schemaVersion: ctx.schema.version,
516
+ ...hasAtomicOps ? { atomicOps } : {}
517
+ },
518
+ ctx.clock
519
+ );
520
+ ctx.causalTracker?.afterOperation(ctx.collection, operation.id, ctx.inTransaction);
521
+ const serializedChanges = serializeRecord(resolvedData, ctx.definition.fields);
522
+ const version = serializeRowVersion(operation.timestamp);
523
+ const updateQuery = buildUpdateQuery(ctx.collection, id, {
524
+ ...serializedChanges,
525
+ _updated_at: operation.timestamp.wallTime,
526
+ _version: version
527
+ });
528
+ const opInsert = buildInsertQuery(
529
+ `_kora_ops_${ctx.collection}`,
530
+ serializeOperation(operation)
531
+ );
532
+ await tx.execute(updateQuery.sql, updateQuery.params);
533
+ await tx.execute(opInsert.sql, opInsert.params);
534
+ });
535
+ ctx.onMutation(ctx.collection, operation);
536
+ const rows = await ctx.adapter.query(
537
+ `SELECT * FROM ${ctx.collection} WHERE id = ? AND _deleted = 0`,
538
+ [id]
539
+ );
540
+ const row = rows[0];
541
+ if (!row) {
542
+ throw new RecordNotFoundError(ctx.collection, id);
543
+ }
544
+ return deserializeRecord(row, ctx.definition.fields);
545
+ }
546
+
547
+ export {
548
+ serializeRowVersion,
549
+ rowVersionFromRecord,
550
+ isIncomingNewerThanRow,
551
+ buildSelectQuery,
552
+ buildCountQuery,
553
+ buildInsertQuery,
554
+ buildUpdateQuery,
555
+ buildSoftDeleteQuery,
556
+ buildLwwUpdateQuery,
557
+ buildLwwSoftDeleteQuery,
558
+ buildWhereClause,
559
+ allocateNextSequenceNumber,
560
+ allocateNextSequenceInTransaction,
561
+ readSequenceNumber,
562
+ resolveCausalDeps,
563
+ executeDelete,
564
+ executeInsert,
565
+ InvalidStateTransitionError,
566
+ validateStateTransition,
567
+ validateUpdateStateMachine,
568
+ executeUpdate
569
+ };
570
+ //# sourceMappingURL=chunk-7BPETY5Y.js.map