@tanstack/electric-db-collection 0.4.10 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"electric.js","sources":["../../src/electric.ts"],"sourcesContent":["import {\n ShapeStream,\n isChangeMessage,\n isControlMessage,\n isVisibleInSnapshot,\n} from '@electric-sql/client'\nimport DebugModule from 'debug'\nimport {\n DeduplicatedLoadSubset,\n LoadSubsetOperationAbortedError,\n and,\n withCollectionConfigFactory,\n withCollectionSyncConfigCleanup,\n withCollectionSyncConfigFactory,\n} from '@tanstack/db'\nimport {\n ExpectedNumberInAwaitTxIdError,\n StreamAbortedError,\n TimeoutWaitingForMatchError,\n TimeoutWaitingForTxIdError,\n} from './errors'\nimport { compileSQL } from './sql-compiler'\nimport {\n addTagToIndex,\n deriveDisjunctPositions,\n findRowsMatchingPattern,\n getTagLength,\n isMoveInMessage,\n isMoveOutMessage,\n parseTag as parseTagString,\n removeTagFromIndex,\n rowVisible,\n tagMatchesPattern,\n} from './tag-index'\nimport type { ColumnEncoder } from './sql-compiler'\nimport type {\n ActiveConditions,\n DisjunctPositions,\n MovePattern,\n MoveTag,\n ParsedMoveTag,\n RowId,\n TagIndex,\n} from './tag-index'\nimport type {\n BaseCollectionConfig,\n ChangeMessageOrDeleteKeyMessage,\n CollectionConfig,\n DeleteMutationFnParams,\n InsertMutationFnParams,\n LoadSubsetOptions,\n SyncAppliedReceipt,\n SyncConfig,\n SyncMetadataApi,\n SyncMode,\n UpdateMutationFnParams,\n UtilsRecord,\n} from '@tanstack/db'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type {\n ControlMessage,\n GetExtensions,\n Message,\n Offset,\n PostgresSnapshot,\n Row,\n ShapeStreamOptions,\n} from '@electric-sql/client'\n\ntype ElectricSyncMetadataWithHydration = SyncMetadataApi<string | number> & {\n row: SyncMetadataApi<string | number>[`row`] & {\n whenHydrated?: () => Promise<void>\n // Capability marker for wrappers predating the hydration barrier.\n scanPersisted?: unknown\n }\n}\n\n// Re-export for user convenience in custom match functions\nexport { isChangeMessage, isControlMessage } from '@electric-sql/client'\n\nconst debug = DebugModule.debug(`ts/db:electric`)\n\nconst FORCE_DISCONNECT_AND_REFRESH_TIMEOUT_MS = 250\n\n/**\n * Symbol for internal test hooks (hidden from public API)\n */\nexport const ELECTRIC_TEST_HOOKS = Symbol(`electricTestHooks`)\n\n/**\n * Internal test hooks interface (for testing only)\n */\nexport interface ElectricTestHooks {\n /**\n * Called before marking collection ready after first up-to-date in progressive mode\n * Allows tests to pause and validate snapshot phase before atomic swap completes\n */\n beforeMarkingReady?: () => Promise<void>\n}\n\n/**\n * Type representing a transaction ID in ElectricSQL\n */\nexport type Txid = number\n\ntype ElectricResumeState =\n | {\n kind: `resume`\n offset: string\n handle: string\n shapeId: string\n updatedAt: number\n requiresTagState?: boolean\n }\n | {\n kind: `reset`\n updatedAt: number\n }\n\ntype ElectricSyncMeta = {\n version: 1\n resume?: ElectricResumeState\n seenTxids: Array<Txid>\n}\n\ntype ElectricLifecycleEvidence = {\n seenTxids: Set<Txid>\n seenSnapshots: Array<PostgresSnapshot>\n hydratedResumeState?: ElectricResumeState\n}\n\ntype ElectricPendingMatch<T extends Row<unknown>> = {\n matchFn: (message: Message<T>) => boolean\n resolve: (value: boolean) => void\n reject: (error: Error) => void\n timeoutId: ReturnType<typeof setTimeout>\n matched: boolean\n}\n\ntype ElectricMatchBuffer<T extends Row<unknown>> = {\n committedMessages: Array<Message<T>>\n pendingMessages: Array<Message<T>>\n}\n\nfunction exportElectricSyncMeta(\n evidence: ElectricLifecycleEvidence,\n): ElectricSyncMeta {\n const resume = evidence.hydratedResumeState\n return {\n version: 1,\n ...(resume ? { resume } : {}),\n seenTxids: Array.from(evidence.seenTxids).sort((a, b) => a - b),\n }\n}\n\nfunction importElectricSyncMeta(\n evidence: ElectricLifecycleEvidence,\n meta: unknown,\n): void {\n const parsed = parseElectricSyncMeta(meta)\n if (!parsed) return\n\n evidence.hydratedResumeState = parsed.resume\n evidence.seenTxids = new Set(parsed.seenTxids)\n}\n\nfunction parseElectricResumeState(\n value: unknown,\n): ElectricResumeState | undefined {\n if (!value || typeof value !== `object`) {\n return undefined\n }\n\n const record = value as Record<string, unknown>\n if (\n record.kind === `resume` &&\n typeof record.offset === `string` &&\n typeof record.handle === `string` &&\n typeof record.shapeId === `string` &&\n typeof record.updatedAt === `number` &&\n Number.isFinite(record.updatedAt)\n ) {\n return {\n kind: `resume`,\n offset: record.offset,\n handle: record.handle,\n shapeId: record.shapeId,\n updatedAt: record.updatedAt,\n ...(typeof record.requiresTagState === `boolean` && {\n requiresTagState: record.requiresTagState,\n }),\n }\n }\n\n if (\n record.kind === `reset` &&\n typeof record.updatedAt === `number` &&\n Number.isFinite(record.updatedAt)\n ) {\n return {\n kind: `reset`,\n updatedAt: record.updatedAt,\n }\n }\n\n return undefined\n}\n\nfunction parseElectricSyncMeta(value: unknown): ElectricSyncMeta | undefined {\n if (!value || typeof value !== `object`) {\n return undefined\n }\n\n const record = value as Record<string, unknown>\n if (\n record.version !== 1 ||\n !Array.isArray(record.seenTxids) ||\n !record.seenTxids.every(\n (txid) => typeof txid === `number` && Number.isFinite(txid),\n )\n ) {\n return undefined\n }\n\n const resume =\n record.resume === undefined\n ? undefined\n : parseElectricResumeState(record.resume)\n if (record.resume !== undefined && resume === undefined) {\n return undefined\n }\n\n return {\n version: 1,\n ...(resume ? { resume } : {}),\n seenTxids: Array.from(new Set(record.seenTxids)).sort((a, b) => a - b),\n }\n}\n\nfunction mergeElectricSyncMeta(\n current: unknown,\n incoming: unknown,\n): ElectricSyncMeta | unknown {\n const currentMeta = parseElectricSyncMeta(current)\n const incomingMeta = parseElectricSyncMeta(incoming)\n\n if (!incomingMeta) {\n return current\n }\n if (!currentMeta) {\n return incomingMeta\n }\n\n const resume = getNewestElectricResumeState(\n currentMeta.resume,\n incomingMeta.resume,\n )\n\n return {\n version: 1,\n ...(resume ? { resume } : {}),\n seenTxids: Array.from(\n new Set([...currentMeta.seenTxids, ...incomingMeta.seenTxids]),\n ).sort((a, b) => a - b),\n }\n}\n\nfunction getNewestElectricResumeState(\n current: ElectricResumeState | undefined,\n incoming: ElectricResumeState | undefined,\n): ElectricResumeState | undefined {\n if (!current) return incoming\n if (!incoming) return current\n if (incoming.updatedAt > current.updatedAt) return incoming\n if (incoming.updatedAt < current.updatedAt) return current\n\n const isSameState =\n current.kind === incoming.kind &&\n (current.kind === `reset` ||\n (incoming.kind === `resume` &&\n current.offset === incoming.offset &&\n current.handle === incoming.handle &&\n current.shapeId === incoming.shapeId))\n\n // Equal timestamps have no causal ordering. Preserve an identical state,\n // but collapse every conflict to reset so merge order cannot resurrect an\n // offset that another source has already declared unsafe.\n return isSameState ? current : { kind: `reset`, updatedAt: current.updatedAt }\n}\n\n/**\n * Custom match function type - receives stream messages and returns boolean\n * indicating if the mutation has been synchronized\n */\nexport type MatchFunction<T extends Row<unknown>> = (\n message: Message<T>,\n) => boolean\n\n/**\n * Matching strategies for Electric synchronization\n * Handlers can return:\n * - Txid strategy: { txid: number | number[], timeout?: number } (recommended)\n * - Void (no return value) - mutation completes without waiting\n *\n * The optional timeout property specifies how long to wait for the txid(s) in milliseconds.\n * If not specified, defaults to 5000ms.\n */\nexport type MatchingStrategy = {\n txid: Txid | Array<Txid>\n timeout?: number\n} | void\n\n/**\n * Type representing a snapshot end message\n */\ntype SnapshotEndMessage = ControlMessage & {\n headers: { control: `snapshot-end` }\n}\n// The `InferSchemaOutput` and `ResolveType` are copied from the `@tanstack/db` package\n// but we modified `InferSchemaOutput` slightly to restrict the schema output to `Row<unknown>`\n// This is needed in order for `GetExtensions` to be able to infer the parser extensions type from the schema\ntype InferSchemaOutput<T> = T extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<T> extends Row<unknown>\n ? StandardSchemaV1.InferOutput<T>\n : Record<string, unknown>\n : Record<string, unknown>\n\n/**\n * The mode of sync to use for the collection.\n * @default `eager`\n * @description\n * - `eager`:\n * - syncs all data immediately on preload\n * - collection will be marked as ready once the sync is complete\n * - there is no incremental sync\n * - `on-demand`:\n * - syncs data in incremental snapshots when the collection is queried\n * - collection will be marked as ready immediately after the first snapshot is synced\n * - `progressive`:\n * - syncs all data for the collection in the background\n * - uses incremental snapshots during the initial sync to provide a fast path to the data required for queries\n * - collection will be marked as ready once the full sync is complete\n */\nexport type ElectricSyncMode = SyncMode | `progressive`\n\n/**\n * Configuration interface for Electric collection options\n * @template T - The type of items in the collection\n * @template TSchema - The schema type for validation\n */\nexport interface ElectricCollectionConfig<\n T extends Row<unknown> = Row<unknown>,\n TSchema extends StandardSchemaV1 = never,\n> extends Omit<\n BaseCollectionConfig<\n T,\n string | number,\n TSchema,\n ElectricCollectionUtils<T>,\n any\n >,\n `onInsert` | `onUpdate` | `onDelete` | `syncMode`\n> {\n /**\n * Configuration options for the ElectricSQL ShapeStream\n */\n shapeOptions: ShapeStreamOptions<GetExtensions<T>>\n syncMode?: ElectricSyncMode\n\n /**\n * Internal test hooks (for testing only)\n * Hidden via Symbol to prevent accidental usage in production\n */\n [ELECTRIC_TEST_HOOKS]?: ElectricTestHooks\n\n /**\n * Optional asynchronous handler function called before an insert operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to { txid, timeout? } or void\n * @example\n * // Basic Electric insert handler with txid (recommended)\n * onInsert: async ({ transaction }) => {\n * const newItem = transaction.mutations[0].modified\n * const result = await api.todos.create({\n * data: newItem\n * })\n * return { txid: result.txid }\n * }\n *\n * @example\n * // Insert handler with custom timeout\n * onInsert: async ({ transaction }) => {\n * const newItem = transaction.mutations[0].modified\n * const result = await api.todos.create({\n * data: newItem\n * })\n * return { txid: result.txid, timeout: 10000 } // Wait up to 10 seconds\n * }\n *\n * @example\n * // Insert handler with multiple items - return array of txids\n * onInsert: async ({ transaction }) => {\n * const items = transaction.mutations.map(m => m.modified)\n * const results = await Promise.all(\n * items.map(item => api.todos.create({ data: item }))\n * )\n * return { txid: results.map(r => r.txid) }\n * }\n *\n * @example\n * // Use awaitMatch utility for custom matching\n * onInsert: async ({ transaction, collection }) => {\n * const newItem = transaction.mutations[0].modified\n * await api.todos.create({ data: newItem })\n * await collection.utils.awaitMatch(\n * (message) => isChangeMessage(message) &&\n * message.headers.operation === 'insert' &&\n * message.value.name === newItem.name\n * )\n * }\n */\n onInsert?: (\n params: InsertMutationFnParams<\n T,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => Promise<MatchingStrategy>\n\n /**\n * Optional asynchronous handler function called before an update operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to { txid, timeout? } or void\n * @example\n * // Basic Electric update handler with txid (recommended)\n * onUpdate: async ({ transaction }) => {\n * const { original, changes } = transaction.mutations[0]\n * const result = await api.todos.update({\n * where: { id: original.id },\n * data: changes\n * })\n * return { txid: result.txid }\n * }\n *\n * @example\n * // Use awaitMatch utility for custom matching\n * onUpdate: async ({ transaction, collection }) => {\n * const { original, changes } = transaction.mutations[0]\n * await api.todos.update({ where: { id: original.id }, data: changes })\n * await collection.utils.awaitMatch(\n * (message) => isChangeMessage(message) &&\n * message.headers.operation === 'update' &&\n * message.value.id === original.id\n * )\n * }\n */\n onUpdate?: (\n params: UpdateMutationFnParams<\n T,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => Promise<MatchingStrategy>\n\n /**\n * Optional asynchronous handler function called before a delete operation\n * @param params Object containing transaction and collection information\n * @returns Promise resolving to { txid, timeout? } or void\n * @example\n * // Basic Electric delete handler with txid (recommended)\n * onDelete: async ({ transaction }) => {\n * const mutation = transaction.mutations[0]\n * const result = await api.todos.delete({\n * id: mutation.original.id\n * })\n * return { txid: result.txid }\n * }\n *\n * @example\n * // Use awaitMatch utility for custom matching\n * onDelete: async ({ transaction, collection }) => {\n * const mutation = transaction.mutations[0]\n * await api.todos.delete({ id: mutation.original.id })\n * await collection.utils.awaitMatch(\n * (message) => isChangeMessage(message) &&\n * message.headers.operation === 'delete' &&\n * message.value.id === mutation.original.id\n * )\n * }\n */\n onDelete?: (\n params: DeleteMutationFnParams<\n T,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => Promise<MatchingStrategy>\n}\n\nfunction isUpToDateMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is ControlMessage & { up_to_date: true } {\n return isControlMessage(message) && message.headers.control === `up-to-date`\n}\n\nfunction isMustRefetchMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is ControlMessage & { headers: { control: `must-refetch` } } {\n return isControlMessage(message) && message.headers.control === `must-refetch`\n}\n\nfunction isSnapshotEndMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is SnapshotEndMessage {\n return isControlMessage(message) && message.headers.control === `snapshot-end`\n}\n\nfunction isSubsetEndMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is ControlMessage & { headers: { control: `subset-end` } } {\n return (\n isControlMessage(message) &&\n (message.headers.control as string) === `subset-end`\n )\n}\n\nfunction parseSnapshotMessage(message: SnapshotEndMessage): PostgresSnapshot {\n return {\n xmin: message.headers.xmin,\n xmax: message.headers.xmax,\n xip_list: message.headers.xip_list,\n }\n}\n\nfunction toStableSerializable(value: unknown): unknown {\n if (value == null) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => toStableSerializable(entry))\n }\n\n if (value instanceof Date) {\n return value.toISOString()\n }\n\n if (typeof value === `object`) {\n const record = value as Record<string, unknown>\n const stableRecord: Record<string, unknown> = {}\n const keys = Object.keys(record).sort((left, right) =>\n left < right ? -1 : left > right ? 1 : 0,\n )\n for (const key of keys) {\n stableRecord[key] = toStableSerializable(record[key])\n }\n return stableRecord\n }\n\n return value\n}\n\nfunction getStableShapeIdentity(shapeOptions: {\n url: string\n params?: Record<string, unknown>\n}): string {\n return JSON.stringify(\n toStableSerializable({\n url: shapeOptions.url,\n params: shapeOptions.params ?? null,\n }),\n )\n}\n\n// Check if a message contains txids in its headers\nfunction hasTxids<T extends Row<unknown>>(\n message: Message<T>,\n): message is Message<T> & { headers: { txids?: Array<Txid> } } {\n return `txids` in message.headers && Array.isArray(message.headers.txids)\n}\n\n/**\n * Creates a deduplicated loadSubset handler for progressive/on-demand modes\n * Returns null for eager mode, or a DeduplicatedLoadSubset instance for other modes.\n * Handles fetching snapshots in progressive mode during buffering phase,\n * and requesting snapshots in on-demand mode.\n *\n * When cursor expressions are provided (whereFrom/whereCurrent), makes two\n * requestSnapshot calls:\n * - One for whereFrom (rows > cursor) with limit\n * - One for whereCurrent (rows = cursor, for tie-breaking) without limit\n */\nfunction createLoadSubsetDedupe<T extends Row<unknown>>({\n stream,\n syncMode,\n isBufferingInitialSync,\n begin,\n write,\n commit,\n getCommitCursor,\n waitForCommitsAfter,\n collectionId,\n encodeColumnName,\n signal,\n}: {\n stream: ShapeStream<T>\n syncMode: ElectricSyncMode\n isBufferingInitialSync: () => boolean\n begin: () => void\n write: (mutation: {\n type: `insert` | `update` | `delete`\n value: T\n metadata: Record<string, unknown>\n }) => void\n commit: (signal?: AbortSignal) => SyncAppliedReceipt\n getCommitCursor: () => number\n waitForCommitsAfter: (cursor: number) => Promise<void>\n collectionId?: string\n /**\n * Optional function to encode column names (e.g., camelCase to snake_case).\n * This is typically the `encode` function from shapeOptions.columnMapper.\n */\n encodeColumnName?: ColumnEncoder\n /**\n * Abort signal to check if the stream has been aborted during cleanup.\n * When aborted, errors from requestSnapshot are silently ignored.\n */\n signal: AbortSignal\n}): DeduplicatedLoadSubset | null {\n if (syncMode === `eager`) {\n return null\n }\n\n const compileOptions = encodeColumnName ? { encodeColumnName } : undefined\n const logPrefix = collectionId ? `[${collectionId}] ` : ``\n\n const abortReason = (abortedSignal: AbortSignal): unknown =>\n abortedSignal.reason ?? new LoadSubsetOperationAbortedError()\n\n /**\n * Handles errors from snapshot operations. Returns true if the error was\n * handled (signal aborted during cleanup), false if it should be re-thrown.\n */\n function handleSnapshotError(error: unknown, operation: string): boolean {\n if (signal.aborted) {\n debug(`${logPrefix}Ignoring ${operation} error during cleanup: %o`, error)\n return true\n }\n debug(`${logPrefix}Error in ${operation}: %o`, error)\n return false\n }\n\n const loadSubset = async (opts: LoadSubsetOptions) => {\n const commitCursor = getCommitCursor()\n const throwIfAborted = () => {\n if (signal.aborted) throw abortReason(signal)\n if (opts.signal?.aborted) throw abortReason(opts.signal)\n }\n throwIfAborted()\n\n if (isBufferingInitialSync()) {\n const snapshotParams = compileSQL<T>(opts, compileOptions)\n try {\n const { data: rows } = await stream.fetchSnapshot(snapshotParams)\n if (opts.signal?.aborted || !isBufferingInitialSync()) {\n debug(`${logPrefix}Ignoring snapshot - sync completed while fetching`)\n return\n }\n\n if (rows.length > 0) {\n begin()\n for (const row of rows) {\n write({\n type: `insert`,\n value: row.value,\n metadata: { ...row.headers },\n })\n }\n await commit(opts.signal)\n debug(`${logPrefix}Applied snapshot with ${rows.length} rows`)\n }\n } catch (error) {\n if (opts.signal?.aborted) return\n if (handleSnapshotError(error, `fetchSnapshot`)) {\n return\n }\n throw error\n }\n return\n }\n\n if (syncMode === `progressive`) {\n return\n }\n\n const { cursor, where, orderBy, limit } = opts\n\n // When the stream is already up-to-date, it may be in a long-poll wait.\n // Forcing a disconnect-and-refresh ensures requestSnapshot gets a response\n // from a fresh server round-trip rather than waiting for the current poll to end.\n // Some native fetch implementations (notably React Native/Expo) may not abort\n // long-poll requests promptly. Bound the wait so on-demand live queries don't\n // remain loading until the long-poll naturally times out.\n // If the refresh fails or times out, we fall through to requestSnapshot which\n // still works.\n if (stream.isUpToDate) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n const abortSignals = [signal, opts.signal].filter(\n (candidate): candidate is AbortSignal => candidate !== undefined,\n )\n let rejectAbort: (reason: unknown) => void = () => {}\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject\n })\n const abort = (event: Event) =>\n rejectAbort(abortReason(event.currentTarget as AbortSignal))\n for (const abortSignal of abortSignals) {\n abortSignal.addEventListener(`abort`, abort, { once: true })\n }\n try {\n await Promise.race([\n stream.forceDisconnectAndRefresh(),\n new Promise<void>((resolve) => {\n timeoutId = setTimeout(\n resolve,\n FORCE_DISCONNECT_AND_REFRESH_TIMEOUT_MS,\n )\n }),\n aborted,\n ])\n } catch (error) {\n if (signal.aborted || opts.signal?.aborted) throw error\n if (handleSnapshotError(error, `forceDisconnectAndRefresh`)) {\n return\n }\n debug(\n `${logPrefix}forceDisconnectAndRefresh failed, proceeding to requestSnapshot: %o`,\n error,\n )\n } finally {\n clearTimeout(timeoutId)\n for (const abortSignal of abortSignals) {\n abortSignal.removeEventListener(`abort`, abort)\n }\n }\n }\n\n throwIfAborted()\n\n // Upstream limitation: ShapeStream.requestSnapshot() publishes its rows\n // through the stream callback before its Promise resolves. It accepts no\n // request signal and exposes no request identity on those messages, so an\n // aborted request can already have installed rows before the check below.\n // Full request-scoped cancellation requires support in the Electric client;\n // matching snapshots by parameters is unsafe for overlapping equal requests.\n try {\n if (cursor) {\n const whereCurrentOpts: LoadSubsetOptions = {\n where: where ? and(where, cursor.whereCurrent) : cursor.whereCurrent,\n orderBy,\n }\n const whereCurrentParams = compileSQL<T>(\n whereCurrentOpts,\n compileOptions,\n )\n\n const whereFromOpts: LoadSubsetOptions = {\n where: where ? and(where, cursor.whereFrom) : cursor.whereFrom,\n orderBy,\n limit,\n }\n const whereFromParams = compileSQL<T>(whereFromOpts, compileOptions)\n\n debug(`${logPrefix}Requesting cursor.whereCurrent snapshot (all ties)`)\n debug(\n `${logPrefix}Requesting cursor.whereFrom snapshot (with limit ${limit})`,\n )\n\n await Promise.all([\n stream.requestSnapshot(whereCurrentParams),\n stream.requestSnapshot(whereFromParams),\n ])\n } else {\n const snapshotParams = compileSQL<T>(opts, compileOptions)\n await stream.requestSnapshot(snapshotParams)\n }\n } catch (error) {\n if (opts.signal?.aborted) return\n if (handleSnapshotError(error, `requestSnapshot`)) {\n return\n }\n throw error\n }\n await waitForCommitsAfter(commitCursor)\n }\n\n return new DeduplicatedLoadSubset({ loadSubset })\n}\n\n/**\n * Type for the awaitTxId utility function\n */\nexport type AwaitTxIdFn = (txId: Txid, timeout?: number) => Promise<boolean>\n\n/**\n * Type for the awaitMatch utility function\n */\nexport type AwaitMatchFn<T extends Row<unknown>> = (\n matchFn: MatchFunction<T>,\n timeout?: number,\n) => Promise<boolean>\n\n/**\n * Electric collection utilities type\n */\nexport interface ElectricCollectionUtils<\n T extends Row<unknown> = Row<unknown>,\n> extends UtilsRecord {\n awaitTxId: AwaitTxIdFn\n awaitMatch: AwaitMatchFn<T>\n}\n\n/** Owns evidence and pending work for one materialized Collection. */\nclass ElectricLifecycle<T extends Row<unknown>> {\n private readonly evidence: ElectricLifecycleEvidence = {\n seenTxids: new Set(),\n seenSnapshots: [],\n }\n\n private readonly pendingMatches = new Map<number, ElectricPendingMatch<T>>()\n private readonly pendingTxidWaits = new Map<\n number,\n {\n txId: Txid\n resolve: (value: boolean) => void\n reject: (error: Error) => void\n timeoutId: ReturnType<typeof setTimeout>\n }\n >()\n private matchBuffer: ElectricMatchBuffer<T> = {\n committedMessages: [],\n pendingMessages: [],\n }\n private nextWaiterId = 0\n private epoch = 0\n private active = false\n\n constructor(private readonly collectionId?: string) {}\n\n readonly utils: ElectricCollectionUtils<T> = {\n awaitTxId: (txId, timeout) => this.awaitTxId(txId, timeout),\n awaitMatch: (matchFn, timeout) => this.awaitMatch(matchFn, timeout),\n }\n\n start(): number {\n if (this.active) this.retire()\n this.active = true\n this.epoch++\n this.matchBuffer = { committedMessages: [], pendingMessages: [] }\n return this.epoch\n }\n\n isActive(epoch: number): boolean {\n return this.active && this.epoch === epoch\n }\n\n retire(epoch?: number): void {\n if (epoch !== undefined && !this.isActive(epoch)) return\n this.active = false\n this.epoch++\n\n for (const match of this.pendingMatches.values()) {\n clearTimeout(match.timeoutId)\n match.reject(new StreamAbortedError(this.collectionId))\n }\n this.pendingMatches.clear()\n\n for (const waiter of this.pendingTxidWaits.values()) {\n clearTimeout(waiter.timeoutId)\n waiter.reject(new StreamAbortedError(this.collectionId))\n }\n this.pendingTxidWaits.clear()\n this.matchBuffer = { committedMessages: [], pendingMessages: [] }\n this.evidence.hydratedResumeState = undefined\n }\n\n exportMeta(): ElectricSyncMeta {\n return exportElectricSyncMeta(this.evidence)\n }\n\n importMeta(meta: unknown): void {\n importElectricSyncMeta(this.evidence, meta)\n this.resolveTxidWaiters()\n }\n\n get resumeState(): ElectricResumeState | undefined {\n return this.evidence.hydratedResumeState\n }\n\n set resumeState(value: ElectricResumeState | undefined) {\n this.evidence.hydratedResumeState = value\n }\n\n publishEvidence(\n txids: ReadonlySet<Txid>,\n snapshots: ReadonlyArray<PostgresSnapshot>,\n ): void {\n txids.forEach((txid) => this.evidence.seenTxids.add(txid))\n this.evidence.seenSnapshots.push(...snapshots)\n this.resolveTxidWaiters()\n }\n\n private hasTxid(txId: Txid): boolean {\n return (\n this.evidence.seenTxids.has(txId) ||\n this.evidence.seenSnapshots.some((snapshot) =>\n isVisibleInSnapshot(txId, snapshot),\n )\n )\n }\n\n private resolveTxidWaiters(): void {\n for (const [waitId, waiter] of this.pendingTxidWaits) {\n if (!this.hasTxid(waiter.txId)) continue\n clearTimeout(waiter.timeoutId)\n this.pendingTxidWaits.delete(waitId)\n waiter.resolve(true)\n }\n }\n\n private async awaitTxId(\n txId: Txid,\n timeout: number = 5000,\n ): Promise<boolean> {\n debug(\n `${this.collectionId ? `[${this.collectionId}] ` : ``}awaitTxId called with txid %d`,\n txId,\n )\n if (typeof txId !== `number`) {\n throw new ExpectedNumberInAwaitTxIdError(typeof txId, this.collectionId)\n }\n if (this.hasTxid(txId)) return true\n\n return new Promise((resolve, reject) => {\n const waitId = this.nextWaiterId++\n const timeoutId = setTimeout(() => {\n this.pendingTxidWaits.delete(waitId)\n reject(new TimeoutWaitingForTxIdError(txId, this.collectionId))\n }, timeout)\n this.pendingTxidWaits.set(waitId, {\n txId,\n resolve,\n reject,\n timeoutId,\n })\n })\n }\n\n private async awaitMatch(\n matchFn: MatchFunction<T>,\n timeout: number = 3000,\n ): Promise<boolean> {\n debug(\n `${this.collectionId ? `[${this.collectionId}] ` : ``}awaitMatch called with custom function`,\n )\n\n for (const message of this.matchBuffer.committedMessages) {\n if (!matchFn(message)) continue\n return true\n }\n for (const message of this.matchBuffer.pendingMessages) {\n if (matchFn(message)) return this.registerMatch(matchFn, timeout, true)\n }\n return this.registerMatch(matchFn, timeout, false)\n }\n\n private registerMatch(\n matchFn: MatchFunction<T>,\n timeout: number,\n matched: boolean,\n ): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const matchId = this.nextWaiterId++\n const timeoutId = setTimeout(() => {\n this.pendingMatches.delete(matchId)\n reject(new TimeoutWaitingForMatchError(this.collectionId))\n }, timeout)\n this.pendingMatches.set(matchId, {\n matchFn,\n resolve,\n reject,\n timeoutId,\n matched,\n })\n })\n }\n\n beginMatchGeneration(messages: ReadonlyArray<Message<T>>): void {\n if (!messages.some(isMustRefetchMessage)) return\n this.matchBuffer = { committedMessages: [], pendingMessages: [] }\n for (const match of this.pendingMatches.values()) match.matched = false\n }\n\n observeMatchMessage(message: Message<T>): void {\n if (\n isChangeMessage(message) ||\n isMoveOutMessage(message) ||\n isMoveInMessage(message)\n ) {\n this.matchBuffer.pendingMessages.push(message)\n let overflow =\n this.matchBuffer.committedMessages.length +\n this.matchBuffer.pendingMessages.length -\n 1000\n if (overflow > 0) {\n const committedOverflow = Math.min(\n overflow,\n this.matchBuffer.committedMessages.length,\n )\n this.matchBuffer.committedMessages.splice(0, committedOverflow)\n overflow -= committedOverflow\n if (overflow > 0) {\n this.matchBuffer.pendingMessages.splice(0, overflow)\n }\n }\n }\n\n const epoch = this.epoch\n for (const [matchId, match] of this.pendingMatches) {\n if (match.matched) continue\n try {\n match.matched = match.matchFn(message)\n } catch (error) {\n clearTimeout(match.timeoutId)\n this.pendingMatches.delete(matchId)\n match.reject(error instanceof Error ? error : new Error(String(error)))\n }\n // Reentry can register replacement-session waiters in this same Map.\n if (!this.isActive(epoch)) return\n }\n }\n\n commitMatches(): void {\n this.matchBuffer.committedMessages.push(...this.matchBuffer.pendingMessages)\n this.matchBuffer.pendingMessages = []\n if (this.matchBuffer.committedMessages.length > 1000) {\n this.matchBuffer.committedMessages.splice(\n 0,\n this.matchBuffer.committedMessages.length - 1000,\n )\n }\n for (const [matchId, match] of this.pendingMatches) {\n if (!match.matched) continue\n clearTimeout(match.timeoutId)\n this.pendingMatches.delete(matchId)\n match.resolve(true)\n }\n }\n}\n\n/**\n * Creates Electric collection options for use with a standard Collection\n *\n * @template T - The explicit type of items in the collection (highest priority)\n * @template TSchema - The schema type for validation and type inference (second priority)\n * @template TFallback - The fallback type if no explicit or schema type is provided\n * @param config - Configuration options for the Electric collection\n * @returns Collection options with utilities\n */\n\n// Overload for when schema is provided\nexport function electricCollectionOptions<T extends StandardSchemaV1>(\n config: ElectricCollectionConfig<InferSchemaOutput<T>, T> & {\n schema: T\n },\n): Omit<\n CollectionConfig<InferSchemaOutput<T>, string | number, T>,\n `utils` | `onInsert` | `onUpdate` | `onDelete`\n> &\n Pick<\n ElectricCollectionConfig<InferSchemaOutput<T>, T>,\n `onInsert` | `onUpdate` | `onDelete`\n > & {\n id?: string\n utils: ElectricCollectionUtils<InferSchemaOutput<T>>\n schema: T\n }\n\n// Overload for when no schema is provided\nexport function electricCollectionOptions<T extends Row<unknown>>(\n config: ElectricCollectionConfig<T> & {\n schema?: never // prohibit schema\n },\n): Omit<\n CollectionConfig<T, string | number>,\n `utils` | `onInsert` | `onUpdate` | `onDelete`\n> &\n Pick<ElectricCollectionConfig<T>, `onInsert` | `onUpdate` | `onDelete`> & {\n id?: string\n utils: ElectricCollectionUtils<T>\n schema?: never // no schema in the result\n }\n\nexport function electricCollectionOptions<T extends Row<unknown>>(\n config: ElectricCollectionConfig<T, any>,\n): Omit<\n CollectionConfig<T, string | number, any, ElectricCollectionUtils<T>>,\n `utils`\n> & {\n id?: string\n utils: ElectricCollectionUtils<T>\n schema?: any\n} {\n let descriptorLifecycle = new ElectricLifecycle<T>(config.id)\n let utilityLifecycle = descriptorLifecycle\n const internalSyncMode = config.syncMode ?? `eager`\n const finalSyncMode =\n internalSyncMode === `progressive` ? `on-demand` : internalSyncMode\n const boundLifecycles = new WeakMap<object, ElectricLifecycle<T>>()\n const awaitTxId: AwaitTxIdFn = (txId, timeout) =>\n utilityLifecycle.utils.awaitTxId(txId, timeout)\n\n const awaitMatch: AwaitMatchFn<T> = (matchFn, timeout) =>\n utilityLifecycle.utils.awaitMatch(matchFn, timeout)\n\n const createSync = () =>\n createElectricSync<T>(config.shapeOptions, {\n getLifecycle: (collection) =>\n boundLifecycles.get(collection) ?? descriptorLifecycle,\n syncMode: internalSyncMode,\n collectionId: config.id,\n testHooks: config[ELECTRIC_TEST_HOOKS],\n })\n const sync = createSync()\n\n /**\n * Process matching strategy and wait for synchronization\n */\n const processMatchingStrategy = async (\n result: MatchingStrategy,\n waitForTxId: AwaitTxIdFn,\n ): Promise<void> => {\n // Only wait if result contains txid\n if (result && `txid` in result) {\n const timeout = result.timeout\n // Handle both single txid and array of txids\n if (Array.isArray(result.txid)) {\n await Promise.all(result.txid.map((txid) => waitForTxId(txid, timeout)))\n } else {\n await waitForTxId(result.txid, timeout)\n }\n }\n // If result is void/undefined, don't wait - mutation completes immediately\n }\n const getMutationAwaitTxId = (params: unknown): AwaitTxIdFn => {\n const collection = (\n params as {\n collection?: { utils?: { awaitTxId?: AwaitTxIdFn } }\n }\n ).collection\n return collection?.utils?.awaitTxId ?? awaitTxId\n }\n\n // Create wrapper handlers for direct persistence operations that handle different matching strategies\n const wrappedOnInsert = config.onInsert\n ? async (\n params: InsertMutationFnParams<\n any,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => {\n const handlerResult = await config.onInsert!(params)\n await processMatchingStrategy(\n handlerResult,\n getMutationAwaitTxId(params),\n )\n return handlerResult\n }\n : undefined\n\n const wrappedOnUpdate = config.onUpdate\n ? async (\n params: UpdateMutationFnParams<\n any,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => {\n const handlerResult = await config.onUpdate!(params)\n await processMatchingStrategy(\n handlerResult,\n getMutationAwaitTxId(params),\n )\n return handlerResult\n }\n : undefined\n\n const wrappedOnDelete = config.onDelete\n ? async (\n params: DeleteMutationFnParams<\n any,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => {\n const handlerResult = await config.onDelete!(params)\n await processMatchingStrategy(\n handlerResult,\n getMutationAwaitTxId(params),\n )\n return handlerResult\n }\n : undefined\n\n // Extract standard Collection config properties\n const {\n shapeOptions: _shapeOptions,\n onInsert: _onInsert,\n onUpdate: _onUpdate,\n onDelete: _onDelete,\n ...restConfig\n } = config\n\n const utilityTemplate: ElectricCollectionUtils<T> = {\n awaitTxId,\n awaitMatch,\n }\n const consumeDescriptorLifecycle = (): ElectricLifecycle<T> => {\n const lifecycle = descriptorLifecycle\n descriptorLifecycle = new ElectricLifecycle<T>(config.id)\n utilityLifecycle = lifecycle\n return lifecycle\n }\n const createBoundSync = (\n source: SyncConfig<T>,\n utilities: object,\n ): SyncConfig<T> => {\n const lifecycle = consumeDescriptorLifecycle()\n let collectionKey: object | undefined\n Object.assign(utilities, lifecycle.utils)\n\n const boundSync: SyncConfig<T> = {\n ...source,\n sync: (params) => {\n // A copied materialized config may delegate through an older binding.\n // The outermost binding owns this collection; inner wrappers only run\n // the source sync and must not retarget either owner's lifecycle.\n if (!boundLifecycles.has(params.collection)) {\n collectionKey = params.collection\n boundLifecycles.set(params.collection, lifecycle)\n }\n return source.sync(params)\n },\n exportSyncMeta: () => lifecycle.exportMeta(),\n importSyncMeta: (meta) => lifecycle.importMeta(meta),\n mergeSyncMeta: mergeElectricSyncMeta,\n }\n return withCollectionSyncConfigCleanup(boundSync, () => {\n lifecycle.retire()\n if (collectionKey) boundLifecycles.delete(collectionKey)\n })\n }\n const syncTemplate = withCollectionSyncConfigFactory(\n {\n ...sync,\n exportSyncMeta: () => descriptorLifecycle.exportMeta(),\n importSyncMeta: (meta) => descriptorLifecycle.importMeta(meta),\n mergeSyncMeta: mergeElectricSyncMeta,\n },\n createBoundSync,\n )\n const options = {\n ...restConfig,\n syncMode: finalSyncMode,\n sync: syncTemplate,\n onInsert: wrappedOnInsert,\n onUpdate: wrappedOnUpdate,\n onDelete: wrappedOnDelete,\n utils: utilityTemplate,\n }\n Object.defineProperty(options, `utils`, {\n enumerable: true,\n get: () => ({ ...utilityTemplate }),\n })\n\n return withCollectionConfigFactory(options, () =>\n (\n electricCollectionOptions as (\n nextConfig: ElectricCollectionConfig<T, any>,\n ) => typeof options\n )(config),\n )\n}\n\n/**\n * Internal function to create ElectricSQL sync configuration\n */\nfunction createElectricSync<T extends Row<unknown>>(\n shapeOptions: ShapeStreamOptions<GetExtensions<T>>,\n options: {\n syncMode: ElectricSyncMode\n getLifecycle: (collection: object) => ElectricLifecycle<T>\n collectionId?: string\n testHooks?: ElectricTestHooks\n },\n): SyncConfig<T> {\n const { getLifecycle, syncMode, collectionId, testHooks } = options\n\n let relationSchema: string | undefined\n let warnedUnverifiableResume = false\n\n const createTagState = () => {\n const tagCache = new Map<MoveTag, ParsedMoveTag>()\n\n // Parses a tag string into a ParsedMoveTag.\n // It memoizes the result parsed tag such that future calls\n // for the same tag string return the same ParsedMoveTag array.\n const parseTag = (tag: MoveTag): ParsedMoveTag => {\n const cachedTag = tagCache.get(tag)\n if (cachedTag) {\n return cachedTag\n }\n\n const parsedTag = parseTagString(tag)\n tagCache.set(tag, parsedTag)\n return parsedTag\n }\n\n // Tag tracking state\n const rowTagSets = new Map<RowId, Set<MoveTag>>()\n const tagIndex: TagIndex = []\n let tagLength: number | undefined = undefined\n\n // DNF state: active_conditions are per-row, disjunct_positions are global\n // (fixed by the shape's WHERE clause, derived once from the first tagged message).\n const rowActiveConditions = new Map<RowId, ActiveConditions>()\n let disjunctPositions: DisjunctPositions | undefined = undefined\n\n /**\n * Initialize the tag index with the correct length\n */\n const initializeTagIndex = (length: number): void => {\n if (tagIndex.length < length) {\n // Extend the index array to the required length\n for (let i = tagIndex.length; i < length; i++) {\n tagIndex[i] = new Map()\n }\n }\n }\n\n /**\n * Add tags to a row and update the tag index\n */\n const addTagsToRow = (\n tags: Array<MoveTag>,\n rowId: RowId,\n rowTagSet: Set<MoveTag>,\n ): void => {\n for (const tag of tags) {\n const parsedTag = parseTag(tag)\n\n // Infer tag length from first tag\n if (tagLength === undefined) {\n tagLength = getTagLength(parsedTag)\n initializeTagIndex(tagLength)\n }\n\n // Validate tag length matches\n const currentTagLength = getTagLength(parsedTag)\n if (currentTagLength !== tagLength) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Tag length mismatch: expected ${tagLength}, got ${currentTagLength}`,\n )\n continue\n }\n\n rowTagSet.add(tag)\n addTagToIndex(parsedTag, rowId, tagIndex, tagLength)\n }\n }\n\n /**\n * Remove tags from a row and update the tag index\n */\n const removeTagsFromRow = (\n removedTags: Array<MoveTag>,\n rowId: RowId,\n rowTagSet: Set<MoveTag>,\n ): void => {\n if (tagLength === undefined) {\n return\n }\n\n for (const tag of removedTags) {\n const parsedTag = parseTag(tag)\n rowTagSet.delete(tag)\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength)\n // We aggresively evict the tag from the cache\n // if this tag is shared with another row\n // and is not removed from that other row\n // then next time we encounter the tag it will be parsed again\n tagCache.delete(tag)\n }\n }\n\n /**\n * Process tags for a change message (add and remove tags)\n */\n const processTagsForChangeMessage = (\n tags: Array<MoveTag> | undefined,\n removedTags: Array<MoveTag> | undefined,\n rowId: RowId,\n activeConditions?: ActiveConditions,\n ): Set<MoveTag> => {\n // Initialize tag set for this row if it doesn't exist (needed for checking deletion)\n if (!rowTagSets.has(rowId)) {\n rowTagSets.set(rowId, new Set())\n }\n const rowTagSet = rowTagSets.get(rowId)!\n\n // Add new tags\n if (tags) {\n addTagsToRow(tags, rowId, rowTagSet)\n\n // Derive disjunct positions once — they are fixed by the shape's WHERE clause.\n if (disjunctPositions === undefined) {\n const parsedTags = tags.map(parseTag)\n disjunctPositions = deriveDisjunctPositions(parsedTags)\n }\n }\n\n // Remove tags\n if (removedTags) {\n removeTagsFromRow(removedTags, rowId, rowTagSet)\n }\n\n // Store active conditions if provided (overwrite on re-send)\n if (activeConditions && activeConditions.length > 0) {\n rowActiveConditions.set(rowId, [...activeConditions])\n }\n\n return rowTagSet\n }\n\n /**\n * Clear all tag tracking state (used when truncating)\n */\n const clearTagTrackingState = (): void => {\n rowTagSets.clear()\n tagIndex.length = 0\n tagLength = undefined\n rowActiveConditions.clear()\n disjunctPositions = undefined\n }\n\n /**\n * Remove all tags for a row from both the tag set and the index\n * Used when a row is deleted\n */\n const clearTagsForRow = (rowId: RowId): void => {\n if (tagLength === undefined) {\n return\n }\n\n const rowTagSet = rowTagSets.get(rowId)\n if (!rowTagSet) {\n return\n }\n\n // Remove each tag from the index\n for (const tag of rowTagSet) {\n const parsedTag = parseTag(tag)\n const currentTagLength = getTagLength(parsedTag)\n if (currentTagLength === tagLength) {\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength)\n }\n tagCache.delete(tag)\n }\n\n // Remove the row from the tag sets map\n rowTagSets.delete(rowId)\n rowActiveConditions.delete(rowId)\n }\n\n /**\n * Remove matching tags from a row based on a pattern\n * Returns true if the row should be deleted (no longer visible)\n */\n const removeMatchingTagsFromRow = (\n rowId: RowId,\n pattern: MovePattern,\n ): boolean => {\n const rowTagSet = rowTagSets.get(rowId)\n if (!rowTagSet) {\n return false\n }\n\n // DNF mode: check visibility using active conditions.\n // Tag index entries are preserved so that move-in can re-activate positions.\n const activeConditions = rowActiveConditions.get(rowId)\n if (activeConditions && disjunctPositions) {\n // Set the condition at this pattern's position to false\n activeConditions[pattern.pos] = false\n\n if (!rowVisible(activeConditions, disjunctPositions)) {\n // Row is no longer visible — clean up all state including tag index\n for (const tag of rowTagSet) {\n const parsedTag = parseTag(tag)\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength!)\n tagCache.delete(tag)\n }\n rowTagSets.delete(rowId)\n rowActiveConditions.delete(rowId)\n return true\n }\n return false\n }\n\n // Simple shape (no subquery dependencies — server sends no active_conditions):\n // Remove matching tags and delete if tag set is empty\n for (const tag of rowTagSet) {\n const parsedTag = parseTag(tag)\n if (tagMatchesPattern(parsedTag, pattern)) {\n rowTagSet.delete(tag)\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength!)\n }\n }\n\n if (rowTagSet.size === 0) {\n rowTagSets.delete(rowId)\n return true\n }\n\n return false\n }\n\n /**\n * Process move-out event: remove matching tags from rows and delete rows with empty tag sets\n */\n const processMoveOutEvent = (\n patterns: Array<MovePattern>,\n begin: () => void,\n write: (message: ChangeMessageOrDeleteKeyMessage<T>) => void,\n transactionStarted: boolean,\n onDelete: (rowId: RowId) => void,\n ): boolean => {\n if (tagLength === undefined) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Received move-out message but no tag length set yet, ignoring`,\n )\n return transactionStarted\n }\n\n let txStarted = transactionStarted\n\n // Process all patterns and collect rows to delete\n for (const pattern of patterns) {\n // Find all rows that match this pattern\n const affectedRowIds = findRowsMatchingPattern(pattern, tagIndex)\n\n for (const rowId of affectedRowIds) {\n if (removeMatchingTagsFromRow(rowId, pattern)) {\n // Delete rows with empty tag sets\n if (!txStarted) {\n begin()\n txStarted = true\n }\n\n write({\n type: `delete`,\n key: rowId,\n })\n onDelete(rowId)\n }\n }\n }\n\n return txStarted\n }\n\n /**\n * Process move-in event: re-activate conditions for rows matching the patterns.\n * This is a silent operation — no messages are emitted to the collection.\n */\n const processMoveInEvent = (patterns: Array<MovePattern>): void => {\n if (tagLength === undefined) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Received move-in message but no tag length set yet, ignoring`,\n )\n return\n }\n\n for (const pattern of patterns) {\n const affectedRowIds = findRowsMatchingPattern(pattern, tagIndex)\n\n for (const rowId of affectedRowIds) {\n const activeConditions = rowActiveConditions.get(rowId)\n if (activeConditions) {\n activeConditions[pattern.pos] = true\n }\n }\n }\n }\n\n return {\n hasTags: () => tagLength !== undefined,\n processTagsForChangeMessage,\n clearTagTrackingState,\n clearTagsForRow,\n processMoveOutEvent,\n processMoveInEvent,\n }\n }\n // Tags belong to a collection, and survive a compatible resume of that\n // collection. Reusing an options descriptor must not share visibility.\n const collectionTags = new WeakMap<\n object,\n ReturnType<typeof createTagState>\n >()\n\n return {\n getSyncMetadata: () => ({\n relation: shapeOptions.params?.table\n ? [relationSchema || `public`, shapeOptions.params.table]\n : undefined,\n }),\n sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {\n const retainsTagState = collectionTags.has(params.collection)\n let tagState = collectionTags.get(params.collection)\n if (!tagState) {\n tagState = createTagState()\n collectionTags.set(params.collection, tagState)\n }\n const {\n processTagsForChangeMessage,\n clearTagTrackingState,\n clearTagsForRow,\n processMoveOutEvent,\n processMoveInEvent,\n } = tagState\n const lifecycle = getLifecycle(params.collection)\n const lifecycleEpoch = lifecycle.start()\n const isActiveLifecycle = () => lifecycle.isActive(lifecycleEpoch)\n Object.assign(params.collection.utils, lifecycle.utils)\n\n const {\n begin,\n write,\n commit: commitSyncTransaction,\n markReady,\n markError,\n truncate,\n collection,\n metadata,\n } = params\n let commitSequence = 0\n const pendingAppliedReceipts = new Map<number, Promise<void>>()\n const commit = (signal?: AbortSignal): SyncAppliedReceipt => {\n const sequence = ++commitSequence\n const applied = commitSyncTransaction(signal)\n if (applied === true) {\n return true\n }\n pendingAppliedReceipts.set(sequence, applied)\n const removeReceipt = () => pendingAppliedReceipts.delete(sequence)\n void applied.then(removeReceipt, removeReceipt)\n return applied\n }\n const waitForCommitsAfter = async (cursor: number): Promise<void> => {\n await Promise.all(\n Array.from(pendingAppliedReceipts, ([sequence, applied]) =>\n sequence > cursor ? applied : undefined,\n ),\n )\n }\n const readPersistedResumeState = (): ElectricResumeState | undefined => {\n const persistedResumeState = metadata?.collection.get(`electric:resume`)\n return parseElectricResumeState(persistedResumeState)\n }\n\n const persistedMetadata = metadata as\n | ElectricSyncMetadataWithHydration\n | undefined\n const scanPersisted = persistedMetadata?.row.scanPersisted\n const whenHydrated = persistedMetadata?.row.whenHydrated\n\n const persistedResumeState = getNewestElectricResumeState(\n readPersistedResumeState(),\n lifecycle.resumeState,\n )\n const shapeIdentity = getStableShapeIdentity({\n url: shapeOptions.url,\n params: shapeOptions.params as Record<string, unknown> | undefined,\n })\n const hasIncompatiblePersistedResume =\n persistedResumeState?.kind === `resume` &&\n persistedResumeState.shapeId !== shapeIdentity\n const hasUnverifiablePersistedResume =\n shapeOptions.offset === undefined &&\n shapeOptions.handle === undefined &&\n persistedResumeState?.kind === `resume` &&\n scanPersisted !== undefined &&\n whenHydrated === undefined\n if (hasUnverifiablePersistedResume && !warnedUnverifiableResume) {\n warnedUnverifiableResume = true\n console.warn(\n `Electric persistence cannot verify hydration for saved resume state. Update the persistence adapter alongside Electric to enable safe resume.`,\n )\n }\n const needsFullSnapshot =\n shapeOptions.offset === undefined &&\n shapeOptions.handle === undefined &&\n persistedResumeState !== undefined &&\n (persistedResumeState.kind === `reset` ||\n (!retainsTagState && persistedResumeState.requiresTagState !== false))\n const canUsePersistedResume =\n shapeOptions.offset === undefined &&\n shapeOptions.handle === undefined &&\n persistedResumeState?.kind === `resume` &&\n !hasIncompatiblePersistedResume &&\n !hasUnverifiablePersistedResume &&\n // Cached rows do not contain authoritative tag/active-condition state.\n // Unknown (older) metadata is conservative; untagged shapes still resume.\n !needsFullSnapshot\n const hasExplicitResumeOffset =\n shapeOptions.offset !== undefined && shapeOptions.offset !== `-1`\n if (!canUsePersistedResume && !hasExplicitResumeOffset) {\n clearTagTrackingState()\n }\n const receivesCompleteRows = shapeOptions.params?.replica === `full`\n // Eager and progressive streams that start after the initial offset can\n // only apply partial updates when the local materialization is complete.\n const requiresCompleteResume =\n syncMode !== `on-demand` &&\n (canUsePersistedResume ||\n (hasExplicitResumeOffset && !receivesCompleteRows))\n // A fresh snapshot replaces its hydrated cache; omitting the old offset\n // alone would merge rows that no longer exist on the server.\n let freshSnapshotPending =\n (syncMode === `eager` || needsFullSnapshot) &&\n !canUsePersistedResume &&\n !hasExplicitResumeOffset &&\n whenHydrated !== undefined\n\n // Wrap markReady to wait for test hook in progressive mode\n let progressiveReadyGate: Promise<void> | null = null\n let streamErrorVersion = 0\n const wrappedMarkReady = (\n isBuffering: boolean,\n expectedErrorVersion = streamErrorVersion,\n ) => {\n if (streamErrorVersion !== expectedErrorVersion) return\n\n // Only create gate if we're in buffering phase (first up-to-date)\n if (\n isBuffering &&\n syncMode === `progressive` &&\n testHooks?.beforeMarkingReady\n ) {\n // Create a new gate promise for this sync cycle\n progressiveReadyGate = testHooks.beforeMarkingReady()\n progressiveReadyGate.then(() => {\n if (streamErrorVersion === expectedErrorVersion) {\n markReady()\n }\n })\n } else {\n // No hook, not buffering, or already past first up-to-date\n markReady()\n }\n }\n\n // Abort controller for the stream - wraps the signal if provided\n const abortController = new AbortController()\n const forwardExternalAbort = () => abortController.abort()\n\n if (shapeOptions.signal) {\n shapeOptions.signal.addEventListener(`abort`, forwardExternalAbort, {\n once: true,\n })\n if (shapeOptions.signal.aborted) {\n abortController.abort()\n }\n }\n\n abortController.signal.addEventListener(`abort`, () => {\n lifecycle.retire(lifecycleEpoch)\n })\n\n const stream = new ShapeStream({\n ...shapeOptions,\n // Recovery needs a complete snapshot even for on-demand shapes.\n // Normal on-demand startup still subscribes to changes only.\n log:\n syncMode === `on-demand` && !needsFullSnapshot\n ? `changes_only`\n : undefined,\n // In on-demand mode, we only need the changes from the point of time the collection was created\n // so we default to `now` when there is no saved offset.\n offset:\n shapeOptions.offset ??\n (canUsePersistedResume\n ? (persistedResumeState.offset as Offset)\n : syncMode === `on-demand` && !needsFullSnapshot\n ? `now`\n : undefined),\n handle:\n shapeOptions.handle ??\n (canUsePersistedResume ? persistedResumeState.handle : undefined),\n signal: abortController.signal,\n onError: (errorParams) => {\n streamErrorVersion++\n // Note that Electric sends a 409 error on a `must-refetch` message, but the\n // ShapeStream handled this and it will not reach this handler, therefor\n // this handler will not run for a `must-refetch`.\n const initialSyncFailed = collection.status === `loading`\n if (initialSyncFailed) {\n markError(errorParams)\n }\n\n if (shapeOptions.onError) {\n return shapeOptions.onError(errorParams)\n } else {\n console.error(\n `An error occurred while syncing collection: ${collection.id}, \\n` +\n (initialSyncFailed\n ? `the initial sync has been marked as failed. \\n`\n : `the last ready snapshot has been preserved. \\n`) +\n `You can provide an 'onError' handler on the shapeOptions to handle this error, and this message will not be logged.`,\n errorParams,\n )\n }\n\n return\n },\n })\n let transactionStarted = false\n const newTxids = new Set<Txid>()\n const newSnapshots: Array<PostgresSnapshot> = []\n // Track if we've completed initial sync in progressive mode. A persisted\n // resume starts from an already-committed stream offset, so the next\n // up-to-date message must not run the initial atomic swap again.\n let hasReceivedUpToDate =\n syncMode === `progressive` && requiresCompleteResume\n // A must-refetch starts a new snapshot generation. Until its up-to-date\n // commit is applied, old Collection keys cannot make an update valid and\n // the durable resume marker must remain reset.\n let isResettingSnapshot = false\n let resetGeneration = 0\n\n // Progressive mode state\n // Helper to determine if we're buffering the initial sync\n const isBufferingInitialSync = () =>\n syncMode === `progressive` &&\n !hasReceivedUpToDate &&\n !isResettingSnapshot\n const bufferedMessages: Array<Message<T>> = [] // Buffer change messages during initial sync\n\n // Track keys that have been synced to handle overlapping subset queries.\n // When multiple subset queries return the same row, the server sends `insert`\n // for each response. We convert subsequent inserts to updates to avoid\n // duplicate key errors when the row's data has changed between requests.\n const syncedKeys = new Set<string | number>()\n let resumeInvalid = false\n\n const stageResumeMetadata = () => {\n if (!isActiveLifecycle() || resumeInvalid) {\n return\n }\n const shapeHandle = stream.shapeHandle\n const lastOffset = stream.lastOffset\n if (!shapeHandle || lastOffset === `-1`) {\n return\n }\n\n const resumeState: ElectricResumeState = {\n kind: `resume`,\n offset: lastOffset,\n handle: shapeHandle,\n shapeId: shapeIdentity,\n updatedAt: Date.now(),\n requiresTagState: tagState.hasTags(),\n }\n lifecycle.resumeState = resumeState\n metadata?.collection.set(`electric:resume`, resumeState)\n }\n\n const commitResetResumeMetadataImmediately = () => {\n const resetState: ElectricResumeState = {\n kind: `reset`,\n updatedAt: Date.now(),\n }\n lifecycle.resumeState = resetState\n\n if (metadata) {\n begin({ immediate: true })\n metadata.collection.set(`electric:resume`, resetState)\n commit()\n }\n }\n\n if (\n hasIncompatiblePersistedResume ||\n hasUnverifiablePersistedResume ||\n (needsFullSnapshot && persistedResumeState.kind === `resume`)\n ) {\n commitResetResumeMetadataImmediately()\n }\n\n /**\n * Process a change message: handle tags and write the mutation\n */\n const processChangeMessage = (changeMessage: Message<T>) => {\n if (!isChangeMessage(changeMessage)) {\n return\n }\n\n // Process tags if present\n const tags = changeMessage.headers.tags\n const removedTags = changeMessage.headers.removed_tags\n const hasTags = tags || removedTags\n\n // Extract active_conditions from headers (DNF support)\n const activeConditions = changeMessage.headers.active_conditions as\n | ActiveConditions\n | undefined\n\n const rowId = collection.getKeyFromItem(changeMessage.value)\n const operation = changeMessage.headers.operation\n\n // Track synced keys and handle overlapping subset queries.\n // When multiple subset queries return the same row, the server sends\n // `insert` for each response. We convert subsequent inserts to updates\n // to avoid duplicate key errors when the row's data has changed.\n const isDelete = operation === `delete`\n const isDuplicateInsert =\n operation === `insert` && syncedKeys.has(rowId)\n\n if (isDelete) {\n syncedKeys.delete(rowId)\n } else {\n syncedKeys.add(rowId)\n }\n\n if (isDelete) {\n clearTagsForRow(rowId)\n } else if (hasTags) {\n processTagsForChangeMessage(\n tags,\n removedTags,\n rowId,\n activeConditions,\n )\n }\n\n write({\n type: isDuplicateInsert ? `update` : operation,\n value: changeMessage.value,\n // Include the primary key and relation info in the metadata\n metadata: {\n ...changeMessage.headers,\n },\n })\n }\n\n // Create deduplicated loadSubset wrapper for non-eager modes\n // This prevents redundant snapshot requests when multiple concurrent\n // live queries request overlapping or subset predicates\n const loadSubsetDedupe = createLoadSubsetDedupe({\n stream,\n syncMode,\n isBufferingInitialSync,\n begin,\n write,\n commit,\n getCommitCursor: () => commitSequence,\n waitForCommitsAfter,\n collectionId,\n // Pass the columnMapper's encode function to transform column names\n // (e.g., camelCase to snake_case) when compiling SQL for subset queries\n encodeColumnName: shapeOptions.columnMapper?.encode,\n // Pass abort signal so requestSnapshot errors can be ignored during cleanup\n signal: abortController.signal,\n })\n\n const resumeKeysPromise =\n requiresCompleteResume || freshSnapshotPending\n ? whenHydrated?.()\n : undefined\n let areResumeKeysReady = !resumeKeysPromise\n const pendingResumeBatches: Array<Array<Message<T>>> = []\n let unsubscribeStream: () => void = () => {}\n\n const invalidateResume = () => {\n resumeInvalid = true\n if (transactionStarted) {\n const cancellation = new AbortController()\n cancellation.abort()\n commit(cancellation.signal)\n transactionStarted = false\n }\n syncedKeys.clear()\n newTxids.clear()\n newSnapshots.length = 0\n commitResetResumeMetadataImmediately()\n streamErrorVersion++\n unsubscribeStream()\n abortController.abort()\n markError(\n new Error(\n `Electric resume state referenced an unseen row; a full snapshot is required`,\n ),\n )\n }\n\n const processMessages = (messages: Array<Message<T>>): void => {\n if (!isActiveLifecycle() || resumeInvalid) {\n return\n }\n\n if (freshSnapshotPending) {\n freshSnapshotPending = false\n begin()\n transactionStarted = true\n truncate()\n syncedKeys.clear()\n clearTagTrackingState()\n isResettingSnapshot = true\n resetGeneration++\n }\n\n // Applied rows can also arrive through persistence invalidations.\n // Overlay only unapplied writes, once per callback rather than once\n // per message. A queued truncate fences off the previous snapshot.\n const pendingPresence = new Map<string | number, boolean>()\n let usesBaseline = true\n for (const pending of collection._state.pendingSyncedTransactions) {\n if (pending.truncate) {\n pendingPresence.clear()\n usesBaseline = false\n }\n for (const operation of pending.operations) {\n pendingPresence.set(operation.key, operation.type !== `delete`)\n }\n }\n for (const message of bufferedMessages) {\n if (isChangeMessage(message)) {\n pendingPresence.set(\n collection.getKeyFromItem(message.value),\n message.headers.operation !== `delete`,\n )\n }\n }\n\n // Track commit point type - up-to-date takes precedence as it also triggers progressive mode atomic swap\n let commitPoint: `up-to-date` | `subset-end` | null = null\n\n lifecycle.beginMatchGeneration(messages)\n\n for (const message of messages) {\n lifecycle.observeMatchMessage(message)\n // A match predicate can synchronously clean up and restart sync.\n // Nothing after that boundary belongs to the replacement session.\n if (!isActiveLifecycle()) return\n\n // Check for txids in the message and add them to our store\n // Skip during buffered initial sync in progressive mode (txids will be extracted during atomic swap)\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), track txids\n // to avoid losing them when messages are written to the existing transaction.\n if (\n hasTxids(message) &&\n (!isBufferingInitialSync() || transactionStarted)\n ) {\n message.headers.txids?.forEach((txid) => newTxids.add(txid))\n }\n\n if (isChangeMessage(message)) {\n const rowId = collection.getKeyFromItem(message.value)\n const operation = message.headers.operation\n const hasKnownRow =\n pendingPresence.get(rowId) ??\n (usesBaseline && collection._state.syncedData.has(rowId))\n if (operation === `update` && !hasKnownRow) {\n // Validate after all earlier events, including tag move-outs.\n // Cancel staged writes before publishing any part of an invalid\n // resumed callback; the next lifecycle must take a full snapshot.\n if (requiresCompleteResume && !isResettingSnapshot) {\n invalidateResume()\n return\n }\n if (!receivesCompleteRows) continue\n }\n pendingPresence.set(rowId, operation !== `delete`)\n }\n\n if (isChangeMessage(message)) {\n // Check if the message contains schema information\n const schema = message.headers.schema\n if (schema && typeof schema === `string`) {\n // Store the schema for future use if it's a valid string\n relationSchema = schema\n }\n\n // In buffered initial sync of progressive mode, buffer messages instead of writing\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), write\n // directly to it instead of buffering. This prevents orphan transactions.\n if (isBufferingInitialSync() && !transactionStarted) {\n bufferedMessages.push(message)\n } else {\n // Normal processing: write changes immediately\n if (!transactionStarted) {\n begin()\n transactionStarted = true\n }\n\n processChangeMessage(message)\n }\n } else if (isSnapshotEndMessage(message)) {\n // Track postgres snapshot metadata for resolving awaiting mutations\n // Skip during buffered initial sync (will be extracted during atomic swap)\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), track snapshots\n // to avoid losing them when messages are written to the existing transaction.\n if (!isBufferingInitialSync() || transactionStarted) {\n newSnapshots.push(parseSnapshotMessage(message))\n }\n } else if (isUpToDateMessage(message)) {\n // up-to-date takes precedence - also triggers progressive mode atomic swap\n commitPoint = `up-to-date`\n } else if (isSubsetEndMessage(message)) {\n // subset-end triggers commit but not progressive mode atomic swap\n if (commitPoint !== `up-to-date`) {\n commitPoint = `subset-end`\n }\n } else if (isMoveOutMessage(message)) {\n // Handle move-out event: buffer if buffering, otherwise process immediately\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), process\n // immediately to avoid orphan transactions.\n if (isBufferingInitialSync() && !transactionStarted) {\n bufferedMessages.push(message)\n } else {\n // Normal processing: process move-out immediately\n transactionStarted = processMoveOutEvent(\n message.headers.patterns,\n begin,\n write,\n transactionStarted,\n (rowId) => {\n pendingPresence.set(rowId, false)\n syncedKeys.delete(rowId)\n },\n )\n }\n } else if (isMoveInMessage(message)) {\n // Handle move-in event: re-activate conditions for matching rows.\n // Buffer if buffering, otherwise process immediately.\n if (isBufferingInitialSync() && !transactionStarted) {\n bufferedMessages.push(message)\n } else {\n processMoveInEvent(message.headers.patterns)\n }\n } else if (isMustRefetchMessage(message)) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Received must-refetch message, starting transaction with truncate`,\n )\n\n commitResetResumeMetadataImmediately()\n\n // Start a transaction and truncate the collection\n if (!transactionStarted) {\n begin()\n transactionStarted = true\n }\n\n truncate()\n\n // Clear tag tracking state\n clearTagTrackingState()\n\n // Clear synced keys tracking since we're starting fresh\n syncedKeys.clear()\n pendingPresence.clear()\n usesBaseline = false\n isResettingSnapshot = true\n resetGeneration++\n\n // Reset the loadSubset deduplication state since we're starting fresh\n // This ensures that previously loaded predicates don't prevent refetching after truncate\n loadSubsetDedupe?.reset()\n\n // Reset flags so we continue accumulating changes until next up-to-date\n commitPoint = null\n hasReceivedUpToDate = false // Reset for progressive mode (isBufferingInitialSync will reflect this)\n bufferedMessages.length = 0 // Clear buffered messages\n }\n }\n\n // A subset completion cannot publish a partial cold-recovery snapshot.\n if (\n needsFullSnapshot &&\n isResettingSnapshot &&\n commitPoint === `subset-end`\n )\n return\n\n if (commitPoint !== null) {\n let applied: SyncAppliedReceipt = true\n const wasBufferingInitialSync = isBufferingInitialSync()\n const finishesReset =\n isResettingSnapshot && commitPoint === `up-to-date`\n const finishingResetGeneration = resetGeneration\n // PROGRESSIVE MODE: Atomic swap on first up-to-date (not subset-end)\n // EXCEPTION: Skip atomic swap if a transaction is already started (e.g., from must-refetch).\n // In that case, do a normal commit to properly close the existing transaction.\n if (\n isBufferingInitialSync() &&\n commitPoint === `up-to-date` &&\n !transactionStarted\n ) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Progressive mode: Performing atomic swap with ${bufferedMessages.length} buffered messages`,\n )\n\n // Start atomic swap transaction\n begin()\n\n // Truncate to clear all snapshot data\n truncate()\n\n // Clear tag tracking state for atomic swap\n clearTagTrackingState()\n\n // Clear synced keys tracking for atomic swap\n syncedKeys.clear()\n\n // Apply all buffered change messages and extract txids/snapshots\n for (const bufferedMsg of bufferedMessages) {\n if (isChangeMessage(bufferedMsg)) {\n processChangeMessage(bufferedMsg)\n\n // Extract txids from buffered messages (will be committed to store after transaction)\n if (hasTxids(bufferedMsg)) {\n bufferedMsg.headers.txids?.forEach((txid) =>\n newTxids.add(txid),\n )\n }\n } else if (isSnapshotEndMessage(bufferedMsg)) {\n // Extract snapshots from buffered messages (will be committed to store after transaction)\n newSnapshots.push(parseSnapshotMessage(bufferedMsg))\n } else if (isMoveOutMessage(bufferedMsg)) {\n // Process buffered move-out messages during atomic swap\n processMoveOutEvent(\n bufferedMsg.headers.patterns,\n begin,\n write,\n // The swap already opened a transaction, even though the\n // normal-stream transactionStarted flag is still false.\n true,\n (rowId) => {\n pendingPresence.set(rowId, false)\n syncedKeys.delete(rowId)\n },\n )\n } else if (isMoveInMessage(bufferedMsg)) {\n // Process buffered move-in messages during atomic swap\n processMoveInEvent(bufferedMsg.headers.patterns)\n }\n }\n\n // Commit the atomic swap\n stageResumeMetadata()\n applied = commit()\n\n // Exit buffering phase by marking that we've received up-to-date\n // isBufferingInitialSync() will now return false\n bufferedMessages.length = 0\n\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Progressive mode: Atomic swap complete, now in normal sync mode`,\n )\n } else {\n // Normal mode or on-demand: commit transaction if one was started\n // Both up-to-date and subset-end trigger a commit\n if (transactionStarted) {\n if (!isResettingSnapshot || finishesReset) {\n stageResumeMetadata()\n }\n applied = commit()\n transactionStarted = false\n } else if (commitPoint === `up-to-date` && metadata) {\n begin()\n stageResumeMetadata()\n applied = commit()\n }\n }\n const readyErrorVersion = streamErrorVersion\n if (applied === true) {\n wrappedMarkReady(wasBufferingInitialSync, readyErrorVersion)\n } else {\n void applied.then(\n () =>\n wrappedMarkReady(wasBufferingInitialSync, readyErrorVersion),\n () => undefined,\n )\n }\n\n if (finishesReset) {\n const finishReset = () => {\n if (resetGeneration === finishingResetGeneration) {\n isResettingSnapshot = false\n }\n }\n if (applied === true) {\n finishReset()\n } else {\n void applied.then(finishReset, () => undefined)\n }\n }\n\n // Track that we've received the first up-to-date for progressive mode\n if (commitPoint === `up-to-date`) {\n hasReceivedUpToDate = true\n }\n\n // Stream evidence is the acknowledgement boundary used by mutation\n // handlers. It must publish before a parked applied receipt or the\n // optimistic transaction and its acknowledgement can deadlock.\n if (newTxids.size > 0) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}new txids synced from pg %O`,\n Array.from(newTxids),\n )\n }\n newSnapshots.forEach((snapshot) =>\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}new snapshot synced from pg %o`,\n snapshot,\n ),\n )\n lifecycle.publishEvidence(newTxids, newSnapshots)\n newTxids.clear()\n newSnapshots.length = 0\n lifecycle.commitMatches()\n }\n }\n\n unsubscribeStream = stream.subscribe((messages: Array<Message<T>>) => {\n if (!areResumeKeysReady) {\n pendingResumeBatches.push([...messages])\n return\n }\n processMessages(messages)\n })\n\n if (!areResumeKeysReady && resumeKeysPromise) {\n void resumeKeysPromise.then(\n () => {\n if (abortController.signal.aborted) return\n\n areResumeKeysReady = true\n\n const queuedBatches = pendingResumeBatches.splice(0)\n queuedBatches.forEach(processMessages)\n },\n (error: unknown) => {\n if (abortController.signal.aborted) return\n\n pendingResumeBatches.length = 0\n resumeInvalid = true\n commitResetResumeMetadataImmediately()\n streamErrorVersion++\n unsubscribeStream()\n abortController.abort()\n markError(error)\n },\n )\n }\n\n // Return the deduplicated loadSubset if available (on-demand or progressive mode)\n // The loadSubset method is auto-bound, so it can be safely returned directly\n return {\n loadSubset: loadSubsetDedupe?.loadSubset,\n cleanup: () => {\n shapeOptions.signal?.removeEventListener(\n `abort`,\n forwardExternalAbort,\n )\n // Unsubscribe from the stream\n unsubscribeStream()\n // Abort the abort controller to stop the stream\n abortController.abort()\n pendingResumeBatches.length = 0\n // Reset deduplication tracking so collection can load fresh data if restarted\n loadSubsetDedupe?.reset()\n lifecycle.retire(lifecycleEpoch)\n },\n }\n },\n }\n}\n"],"names":["parseTag","parseTagString","persistedResumeState"],"mappings":";;;;;;;AAgFA,MAAM,QAAQ,YAAY,MAAM,gBAAgB;AAEhD,MAAM,0CAA0C;AAKzC,MAAM,6CAA6B,mBAAmB;AAyD7D,SAAS,uBACP,UACkB;AAClB,QAAM,SAAS,SAAS;AACxB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,GAAI,SAAS,EAAE,OAAA,IAAW,CAAA;AAAA,IAC1B,WAAW,MAAM,KAAK,SAAS,SAAS,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAAA,EAAA;AAElE;AAEA,SAAS,uBACP,UACA,MACM;AACN,QAAM,SAAS,sBAAsB,IAAI;AACzC,MAAI,CAAC,OAAQ;AAEb,WAAS,sBAAsB,OAAO;AACtC,WAAS,YAAY,IAAI,IAAI,OAAO,SAAS;AAC/C;AAEA,SAAS,yBACP,OACiC;AACjC,MAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AACf,MACE,OAAO,SAAS,YAChB,OAAO,OAAO,WAAW,YACzB,OAAO,OAAO,WA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;AAAA,MAAA;AAAA,IAEJ;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"electric.js","sources":["../../src/electric.ts"],"sourcesContent":["import {\n ShapeStream,\n isChangeMessage,\n isControlMessage,\n isVisibleInSnapshot,\n} from '@electric-sql/client'\nimport DebugModule from 'debug'\nimport {\n DeduplicatedLoadSubset,\n LoadSubsetOperationAbortedError,\n and,\n validateSyncPersistenceCapability,\n warnOnce,\n withCollectionConfigFactory,\n withCollectionSyncConfigCleanup,\n withCollectionSyncConfigFactory,\n} from '@tanstack/db'\nimport {\n ExpectedNumberInAwaitTxIdError,\n StreamAbortedError,\n TimeoutWaitingForMatchError,\n TimeoutWaitingForTxIdError,\n} from './errors'\nimport { compileSQL } from './sql-compiler'\nimport {\n addTagToIndex,\n deriveDisjunctPositions,\n findRowsMatchingPattern,\n getTagLength,\n isMoveInMessage,\n isMoveOutMessage,\n parseTag as parseTagString,\n removeTagFromIndex,\n rowVisible,\n tagMatchesPattern,\n} from './tag-index'\nimport type { ColumnEncoder } from './sql-compiler'\nimport type {\n ActiveConditions,\n DisjunctPositions,\n MovePattern,\n MoveTag,\n ParsedMoveTag,\n RowId,\n TagIndex,\n} from './tag-index'\nimport type {\n BaseCollectionConfig,\n ChangeMessageOrDeleteKeyMessage,\n CollectionConfig,\n DeleteMutationFnParams,\n InsertMutationFnParams,\n LoadSubsetOptions,\n SyncAppliedReceipt,\n SyncConfig,\n SyncMode,\n UpdateMutationFnParams,\n} from '@tanstack/db'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type {\n ControlMessage,\n GetExtensions,\n Message,\n Offset,\n PostgresSnapshot,\n Row,\n ShapeStreamOptions,\n} from '@electric-sql/client'\n\n// Re-export for user convenience in custom match functions\nexport { isChangeMessage, isControlMessage } from '@electric-sql/client'\n\nconst debug = DebugModule.debug(`ts/db:electric`)\n\n/**\n * Symbol for internal test hooks (hidden from public API)\n */\nexport const ELECTRIC_TEST_HOOKS = Symbol(`electricTestHooks`)\n\n/**\n * Internal test hooks interface (for testing only)\n */\nexport interface ElectricTestHooks {\n /**\n * Called before marking collection ready after first up-to-date in progressive mode\n * Allows tests to pause and validate snapshot phase before atomic swap completes\n */\n beforeMarkingReady?: () => Promise<void>\n}\n\n/**\n * Type representing a transaction ID in ElectricSQL\n */\nexport type Txid = number\n\ntype ElectricResumeState =\n | {\n kind: `resume`\n offset: string\n handle: string\n shapeId: string\n updatedAt: number\n requiresTagState?: boolean\n }\n | {\n kind: `reset`\n updatedAt: number\n }\n\ntype ElectricSyncMeta = {\n version: 1\n resume?: ElectricResumeState\n seenTxids: Array<Txid>\n}\n\ntype ElectricLifecycleEvidence = {\n seenTxids: Set<Txid>\n seenSnapshots: Array<PostgresSnapshot>\n hydratedResumeState?: ElectricResumeState\n}\n\ntype ElectricPendingMatch<T extends Row<unknown>> = {\n matchFn: (message: Message<T>) => boolean\n resolve: (value: boolean) => void\n reject: (error: Error) => void\n timeoutId: ReturnType<typeof setTimeout>\n matched: boolean\n}\n\ntype ElectricMatchBuffer<T extends Row<unknown>> = {\n committedMessages: Array<Message<T>>\n pendingMessages: Array<Message<T>>\n}\n\nfunction exportElectricSyncMeta(\n evidence: ElectricLifecycleEvidence,\n): ElectricSyncMeta {\n const resume = evidence.hydratedResumeState\n return {\n version: 1,\n ...(resume ? { resume } : {}),\n seenTxids: Array.from(evidence.seenTxids).sort((a, b) => a - b),\n }\n}\n\nfunction importElectricSyncMeta(\n evidence: ElectricLifecycleEvidence,\n meta: unknown,\n): void {\n const parsed = parseElectricSyncMeta(meta)\n if (!parsed) return\n\n evidence.hydratedResumeState = parsed.resume\n evidence.seenTxids = new Set(parsed.seenTxids)\n}\n\nfunction parseElectricResumeState(\n value: unknown,\n): ElectricResumeState | undefined {\n if (!value || typeof value !== `object`) {\n return undefined\n }\n\n const record = value as Record<string, unknown>\n if (\n record.kind === `resume` &&\n typeof record.offset === `string` &&\n typeof record.handle === `string` &&\n typeof record.shapeId === `string` &&\n typeof record.updatedAt === `number` &&\n Number.isFinite(record.updatedAt)\n ) {\n return {\n kind: `resume`,\n offset: record.offset,\n handle: record.handle,\n shapeId: record.shapeId,\n updatedAt: record.updatedAt,\n ...(typeof record.requiresTagState === `boolean` && {\n requiresTagState: record.requiresTagState,\n }),\n }\n }\n\n if (\n record.kind === `reset` &&\n typeof record.updatedAt === `number` &&\n Number.isFinite(record.updatedAt)\n ) {\n return {\n kind: `reset`,\n updatedAt: record.updatedAt,\n }\n }\n\n return undefined\n}\n\nfunction parseElectricSyncMeta(value: unknown): ElectricSyncMeta | undefined {\n if (!value || typeof value !== `object`) {\n return undefined\n }\n\n const record = value as Record<string, unknown>\n if (\n record.version !== 1 ||\n !Array.isArray(record.seenTxids) ||\n !record.seenTxids.every(\n (txid) => typeof txid === `number` && Number.isFinite(txid),\n )\n ) {\n return undefined\n }\n\n const resume =\n record.resume === undefined\n ? undefined\n : parseElectricResumeState(record.resume)\n if (record.resume !== undefined && resume === undefined) {\n return undefined\n }\n\n return {\n version: 1,\n ...(resume ? { resume } : {}),\n seenTxids: Array.from(new Set(record.seenTxids)).sort((a, b) => a - b),\n }\n}\n\nfunction mergeElectricSyncMeta(\n current: unknown,\n incoming: unknown,\n): ElectricSyncMeta | unknown {\n const currentMeta = parseElectricSyncMeta(current)\n const incomingMeta = parseElectricSyncMeta(incoming)\n\n if (!incomingMeta) {\n return current\n }\n if (!currentMeta) {\n return incomingMeta\n }\n\n const resume = getNewestElectricResumeState(\n currentMeta.resume,\n incomingMeta.resume,\n )\n\n return {\n version: 1,\n ...(resume ? { resume } : {}),\n seenTxids: Array.from(\n new Set([...currentMeta.seenTxids, ...incomingMeta.seenTxids]),\n ).sort((a, b) => a - b),\n }\n}\n\nfunction getNewestElectricResumeState(\n current: ElectricResumeState | undefined,\n incoming: ElectricResumeState | undefined,\n): ElectricResumeState | undefined {\n if (!current) return incoming\n if (!incoming) return current\n if (incoming.updatedAt > current.updatedAt) return incoming\n if (incoming.updatedAt < current.updatedAt) return current\n\n const isSameState =\n current.kind === incoming.kind &&\n (current.kind === `reset` ||\n (incoming.kind === `resume` &&\n current.offset === incoming.offset &&\n current.handle === incoming.handle &&\n current.shapeId === incoming.shapeId))\n\n // Equal timestamps have no causal ordering. Preserve an identical state,\n // but collapse every conflict to reset so merge order cannot resurrect an\n // offset that another source has already declared unsafe.\n return isSameState ? current : { kind: `reset`, updatedAt: current.updatedAt }\n}\n\n/**\n * Custom match function type - receives stream messages and returns boolean\n * indicating if the mutation has been synchronized\n */\nexport type MatchFunction<T extends Row<unknown>> = (\n message: Message<T>,\n) => boolean\n\n/**\n * Matching strategies for Electric synchronization\n * Handlers can return:\n * - Txid strategy: { txid: number | number[], timeout?: number } (deprecated compatibility behavior)\n * - Void (no return value) - mutation completes without waiting\n *\n * The optional timeout property specifies how long to wait for the txid(s) in milliseconds.\n * If not specified, defaults to 15000ms.\n */\nexport type MatchingStrategy = {\n txid: Txid | Array<Txid>\n timeout?: number\n} | void\n\n/**\n * Type representing a snapshot end message\n */\ntype SnapshotEndMessage = ControlMessage & {\n headers: { control: `snapshot-end` }\n}\n// The `InferSchemaOutput` and `ResolveType` are copied from the `@tanstack/db` package\n// but we modified `InferSchemaOutput` slightly to restrict the schema output to `Row<unknown>`\n// This is needed in order for `GetExtensions` to be able to infer the parser extensions type from the schema\ntype InferSchemaOutput<T> = T extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<T> extends Row<unknown>\n ? StandardSchemaV1.InferOutput<T>\n : Record<string, unknown>\n : Record<string, unknown>\n\n/**\n * The mode of sync to use for the collection.\n * @default `eager`\n * @description\n * - `eager`:\n * - syncs all data immediately on preload\n * - collection will be marked as ready once the sync is complete\n * - there is no incremental sync\n * - `on-demand`:\n * - syncs data in incremental snapshots when the collection is queried\n * - collection will be marked as ready immediately after the first snapshot is synced\n * - `progressive`:\n * - syncs all data for the collection in the background\n * - uses incremental snapshots during the initial sync to provide a fast path to the data required for queries\n * - collection will be marked as ready once the full sync is complete\n */\nexport type ElectricSyncMode = SyncMode | `progressive`\n\n/**\n * Configuration interface for Electric collection options\n * @template T - The type of items in the collection\n * @template TSchema - The schema type for validation\n */\nexport interface ElectricCollectionConfig<\n T extends Row<unknown> = Row<unknown>,\n TSchema extends StandardSchemaV1 = never,\n> extends Omit<\n BaseCollectionConfig<T, string | number, TSchema, ElectricCollectionUtils<T>>,\n `onInsert` | `onUpdate` | `onDelete` | `syncMode`\n> {\n /**\n * Configuration options for the ElectricSQL ShapeStream\n */\n shapeOptions: ShapeStreamOptions<GetExtensions<T>>\n syncMode?: ElectricSyncMode\n\n /**\n * Internal test hooks (for testing only)\n * Hidden via Symbol to prevent accidental usage in production\n */\n [ELECTRIC_TEST_HOOKS]?: ElectricTestHooks\n\n /**\n * Optional asynchronous handler function called before an insert operation\n *\n * **IMPORTANT - Electric Synchronization:**\n * This handler **must not resolve** until synchronization is confirmed.\n * Await one of these synchronization utilities before the handler completes:\n * 1. `await collection.utils.awaitTxId(txid)` (recommended for most cases)\n * 2. `await collection.utils.awaitMatch(fn)` for custom matching logic\n *\n * Simply returning without waiting for sync will drop optimistic state too early, causing UI glitches.\n *\n * @param params Object containing transaction and collection information\n * @returns Promise that should resolve after synchronization is complete\n *\n * **Deprecation notice:** Returning `{ txid }` from handlers is deprecated and will be removed in v1.0.\n * Use `await collection.utils.awaitTxId(txid)` within the handler instead.\n *\n * @example\n * // Recommended: Wait for txid to sync\n * onInsert: async ({ transaction, collection }) => {\n * const newItem = transaction.mutations[0].modified\n * const result = await api.todos.create({\n * data: newItem\n * })\n * // Wait for txid to sync before handler completes\n * await collection.utils.awaitTxId(result.txid)\n * }\n *\n * @example\n * // Insert handler with custom timeout\n * onInsert: async ({ transaction, collection }) => {\n * const newItem = transaction.mutations[0].modified\n * const result = await api.todos.create({\n * data: newItem\n * })\n * // Wait up to 10 seconds for txid\n * await collection.utils.awaitTxId(result.txid, 10000)\n * }\n *\n * @example\n * // Insert handler with timeout error handling\n * onInsert: async ({ transaction, collection }) => {\n * const newItem = transaction.mutations[0].modified\n * const result = await api.todos.create({\n * data: newItem\n * })\n *\n * try {\n * await collection.utils.awaitTxId(result.txid, 5000)\n * } catch (error) {\n * // Decide sync timeout policy:\n * // - Throw to rollback optimistic state\n * // - Catch to keep optimistic state (eventual consistency)\n * // - Schedule background retry\n * console.warn('Sync timeout, keeping optimistic state:', error)\n * // Don't throw - allow optimistic state to persist\n * }\n * }\n *\n * @example\n * // Insert handler with multiple items\n * onInsert: async ({ transaction, collection }) => {\n * const items = transaction.mutations.map(m => m.modified)\n * const results = await Promise.all(\n * items.map(item => api.todos.create({ data: item }))\n * )\n * // Wait for all txids to sync\n * await Promise.all(\n * results.map(r => collection.utils.awaitTxId(r.txid))\n * )\n * }\n *\n * @example\n * // Alternative: Use awaitMatch utility for custom matching logic\n * onInsert: async ({ transaction, collection }) => {\n * const newItem = transaction.mutations[0].modified\n * await api.todos.create({ data: newItem })\n * // Wait for specific change to appear in sync stream\n * await collection.utils.awaitMatch(\n * (message) => isChangeMessage(message) &&\n * message.headers.operation === 'insert' &&\n * message.value.name === newItem.name\n * )\n * }\n */\n onInsert?: (\n params: InsertMutationFnParams<\n T,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => Promise<MatchingStrategy>\n\n /**\n * Optional asynchronous handler function called before an update operation\n *\n * **IMPORTANT - Electric Synchronization:**\n * This handler **must not resolve** until synchronization is confirmed.\n * Await one of these synchronization utilities before the handler completes:\n * 1. `await collection.utils.awaitTxId(txid)` (recommended for most cases)\n * 2. `await collection.utils.awaitMatch(fn)` for custom matching logic\n *\n * Simply returning without waiting for sync will drop optimistic state too early, causing UI glitches.\n *\n * @param params Object containing transaction and collection information\n * @returns Promise that should resolve after synchronization is complete\n *\n * **Deprecation notice:** Returning `{ txid }` from handlers is deprecated and will be removed in v1.0.\n * Use `await collection.utils.awaitTxId(txid)` within the handler instead.\n *\n * @example\n * // Recommended: Wait for txid to sync\n * onUpdate: async ({ transaction, collection }) => {\n * const { original, changes } = transaction.mutations[0]\n * const result = await api.todos.update({\n * where: { id: original.id },\n * data: changes\n * })\n * // Wait for txid to sync before handler completes\n * await collection.utils.awaitTxId(result.txid)\n * }\n *\n * @example\n * // Alternative: Use awaitMatch utility for custom matching logic\n * onUpdate: async ({ transaction, collection }) => {\n * const { original, changes } = transaction.mutations[0]\n * await api.todos.update({ where: { id: original.id }, data: changes })\n * // Wait for specific change to appear in sync stream\n * await collection.utils.awaitMatch(\n * (message) => isChangeMessage(message) &&\n * message.headers.operation === 'update' &&\n * message.value.id === original.id\n * )\n * }\n */\n onUpdate?: (\n params: UpdateMutationFnParams<\n T,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => Promise<MatchingStrategy>\n\n /**\n * Optional asynchronous handler function called before a delete operation\n *\n * **IMPORTANT - Electric Synchronization:**\n * This handler **must not resolve** until synchronization is confirmed.\n * Await one of these synchronization utilities before the handler completes:\n * 1. `await collection.utils.awaitTxId(txid)` (recommended for most cases)\n * 2. `await collection.utils.awaitMatch(fn)` for custom matching logic\n *\n * Simply returning without waiting for sync will drop optimistic state too early, causing UI glitches.\n *\n * @param params Object containing transaction and collection information\n * @returns Promise that should resolve after synchronization is complete\n *\n * **Deprecation notice:** Returning `{ txid }` from handlers is deprecated and will be removed in v1.0.\n * Use `await collection.utils.awaitTxId(txid)` within the handler instead.\n *\n * @example\n * // Recommended: Wait for txid to sync\n * onDelete: async ({ transaction, collection }) => {\n * const mutation = transaction.mutations[0]\n * const result = await api.todos.delete({\n * id: mutation.original.id\n * })\n * // Wait for txid to sync before handler completes\n * await collection.utils.awaitTxId(result.txid)\n * }\n *\n * @example\n * // Alternative: Use awaitMatch utility for custom matching logic\n * onDelete: async ({ transaction, collection }) => {\n * const mutation = transaction.mutations[0]\n * await api.todos.delete({ id: mutation.original.id })\n * // Wait for specific change to appear in sync stream\n * await collection.utils.awaitMatch(\n * (message) => isChangeMessage(message) &&\n * message.headers.operation === 'delete' &&\n * message.value.id === mutation.original.id\n * )\n * }\n */\n onDelete?: (\n params: DeleteMutationFnParams<\n T,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ) => Promise<MatchingStrategy>\n}\n\nfunction isUpToDateMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is ControlMessage & { up_to_date: true } {\n return isControlMessage(message) && message.headers.control === `up-to-date`\n}\n\nfunction isMustRefetchMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is ControlMessage & { headers: { control: `must-refetch` } } {\n return isControlMessage(message) && message.headers.control === `must-refetch`\n}\n\nfunction isSnapshotEndMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is SnapshotEndMessage {\n return isControlMessage(message) && message.headers.control === `snapshot-end`\n}\n\nfunction isSubsetEndMessage<T extends Row<unknown>>(\n message: Message<T>,\n): message is ControlMessage & { headers: { control: `subset-end` } } {\n return (\n isControlMessage(message) &&\n (message.headers.control as string) === `subset-end`\n )\n}\n\nfunction parseSnapshotMessage(message: SnapshotEndMessage): PostgresSnapshot {\n return {\n xmin: message.headers.xmin,\n xmax: message.headers.xmax,\n xip_list: message.headers.xip_list,\n }\n}\n\nfunction toStableSerializable(value: unknown): unknown {\n if (value == null) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map((entry) => toStableSerializable(entry))\n }\n\n if (value instanceof Date) {\n return value.toISOString()\n }\n\n if (typeof value === `object`) {\n const record = value as Record<string, unknown>\n const stableRecord: Record<string, unknown> = {}\n const keys = Object.keys(record).sort((left, right) =>\n left < right ? -1 : left > right ? 1 : 0,\n )\n for (const key of keys) {\n stableRecord[key] = toStableSerializable(record[key])\n }\n return stableRecord\n }\n\n return value\n}\n\nfunction getStableShapeIdentity(shapeOptions: {\n url: string\n params?: Record<string, unknown>\n}): string {\n return JSON.stringify(\n toStableSerializable({\n url: shapeOptions.url,\n params: shapeOptions.params ?? null,\n }),\n )\n}\n\n// Check if a message contains txids in its headers\nfunction hasTxids<T extends Row<unknown>>(\n message: Message<T>,\n): message is Message<T> & { headers: { txids?: Array<Txid> } } {\n return `txids` in message.headers && Array.isArray(message.headers.txids)\n}\n\n/**\n * Creates a deduplicated loadSubset handler for progressive/on-demand modes\n * Returns null for eager mode, or a DeduplicatedLoadSubset instance for other modes.\n * Handles fetching snapshots in progressive mode during buffering phase,\n * and requesting snapshots in on-demand mode.\n *\n * When cursor expressions are provided (whereFrom/whereCurrent), makes two\n * requestSnapshot calls:\n * - One for whereFrom (rows > cursor) with limit\n * - One for whereCurrent (rows = cursor, for tie-breaking) without limit\n */\nfunction createLoadSubsetDedupe<T extends Row<unknown>>({\n stream,\n syncMode,\n isBufferingInitialSync,\n begin,\n write,\n commit,\n getCommitCursor,\n waitForCommitsAfter,\n recordSnapshotRow,\n collectionId,\n encodeColumnName,\n signal,\n}: {\n stream: ShapeStream<T>\n syncMode: ElectricSyncMode\n isBufferingInitialSync: () => boolean\n begin: () => void\n write: (mutation: {\n type: `insert` | `update` | `delete`\n value: T\n metadata: Record<string, unknown>\n }) => void\n commit: (signal?: AbortSignal) => SyncAppliedReceipt\n getCommitCursor: () => number\n waitForCommitsAfter: (cursor: number) => Promise<void>\n recordSnapshotRow?: (row: T, message: Message<T>) => void\n collectionId?: string\n /**\n * Optional function to encode column names (e.g., camelCase to snake_case).\n * This is typically the `encode` function from shapeOptions.columnMapper.\n */\n encodeColumnName?: ColumnEncoder\n /**\n * Abort signal to check if the stream has been aborted during cleanup.\n * When aborted, errors from requestSnapshot are silently ignored.\n */\n signal: AbortSignal\n}): DeduplicatedLoadSubset | null {\n if (syncMode === `eager`) {\n return null\n }\n\n const compileOptions = encodeColumnName ? { encodeColumnName } : undefined\n const logPrefix = collectionId ? `[${collectionId}] ` : ``\n\n const abortReason = (abortedSignal: AbortSignal): unknown =>\n abortedSignal.reason ?? new LoadSubsetOperationAbortedError()\n\n /**\n * Handles errors from snapshot operations. Returns true if the error was\n * handled (signal aborted during cleanup), false if it should be re-thrown.\n */\n function handleSnapshotError(error: unknown, operation: string): boolean {\n if (signal.aborted) {\n debug(`${logPrefix}Ignoring ${operation} error during cleanup: %o`, error)\n return true\n }\n debug(`${logPrefix}Error in ${operation}: %o`, error)\n return false\n }\n\n const loadSubset = async (opts: LoadSubsetOptions) => {\n const commitCursor = getCommitCursor()\n const throwIfAborted = () => {\n if (signal.aborted) throw abortReason(signal)\n if (opts.signal?.aborted) throw abortReason(opts.signal)\n }\n throwIfAborted()\n\n if (isBufferingInitialSync()) {\n const snapshotParams = compileSQL<T>(opts, compileOptions)\n try {\n const { data: rows } = await stream.fetchSnapshot(snapshotParams)\n if (opts.signal?.aborted || !isBufferingInitialSync()) {\n debug(`${logPrefix}Ignoring snapshot - sync completed while fetching`)\n return\n }\n\n if (rows.length > 0) {\n begin()\n for (const row of rows) {\n write({\n type: `insert`,\n value: row.value,\n metadata: { ...row.headers },\n })\n }\n const applied = commit(opts.signal)\n for (const row of rows) recordSnapshotRow?.(row.value, row)\n if (applied !== true) await applied\n debug(`${logPrefix}Applied snapshot with ${rows.length} rows`)\n }\n } catch (error) {\n if (opts.signal?.aborted) return\n if (handleSnapshotError(error, `fetchSnapshot`)) {\n return\n }\n throw error\n }\n return\n }\n\n if (syncMode === `progressive`) {\n return\n }\n\n const { cursor, where, orderBy, limit } = opts\n\n throwIfAborted()\n\n // Upstream limitation: ShapeStream.requestSnapshot() publishes its rows\n // through the stream callback before its Promise resolves. It accepts no\n // request signal and exposes no request identity on those messages, so an\n // aborted request can already have installed rows before the check below.\n // Full request-scoped cancellation requires support in the Electric client;\n // matching snapshots by parameters is unsafe for overlapping equal requests.\n try {\n if (cursor) {\n const whereCurrentOpts: LoadSubsetOptions = {\n where: where ? and(where, cursor.whereCurrent) : cursor.whereCurrent,\n orderBy,\n }\n const whereCurrentParams = compileSQL<T>(\n whereCurrentOpts,\n compileOptions,\n )\n\n const whereFromOpts: LoadSubsetOptions = {\n where: where ? and(where, cursor.whereFrom) : cursor.whereFrom,\n orderBy,\n limit,\n }\n const whereFromParams = compileSQL<T>(whereFromOpts, compileOptions)\n\n debug(`${logPrefix}Requesting cursor.whereCurrent snapshot (all ties)`)\n debug(\n `${logPrefix}Requesting cursor.whereFrom snapshot (with limit ${limit})`,\n )\n\n await Promise.all([\n stream.requestSnapshot(whereCurrentParams),\n stream.requestSnapshot(whereFromParams),\n ])\n } else {\n const snapshotParams = compileSQL<T>(opts, compileOptions)\n await stream.requestSnapshot(snapshotParams)\n }\n } catch (error) {\n if (opts.signal?.aborted) return\n if (handleSnapshotError(error, `requestSnapshot`)) {\n return\n }\n throw error\n }\n await waitForCommitsAfter(commitCursor)\n }\n\n return new DeduplicatedLoadSubset({ loadSubset })\n}\n\n/**\n * Type for the awaitTxId utility function\n */\nexport type AwaitTxIdFn = (txId: Txid, timeout?: number) => Promise<boolean>\n\n/**\n * Type for the awaitMatch utility function\n */\nexport type AwaitMatchFn<T extends Row<unknown>> = (\n matchFn: MatchFunction<T>,\n timeout?: number,\n) => Promise<boolean>\n\n/**\n * Electric collection utilities type\n */\nexport interface ElectricCollectionUtils<\n T extends Row<unknown> = Row<unknown>,\n> {\n // Keep this interface closed: extending UtilsRecord would make every\n // nonexistent adapter utility appear as `any`.\n awaitTxId: AwaitTxIdFn\n awaitMatch: AwaitMatchFn<T>\n}\n\n/** Owns evidence and pending work for one materialized Collection. */\nclass ElectricLifecycle<T extends Row<unknown>> {\n private readonly evidence: ElectricLifecycleEvidence = {\n seenTxids: new Set(),\n seenSnapshots: [],\n }\n\n private readonly pendingMatches = new Map<number, ElectricPendingMatch<T>>()\n private readonly pendingTxidWaits = new Map<\n number,\n {\n txId: Txid\n resolve: (value: boolean) => void\n reject: (error: Error) => void\n timeoutId: ReturnType<typeof setTimeout>\n }\n >()\n private matchBuffer: ElectricMatchBuffer<T> = {\n committedMessages: [],\n pendingMessages: [],\n }\n private nextWaiterId = 0\n private epoch = 0\n private active = false\n\n constructor(private readonly collectionId?: string) {}\n\n readonly utils: ElectricCollectionUtils<T> = {\n awaitTxId: (txId, timeout) => this.awaitTxId(txId, timeout),\n awaitMatch: (matchFn, timeout) => this.awaitMatch(matchFn, timeout),\n }\n\n start(): number {\n if (this.active) this.retire()\n this.active = true\n this.epoch++\n this.matchBuffer = { committedMessages: [], pendingMessages: [] }\n return this.epoch\n }\n\n isActive(epoch: number): boolean {\n return this.active && this.epoch === epoch\n }\n\n retire(epoch?: number): void {\n if (epoch !== undefined && !this.isActive(epoch)) return\n this.active = false\n this.epoch++\n\n for (const match of this.pendingMatches.values()) {\n clearTimeout(match.timeoutId)\n match.reject(new StreamAbortedError(this.collectionId))\n }\n this.pendingMatches.clear()\n\n for (const waiter of this.pendingTxidWaits.values()) {\n clearTimeout(waiter.timeoutId)\n waiter.reject(new StreamAbortedError(this.collectionId))\n }\n this.pendingTxidWaits.clear()\n this.matchBuffer = { committedMessages: [], pendingMessages: [] }\n this.evidence.hydratedResumeState = undefined\n }\n\n exportMeta(): ElectricSyncMeta {\n return exportElectricSyncMeta(this.evidence)\n }\n\n importMeta(meta: unknown): void {\n importElectricSyncMeta(this.evidence, meta)\n this.resolveTxidWaiters()\n }\n\n get resumeState(): ElectricResumeState | undefined {\n return this.evidence.hydratedResumeState\n }\n\n set resumeState(value: ElectricResumeState | undefined) {\n this.evidence.hydratedResumeState = value\n }\n\n publishEvidence(\n txids: ReadonlySet<Txid>,\n snapshots: ReadonlyArray<PostgresSnapshot>,\n ): void {\n txids.forEach((txid) => this.evidence.seenTxids.add(txid))\n this.evidence.seenSnapshots.push(...snapshots)\n this.resolveTxidWaiters()\n }\n\n private hasTxid(txId: Txid): boolean {\n return (\n this.evidence.seenTxids.has(txId) ||\n this.evidence.seenSnapshots.some((snapshot) =>\n isVisibleInSnapshot(txId, snapshot),\n )\n )\n }\n\n private resolveTxidWaiters(): void {\n for (const [waitId, waiter] of this.pendingTxidWaits) {\n if (!this.hasTxid(waiter.txId)) continue\n clearTimeout(waiter.timeoutId)\n this.pendingTxidWaits.delete(waitId)\n waiter.resolve(true)\n }\n }\n\n private async awaitTxId(\n txId: Txid,\n timeout: number = 15000,\n ): Promise<boolean> {\n debug(\n `${this.collectionId ? `[${this.collectionId}] ` : ``}awaitTxId called with txid %d`,\n txId,\n )\n if (typeof txId !== `number`) {\n throw new ExpectedNumberInAwaitTxIdError(typeof txId, this.collectionId)\n }\n if (this.hasTxid(txId)) return true\n\n return new Promise((resolve, reject) => {\n const waitId = this.nextWaiterId++\n const timeoutId = setTimeout(() => {\n this.pendingTxidWaits.delete(waitId)\n reject(new TimeoutWaitingForTxIdError(txId, this.collectionId))\n }, timeout)\n this.pendingTxidWaits.set(waitId, {\n txId,\n resolve,\n reject,\n timeoutId,\n })\n })\n }\n\n private async awaitMatch(\n matchFn: MatchFunction<T>,\n timeout: number = 15000,\n ): Promise<boolean> {\n debug(\n `${this.collectionId ? `[${this.collectionId}] ` : ``}awaitMatch called with custom function`,\n )\n\n for (const message of this.matchBuffer.committedMessages) {\n if (!matchFn(message)) continue\n return true\n }\n for (const message of this.matchBuffer.pendingMessages) {\n if (matchFn(message)) return this.registerMatch(matchFn, timeout, true)\n }\n return this.registerMatch(matchFn, timeout, false)\n }\n\n private registerMatch(\n matchFn: MatchFunction<T>,\n timeout: number,\n matched: boolean,\n ): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const matchId = this.nextWaiterId++\n const timeoutId = setTimeout(() => {\n this.pendingMatches.delete(matchId)\n reject(new TimeoutWaitingForMatchError(this.collectionId))\n }, timeout)\n this.pendingMatches.set(matchId, {\n matchFn,\n resolve,\n reject,\n timeoutId,\n matched,\n })\n })\n }\n\n beginMatchGeneration(messages: ReadonlyArray<Message<T>>): void {\n if (!messages.some(isMustRefetchMessage)) return\n this.matchBuffer = { committedMessages: [], pendingMessages: [] }\n for (const match of this.pendingMatches.values()) match.matched = false\n }\n\n observeMatchMessage(message: Message<T>): void {\n if (\n isChangeMessage(message) ||\n isMoveOutMessage(message) ||\n isMoveInMessage(message)\n ) {\n this.matchBuffer.pendingMessages.push(message)\n let overflow =\n this.matchBuffer.committedMessages.length +\n this.matchBuffer.pendingMessages.length -\n 1000\n if (overflow > 0) {\n const committedOverflow = Math.min(\n overflow,\n this.matchBuffer.committedMessages.length,\n )\n this.matchBuffer.committedMessages.splice(0, committedOverflow)\n overflow -= committedOverflow\n if (overflow > 0) {\n this.matchBuffer.pendingMessages.splice(0, overflow)\n }\n }\n }\n\n const epoch = this.epoch\n for (const [matchId, match] of this.pendingMatches) {\n if (match.matched) continue\n try {\n match.matched = match.matchFn(message)\n } catch (error) {\n clearTimeout(match.timeoutId)\n this.pendingMatches.delete(matchId)\n match.reject(error instanceof Error ? error : new Error(String(error)))\n }\n // Reentry can register replacement-session waiters in this same Map.\n if (!this.isActive(epoch)) return\n }\n }\n\n commitMatches(): void {\n this.matchBuffer.committedMessages.push(...this.matchBuffer.pendingMessages)\n this.matchBuffer.pendingMessages = []\n if (this.matchBuffer.committedMessages.length > 1000) {\n this.matchBuffer.committedMessages.splice(\n 0,\n this.matchBuffer.committedMessages.length - 1000,\n )\n }\n for (const [matchId, match] of this.pendingMatches) {\n if (!match.matched) continue\n clearTimeout(match.timeoutId)\n this.pendingMatches.delete(matchId)\n match.resolve(true)\n }\n }\n}\n\n/**\n * Creates Electric collection options for use with a standard Collection\n *\n * @template T - The explicit type of items in the collection (highest priority)\n * @template TSchema - The schema type for validation and type inference (second priority)\n * @template TFallback - The fallback type if no explicit or schema type is provided\n * @param config - Configuration options for the Electric collection\n * @returns Collection options with utilities\n */\n\n// Overload for when schema is provided\nexport function electricCollectionOptions<T extends StandardSchemaV1>(\n config: ElectricCollectionConfig<InferSchemaOutput<T>, T> & {\n schema: T\n },\n): Omit<\n CollectionConfig<InferSchemaOutput<T>, string | number, T>,\n `utils` | `onInsert` | `onUpdate` | `onDelete`\n> &\n Pick<\n ElectricCollectionConfig<InferSchemaOutput<T>, T>,\n `onInsert` | `onUpdate` | `onDelete`\n > & {\n id?: string\n utils: ElectricCollectionUtils<InferSchemaOutput<T>>\n schema: T\n }\n\n// Overload for when no schema is provided\nexport function electricCollectionOptions<T extends Row<unknown>>(\n config: ElectricCollectionConfig<T> & {\n schema?: never // prohibit schema\n },\n): Omit<\n CollectionConfig<T, string | number>,\n `utils` | `onInsert` | `onUpdate` | `onDelete`\n> &\n Pick<ElectricCollectionConfig<T>, `onInsert` | `onUpdate` | `onDelete`> & {\n id?: string\n utils: ElectricCollectionUtils<T>\n schema?: never // no schema in the result\n }\n\nexport function electricCollectionOptions<T extends Row<unknown>>(\n config: ElectricCollectionConfig<T, any>,\n): Omit<\n CollectionConfig<T, string | number, any, ElectricCollectionUtils<T>>,\n `utils`\n> & {\n id?: string\n utils: ElectricCollectionUtils<T>\n schema?: any\n} {\n let descriptorLifecycle = new ElectricLifecycle<T>(config.id)\n let utilityLifecycle = descriptorLifecycle\n const internalSyncMode = config.syncMode ?? `eager`\n const finalSyncMode =\n internalSyncMode === `progressive` ? `on-demand` : internalSyncMode\n const boundLifecycles = new WeakMap<object, ElectricLifecycle<T>>()\n const awaitTxId: AwaitTxIdFn = (txId, timeout) =>\n utilityLifecycle.utils.awaitTxId(txId, timeout)\n\n const awaitMatch: AwaitMatchFn<T> = (matchFn, timeout) =>\n utilityLifecycle.utils.awaitMatch(matchFn, timeout)\n\n const createSync = () =>\n createElectricSync<T>(config.shapeOptions, {\n getLifecycle: (collection) =>\n boundLifecycles.get(collection) ?? descriptorLifecycle,\n syncMode: internalSyncMode,\n collectionId: config.id,\n testHooks: config[ELECTRIC_TEST_HOOKS],\n })\n const sync = createSync()\n\n /**\n * Process matching strategy and wait for synchronization\n */\n const processMatchingStrategy = async (\n result: unknown,\n waitForTxId: AwaitTxIdFn,\n ): Promise<void> => {\n const canHaveProperties =\n (typeof result === `object` && result !== null) ||\n typeof result === `function`\n\n // Only wait if result contains txid\n if (canHaveProperties && `txid` in result) {\n const strategy = result as Exclude<MatchingStrategy, void>\n // Warn about deprecated return value pattern\n warnOnce(\n 'electric-collection-txid-return',\n '[TanStack DB] DEPRECATED: Returning { txid } from mutation handlers is deprecated and will be removed in v1.0. ' +\n 'Use `await collection.utils.awaitTxId(txid)` instead of returning { txid }. ' +\n 'See migration guide: https://tanstack.com/db/latest/docs/collections/electric-collection#persistence-handlers--synchronization',\n )\n\n const timeout = strategy.timeout\n // Handle both single txid and array of txids\n if (Array.isArray(strategy.txid)) {\n await Promise.all(\n strategy.txid.map((txid) => waitForTxId(txid, timeout)),\n )\n } else {\n await waitForTxId(strategy.txid, timeout)\n }\n }\n // If result is void/undefined, don't wait - mutation completes immediately\n }\n const getMutationAwaitTxId = (params: unknown): AwaitTxIdFn => {\n const collection = (\n params as {\n collection?: { utils?: { awaitTxId?: AwaitTxIdFn } }\n }\n ).collection\n return collection?.utils?.awaitTxId ?? awaitTxId\n }\n\n // Create wrapper handlers for direct persistence operations that handle different matching strategies\n // These wrappers process deprecated return values but don't pass them through\n const wrappedOnInsert = config.onInsert\n ? async (\n params: InsertMutationFnParams<\n any,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ): Promise<void> => {\n const handlerResult = await config.onInsert!(params)\n await processMatchingStrategy(\n handlerResult,\n getMutationAwaitTxId(params),\n )\n }\n : undefined\n\n const wrappedOnUpdate = config.onUpdate\n ? async (\n params: UpdateMutationFnParams<\n any,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ): Promise<void> => {\n const handlerResult = await config.onUpdate!(params)\n await processMatchingStrategy(\n handlerResult,\n getMutationAwaitTxId(params),\n )\n }\n : undefined\n\n const wrappedOnDelete = config.onDelete\n ? async (\n params: DeleteMutationFnParams<\n any,\n string | number,\n ElectricCollectionUtils<T>\n >,\n ): Promise<void> => {\n const handlerResult = await config.onDelete!(params)\n await processMatchingStrategy(\n handlerResult,\n getMutationAwaitTxId(params),\n )\n }\n : undefined\n\n // Extract standard Collection config properties\n const {\n shapeOptions: _shapeOptions,\n onInsert: _onInsert,\n onUpdate: _onUpdate,\n onDelete: _onDelete,\n ...restConfig\n } = config\n\n const utilityTemplate: ElectricCollectionUtils<T> = {\n awaitTxId,\n awaitMatch,\n }\n const consumeDescriptorLifecycle = (): ElectricLifecycle<T> => {\n const lifecycle = descriptorLifecycle\n descriptorLifecycle = new ElectricLifecycle<T>(config.id)\n utilityLifecycle = lifecycle\n return lifecycle\n }\n const createBoundSync = (\n source: SyncConfig<T>,\n utilities: object,\n ): SyncConfig<T> => {\n const lifecycle = consumeDescriptorLifecycle()\n let collectionKey: object | undefined\n Object.assign(utilities, lifecycle.utils)\n\n const boundSync: SyncConfig<T> = {\n ...source,\n sync: (params) => {\n // A copied materialized config may delegate through an older binding.\n // The outermost binding owns this collection; inner wrappers only run\n // the source sync and must not retarget either owner's lifecycle.\n if (!boundLifecycles.has(params.collection)) {\n collectionKey = params.collection\n boundLifecycles.set(params.collection, lifecycle)\n }\n return source.sync(params)\n },\n exportSyncMeta: () => lifecycle.exportMeta(),\n importSyncMeta: (meta) => lifecycle.importMeta(meta),\n mergeSyncMeta: mergeElectricSyncMeta,\n }\n return withCollectionSyncConfigCleanup(boundSync, () => {\n lifecycle.retire()\n if (collectionKey) boundLifecycles.delete(collectionKey)\n })\n }\n const syncTemplate = withCollectionSyncConfigFactory(\n {\n ...sync,\n exportSyncMeta: () => descriptorLifecycle.exportMeta(),\n importSyncMeta: (meta) => descriptorLifecycle.importMeta(meta),\n mergeSyncMeta: mergeElectricSyncMeta,\n },\n createBoundSync,\n )\n const options = {\n ...restConfig,\n syncMode: finalSyncMode,\n sync: syncTemplate,\n onInsert: wrappedOnInsert,\n onUpdate: wrappedOnUpdate,\n onDelete: wrappedOnDelete,\n utils: utilityTemplate,\n }\n Object.defineProperty(options, `utils`, {\n enumerable: true,\n get: () => ({ ...utilityTemplate }),\n })\n\n return withCollectionConfigFactory(options, () =>\n (\n electricCollectionOptions as (\n nextConfig: ElectricCollectionConfig<T, any>,\n ) => typeof options\n )(config),\n )\n}\n\n/**\n * Internal function to create ElectricSQL sync configuration\n */\nfunction createElectricSync<T extends Row<unknown>>(\n shapeOptions: ShapeStreamOptions<GetExtensions<T>>,\n options: {\n syncMode: ElectricSyncMode\n getLifecycle: (collection: object) => ElectricLifecycle<T>\n collectionId?: string\n testHooks?: ElectricTestHooks\n },\n): SyncConfig<T> {\n const { getLifecycle, syncMode, collectionId, testHooks } = options\n\n let relationSchema: string | undefined\n\n const createTagState = () => {\n const tagCache = new Map<MoveTag, ParsedMoveTag>()\n\n // Parses a tag string into a ParsedMoveTag.\n // It memoizes the result parsed tag such that future calls\n // for the same tag string return the same ParsedMoveTag array.\n const parseTag = (tag: MoveTag): ParsedMoveTag => {\n const cachedTag = tagCache.get(tag)\n if (cachedTag) {\n return cachedTag\n }\n\n const parsedTag = parseTagString(tag)\n tagCache.set(tag, parsedTag)\n return parsedTag\n }\n\n // Tag tracking state\n const rowTagSets = new Map<RowId, Set<MoveTag>>()\n const tagIndex: TagIndex = []\n let tagLength: number | undefined = undefined\n\n // DNF state: active_conditions are per-row, disjunct_positions are global\n // (fixed by the shape's WHERE clause, derived once from the first tagged message).\n const rowActiveConditions = new Map<RowId, ActiveConditions>()\n let disjunctPositions: DisjunctPositions | undefined = undefined\n\n /**\n * Initialize the tag index with the correct length\n */\n const initializeTagIndex = (length: number): void => {\n if (tagIndex.length < length) {\n // Extend the index array to the required length\n for (let i = tagIndex.length; i < length; i++) {\n tagIndex[i] = new Map()\n }\n }\n }\n\n /**\n * Add tags to a row and update the tag index\n */\n const addTagsToRow = (\n tags: Array<MoveTag>,\n rowId: RowId,\n rowTagSet: Set<MoveTag>,\n ): void => {\n for (const tag of tags) {\n const parsedTag = parseTag(tag)\n\n // Infer tag length from first tag\n if (tagLength === undefined) {\n tagLength = getTagLength(parsedTag)\n initializeTagIndex(tagLength)\n }\n\n // Validate tag length matches\n const currentTagLength = getTagLength(parsedTag)\n if (currentTagLength !== tagLength) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Tag length mismatch: expected ${tagLength}, got ${currentTagLength}`,\n )\n continue\n }\n\n rowTagSet.add(tag)\n addTagToIndex(parsedTag, rowId, tagIndex, tagLength)\n }\n }\n\n /**\n * Remove tags from a row and update the tag index\n */\n const removeTagsFromRow = (\n removedTags: Array<MoveTag>,\n rowId: RowId,\n rowTagSet: Set<MoveTag>,\n ): void => {\n if (tagLength === undefined) {\n return\n }\n\n for (const tag of removedTags) {\n const parsedTag = parseTag(tag)\n rowTagSet.delete(tag)\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength)\n // We aggresively evict the tag from the cache\n // if this tag is shared with another row\n // and is not removed from that other row\n // then next time we encounter the tag it will be parsed again\n tagCache.delete(tag)\n }\n }\n\n /**\n * Process tags for a change message (add and remove tags)\n */\n const processTagsForChangeMessage = (\n tags: Array<MoveTag> | undefined,\n removedTags: Array<MoveTag> | undefined,\n rowId: RowId,\n activeConditions?: ActiveConditions,\n ): Set<MoveTag> => {\n // Initialize tag set for this row if it doesn't exist (needed for checking deletion)\n if (!rowTagSets.has(rowId)) {\n rowTagSets.set(rowId, new Set())\n }\n const rowTagSet = rowTagSets.get(rowId)!\n\n // Add new tags\n if (tags) {\n addTagsToRow(tags, rowId, rowTagSet)\n\n // Derive disjunct positions once — they are fixed by the shape's WHERE clause.\n if (disjunctPositions === undefined) {\n const parsedTags = tags.map(parseTag)\n disjunctPositions = deriveDisjunctPositions(parsedTags)\n }\n }\n\n // Remove tags\n if (removedTags) {\n removeTagsFromRow(removedTags, rowId, rowTagSet)\n }\n\n // Store active conditions if provided (overwrite on re-send)\n if (activeConditions && activeConditions.length > 0) {\n rowActiveConditions.set(rowId, [...activeConditions])\n }\n\n return rowTagSet\n }\n\n /**\n * Clear all tag tracking state (used when truncating)\n */\n const clearTagTrackingState = (): void => {\n rowTagSets.clear()\n tagIndex.length = 0\n tagLength = undefined\n rowActiveConditions.clear()\n disjunctPositions = undefined\n }\n\n /**\n * Remove all tags for a row from both the tag set and the index\n * Used when a row is deleted\n */\n const clearTagsForRow = (rowId: RowId): void => {\n if (tagLength === undefined) {\n return\n }\n\n const rowTagSet = rowTagSets.get(rowId)\n if (!rowTagSet) {\n return\n }\n\n // Remove each tag from the index\n for (const tag of rowTagSet) {\n const parsedTag = parseTag(tag)\n const currentTagLength = getTagLength(parsedTag)\n if (currentTagLength === tagLength) {\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength)\n }\n tagCache.delete(tag)\n }\n\n // Remove the row from the tag sets map\n rowTagSets.delete(rowId)\n rowActiveConditions.delete(rowId)\n }\n\n /**\n * Remove matching tags from a row based on a pattern\n * Returns true if the row should be deleted (no longer visible)\n */\n const removeMatchingTagsFromRow = (\n rowId: RowId,\n pattern: MovePattern,\n ): boolean => {\n const rowTagSet = rowTagSets.get(rowId)\n if (!rowTagSet) {\n return false\n }\n\n // DNF mode: check visibility using active conditions.\n // Tag index entries are preserved so that move-in can re-activate positions.\n const activeConditions = rowActiveConditions.get(rowId)\n if (activeConditions && disjunctPositions) {\n // Set the condition at this pattern's position to false\n activeConditions[pattern.pos] = false\n\n if (!rowVisible(activeConditions, disjunctPositions)) {\n // Row is no longer visible — clean up all state including tag index\n for (const tag of rowTagSet) {\n const parsedTag = parseTag(tag)\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength!)\n tagCache.delete(tag)\n }\n rowTagSets.delete(rowId)\n rowActiveConditions.delete(rowId)\n return true\n }\n return false\n }\n\n // Simple shape (no subquery dependencies — server sends no active_conditions):\n // Remove matching tags and delete if tag set is empty\n for (const tag of rowTagSet) {\n const parsedTag = parseTag(tag)\n if (tagMatchesPattern(parsedTag, pattern)) {\n rowTagSet.delete(tag)\n removeTagFromIndex(parsedTag, rowId, tagIndex, tagLength!)\n }\n }\n\n if (rowTagSet.size === 0) {\n rowTagSets.delete(rowId)\n return true\n }\n\n return false\n }\n\n /**\n * Process move-out event: remove matching tags from rows and delete rows with empty tag sets\n */\n const processMoveOutEvent = (\n patterns: Array<MovePattern>,\n begin: () => void,\n write: (message: ChangeMessageOrDeleteKeyMessage<T>) => void,\n transactionStarted: boolean,\n onDelete: (rowId: RowId) => void,\n ): boolean => {\n if (tagLength === undefined) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Received move-out message but no tag length set yet, ignoring`,\n )\n return transactionStarted\n }\n\n let txStarted = transactionStarted\n\n // Process all patterns and collect rows to delete\n for (const pattern of patterns) {\n // Find all rows that match this pattern\n const affectedRowIds = findRowsMatchingPattern(pattern, tagIndex)\n\n for (const rowId of affectedRowIds) {\n if (removeMatchingTagsFromRow(rowId, pattern)) {\n // Delete rows with empty tag sets\n if (!txStarted) {\n begin()\n txStarted = true\n }\n\n write({\n type: `delete`,\n key: rowId,\n })\n onDelete(rowId)\n }\n }\n }\n\n return txStarted\n }\n\n /**\n * Process move-in event: re-activate conditions for rows matching the patterns.\n * This is a silent operation — no messages are emitted to the collection.\n */\n const processMoveInEvent = (patterns: Array<MovePattern>): void => {\n if (tagLength === undefined) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Received move-in message but no tag length set yet, ignoring`,\n )\n return\n }\n\n for (const pattern of patterns) {\n const affectedRowIds = findRowsMatchingPattern(pattern, tagIndex)\n\n for (const rowId of affectedRowIds) {\n const activeConditions = rowActiveConditions.get(rowId)\n if (activeConditions) {\n activeConditions[pattern.pos] = true\n }\n }\n }\n }\n\n return {\n hasTags: () => tagLength !== undefined,\n processTagsForChangeMessage,\n clearTagTrackingState,\n clearTagsForRow,\n processMoveOutEvent,\n processMoveInEvent,\n }\n }\n // Tags belong to a collection, and survive a compatible resume of that\n // collection. Reusing an options descriptor must not share visibility.\n const collectionTags = new WeakMap<\n object,\n ReturnType<typeof createTagState>\n >()\n\n return {\n getSyncMetadata: () => ({\n relation: shapeOptions.params?.table\n ? [relationSchema || `public`, shapeOptions.params.table]\n : undefined,\n }),\n sync: (params: Parameters<SyncConfig<T>[`sync`]>[0]) => {\n const retainsTagState = collectionTags.has(params.collection)\n let tagState = collectionTags.get(params.collection)\n if (!tagState) {\n tagState = createTagState()\n collectionTags.set(params.collection, tagState)\n }\n const {\n processTagsForChangeMessage,\n clearTagTrackingState,\n clearTagsForRow,\n processMoveOutEvent,\n processMoveInEvent,\n } = tagState\n const lifecycle = getLifecycle(params.collection)\n const lifecycleEpoch = lifecycle.start()\n const isActiveLifecycle = () => lifecycle.isActive(lifecycleEpoch)\n Object.assign(params.collection.utils, lifecycle.utils)\n\n const {\n begin,\n write,\n commit: commitSyncTransaction,\n markReady,\n markError,\n truncate,\n collection,\n metadata,\n } = params\n let commitSequence = 0\n const pendingAppliedReceipts = new Map<number, Promise<void>>()\n const commit = (signal?: AbortSignal): SyncAppliedReceipt => {\n const sequence = ++commitSequence\n const applied = commitSyncTransaction(signal)\n if (applied === true) {\n return true\n }\n pendingAppliedReceipts.set(sequence, applied)\n const removeReceipt = () => pendingAppliedReceipts.delete(sequence)\n void applied.then(removeReceipt, removeReceipt)\n return applied\n }\n const waitForCommitsAfter = async (cursor: number): Promise<void> => {\n await Promise.all(\n Array.from(pendingAppliedReceipts, ([sequence, applied]) =>\n sequence > cursor ? applied : undefined,\n ),\n )\n }\n const readPersistedResumeState = (): ElectricResumeState | undefined => {\n const persistedResumeState = metadata?.collection.get(`electric:resume`)\n return parseElectricResumeState(persistedResumeState)\n }\n\n const persistence =\n metadata === undefined\n ? null\n : validateSyncPersistenceCapability(metadata.persistence)\n const hydrateBaseline = persistence?.hydrateBaseline\n const resumeSnapshot = persistence?.resumeSnapshot\n const certifyResumeSnapshot = resumeSnapshot?.certify\n const getKeySetEvidence = resumeSnapshot?.getKeySetEvidence\n const expectCurrentCommit = resumeSnapshot?.expectCurrentCommit\n const persistedKeySetEvidence = getKeySetEvidence?.()\n\n const persistedResumeState = getNewestElectricResumeState(\n readPersistedResumeState(),\n lifecycle.resumeState,\n )\n const shapeIdentity = getStableShapeIdentity({\n url: shapeOptions.url,\n params: shapeOptions.params as Record<string, unknown> | undefined,\n })\n const hasIncompatiblePersistedResume =\n persistedResumeState?.kind === `resume` &&\n persistedResumeState.shapeId !== shapeIdentity\n // A pre-ledger `unknown` baseline cannot justify a non-initial cursor.\n // One fresh replacement establishes consistent evidence for later resumes.\n const lacksCompletePersistedKeySet =\n persistedResumeState?.kind === `resume` &&\n getKeySetEvidence !== undefined &&\n persistedKeySetEvidence?.status !== `consistent`\n const needsFullSnapshot =\n shapeOptions.offset === undefined &&\n shapeOptions.handle === undefined &&\n persistedResumeState !== undefined &&\n (persistedResumeState.kind === `reset` ||\n lacksCompletePersistedKeySet ||\n (!retainsTagState && persistedResumeState.requiresTagState !== false))\n const canUsePersistedResume =\n shapeOptions.offset === undefined &&\n shapeOptions.handle === undefined &&\n persistedResumeState?.kind === `resume` &&\n !hasIncompatiblePersistedResume &&\n // Cached rows do not contain authoritative tag/active-condition state.\n // Only a complete adapter ledger can justify a persisted cursor.\n !needsFullSnapshot\n const hasExplicitResumeOffset =\n shapeOptions.offset !== undefined && shapeOptions.offset !== `-1`\n if (!canUsePersistedResume && !hasExplicitResumeOffset) {\n clearTagTrackingState()\n }\n const receivesCompleteRows = shapeOptions.params?.replica === `full`\n const requiresKeySetCertification =\n canUsePersistedResume && certifyResumeSnapshot !== undefined\n // Eager and progressive streams that start after the initial offset can\n // only apply partial updates when the local materialization is complete.\n const requiresCompleteResume =\n syncMode !== `on-demand` &&\n (canUsePersistedResume ||\n (hasExplicitResumeOffset && !receivesCompleteRows))\n // A fresh snapshot replaces its hydrated cache; omitting the old offset\n // alone would merge rows that no longer exist on the server.\n let freshSnapshotPending =\n (syncMode === `eager` || needsFullSnapshot) &&\n !canUsePersistedResume &&\n !hasExplicitResumeOffset &&\n hydrateBaseline !== undefined\n\n // Wrap markReady to wait for test hook in progressive mode\n let progressiveReadyGate: Promise<void> | null = null\n let streamErrorVersion = 0\n const wrappedMarkReady = (\n isBuffering: boolean,\n expectedErrorVersion = streamErrorVersion,\n ) => {\n if (streamErrorVersion !== expectedErrorVersion) return\n\n // Only create gate if we're in buffering phase (first up-to-date)\n if (\n isBuffering &&\n syncMode === `progressive` &&\n testHooks?.beforeMarkingReady\n ) {\n // Create a new gate promise for this sync cycle\n progressiveReadyGate = testHooks.beforeMarkingReady()\n progressiveReadyGate.then(() => {\n if (streamErrorVersion === expectedErrorVersion) {\n markReady()\n }\n })\n } else {\n // No hook, not buffering, or already past first up-to-date\n markReady()\n }\n }\n\n // Abort controller for the stream - wraps the signal if provided\n const abortController = new AbortController()\n const forwardExternalAbort = () => abortController.abort()\n\n if (shapeOptions.signal) {\n shapeOptions.signal.addEventListener(`abort`, forwardExternalAbort, {\n once: true,\n })\n if (shapeOptions.signal.aborted) {\n abortController.abort()\n }\n }\n\n abortController.signal.addEventListener(`abort`, () => {\n lifecycle.retire(lifecycleEpoch)\n })\n\n const stream = new ShapeStream({\n ...shapeOptions,\n // Recovery needs a complete snapshot even for on-demand shapes.\n // Normal on-demand startup still subscribes to changes only.\n log:\n syncMode === `on-demand` && !needsFullSnapshot\n ? `changes_only`\n : undefined,\n // In on-demand mode, we only need the changes from the point of time the collection was created\n // so we default to `now` when there is no saved offset.\n offset:\n shapeOptions.offset ??\n (canUsePersistedResume\n ? (persistedResumeState.offset as Offset)\n : syncMode === `on-demand` && !needsFullSnapshot\n ? `now`\n : undefined),\n handle:\n shapeOptions.handle ??\n (canUsePersistedResume ? persistedResumeState.handle : undefined),\n signal: abortController.signal,\n onError: (errorParams) => {\n streamErrorVersion++\n // Note that Electric sends a 409 error on a `must-refetch` message, but the\n // ShapeStream handled this and it will not reach this handler, therefor\n // this handler will not run for a `must-refetch`.\n const initialSyncFailed = collection.status === `loading`\n if (initialSyncFailed) {\n markError(errorParams)\n }\n\n if (shapeOptions.onError) {\n return shapeOptions.onError(errorParams)\n } else {\n console.error(\n `An error occurred while syncing collection: ${collection.id}, \\n` +\n (initialSyncFailed\n ? `the initial sync has been marked as failed. \\n`\n : `the last ready snapshot has been preserved. \\n`) +\n `You can provide an 'onError' handler on the shapeOptions to handle this error, and this message will not be logged.`,\n errorParams,\n )\n }\n\n return\n },\n })\n let transactionStarted = false\n const newTxids = new Set<Txid>()\n const newSnapshots: Array<PostgresSnapshot> = []\n // Track if we've completed initial sync in progressive mode. A persisted\n // resume starts from an already-committed stream offset, so the next\n // up-to-date message must not run the initial atomic swap again.\n let hasReceivedUpToDate =\n syncMode === `progressive` && requiresCompleteResume\n // A must-refetch starts a new snapshot generation. Until its up-to-date\n // commit is applied, old Collection keys cannot make an update valid and\n // the durable resume marker must remain reset.\n let isResettingSnapshot = false\n let resetGeneration = 0\n\n // Progressive mode state\n // Helper to determine if we're buffering the initial sync\n const isBufferingInitialSync = () =>\n syncMode === `progressive` &&\n !hasReceivedUpToDate &&\n !isResettingSnapshot\n const bufferedMessages: Array<Message<T>> = [] // Buffer change messages during initial sync\n // Progressive subset rows are provisional: the initial atomic swap\n // normally discards them. Retain one only when a later stream update\n // needs that full row as its baseline.\n const progressiveSnapshotRows = new Map<string | number, Message<T>>()\n\n // Presence spans the open source transaction and persisted callbacks\n // whose FIFO receipts have not applied yet. Later callbacks must see\n // those staged writes even though persistence has not replayed them into\n // core. Once the newest receipt applies, syncedData is authoritative.\n const pendingPresence = new Map<string | number, boolean>()\n let usesBaseline = true\n let pendingPresenceRevision = 0\n\n const recordPendingPresence = (\n rowId: string | number,\n present: boolean,\n ) => {\n pendingPresenceRevision++\n pendingPresence.set(rowId, present)\n }\n\n const recordPendingTruncate = () => {\n pendingPresenceRevision++\n pendingPresence.clear()\n progressiveSnapshotRows.clear()\n usesBaseline = false\n }\n\n const commitSourceTransaction = (): SyncAppliedReceipt => {\n const committedPresenceRevision = pendingPresenceRevision\n const applied = commit()\n if (metadata?.persistence) {\n const retireAppliedPresence = () => {\n if (pendingPresenceRevision === committedPresenceRevision) {\n pendingPresence.clear()\n usesBaseline = true\n }\n }\n if (applied === true) retireAppliedPresence()\n else void applied.then(retireAppliedPresence, () => undefined)\n }\n return applied\n }\n\n const beginSourceTransaction = () => {\n if (metadata?.persistence) begin({ immediate: true })\n else begin()\n }\n\n // Track keys that have been synced to handle overlapping subset queries.\n // When multiple subset queries return the same row, the server sends `insert`\n // for each response. We convert subsequent inserts to updates to avoid\n // duplicate key errors when the row's data has changed between requests.\n const syncedKeys = new Set<string | number>()\n let resumeInvalid = false\n\n const stageResumeMetadata = () => {\n if (!isActiveLifecycle() || resumeInvalid) {\n return\n }\n const shapeHandle = stream.shapeHandle\n const lastOffset = stream.lastOffset\n if (!shapeHandle || lastOffset === `-1`) {\n return\n }\n\n const resumeState: ElectricResumeState = {\n kind: `resume`,\n offset: lastOffset,\n handle: shapeHandle,\n shapeId: shapeIdentity,\n updatedAt: Date.now(),\n requiresTagState: tagState.hasTags(),\n }\n lifecycle.resumeState = resumeState\n metadata?.collection.set(`electric:resume`, resumeState)\n }\n\n const commitResetResumeMetadataImmediately = (\n expectInResumeSnapshot = false,\n ) => {\n const resetState: ElectricResumeState = {\n kind: `reset`,\n updatedAt: Date.now(),\n }\n lifecycle.resumeState = resetState\n\n if (metadata) {\n begin({ immediate: true })\n metadata.collection.set(`electric:resume`, resetState)\n if (expectInResumeSnapshot) {\n expectCurrentCommit?.()\n }\n commit()\n }\n }\n\n if (\n hasIncompatiblePersistedResume ||\n (needsFullSnapshot && persistedResumeState.kind === `resume`)\n ) {\n // This reset is part of the current runtime's startup decision. The\n // persisted wrapper may commit it before loading the atomic baseline,\n // so carry ownership of exactly this generation into certification.\n commitResetResumeMetadataImmediately(true)\n }\n\n /**\n * Process a change message: handle tags and write the mutation\n */\n const processChangeMessage = (changeMessage: Message<T>) => {\n if (!isChangeMessage(changeMessage)) {\n return\n }\n\n // Process tags if present\n const tags = changeMessage.headers.tags\n const removedTags = changeMessage.headers.removed_tags\n const hasTags = tags || removedTags\n\n // Extract active_conditions from headers (DNF support)\n const activeConditions = changeMessage.headers.active_conditions as\n | ActiveConditions\n | undefined\n\n const rowId = collection.getKeyFromItem(changeMessage.value)\n const operation = changeMessage.headers.operation\n\n // Track synced keys and handle overlapping subset queries.\n // When multiple subset queries return the same row, the server sends\n // `insert` for each response. We convert subsequent inserts to updates\n // to avoid duplicate key errors when the row's data has changed.\n const isDelete = operation === `delete`\n const isDuplicateInsert =\n operation === `insert` && syncedKeys.has(rowId)\n\n if (isDelete) {\n syncedKeys.delete(rowId)\n } else {\n syncedKeys.add(rowId)\n }\n\n if (isDelete) {\n clearTagsForRow(rowId)\n } else if (hasTags) {\n processTagsForChangeMessage(\n tags,\n removedTags,\n rowId,\n activeConditions,\n )\n }\n\n write({\n type: isDuplicateInsert ? `update` : operation,\n value: changeMessage.value,\n // Include the primary key and relation info in the metadata\n metadata: {\n ...changeMessage.headers,\n },\n })\n }\n\n // Create deduplicated loadSubset wrapper for non-eager modes\n // This prevents redundant snapshot requests when multiple concurrent\n // live queries request overlapping or subset predicates\n const loadSubsetDedupe = createLoadSubsetDedupe({\n stream,\n syncMode,\n isBufferingInitialSync,\n begin,\n write,\n commit,\n getCommitCursor: () => commitSequence,\n waitForCommitsAfter,\n recordSnapshotRow: (row, message) => {\n recordPendingPresence(collection.getKeyFromItem(row), true)\n progressiveSnapshotRows.set(collection.getKeyFromItem(row), message)\n },\n collectionId,\n // Pass the columnMapper's encode function to transform column names\n // (e.g., camelCase to snake_case) when compiling SQL for subset queries\n encodeColumnName: shapeOptions.columnMapper?.encode,\n // Pass abort signal so requestSnapshot errors can be ignored during cleanup\n signal: abortController.signal,\n })\n\n const resumeKeysPromise =\n requiresCompleteResume || freshSnapshotPending\n ? hydrateBaseline\n ? (async () => {\n await hydrateBaseline()\n const currentKeySetEvidence = getKeySetEvidence?.()\n if (\n canUsePersistedResume &&\n currentKeySetEvidence?.status !== `consistent`\n ) {\n throw new Error(\n `Electric persisted resume baseline could not be certified during hydration`,\n )\n }\n })()\n : undefined\n : requiresKeySetCertification\n ? (async () => {\n await certifyResumeSnapshot()\n const currentKeySetEvidence = getKeySetEvidence?.()\n if (currentKeySetEvidence?.status !== `consistent`) {\n throw new Error(\n `Electric persisted resume baseline could not be certified`,\n )\n }\n })()\n : undefined\n let areResumeKeysReady = !resumeKeysPromise\n const pendingResumeBatches: Array<Array<Message<T>>> = []\n let unsubscribeStream: () => void = () => {}\n\n const invalidateResume = () => {\n resumeInvalid = true\n if (transactionStarted) {\n const cancellation = new AbortController()\n cancellation.abort()\n commit(cancellation.signal)\n transactionStarted = false\n }\n syncedKeys.clear()\n newTxids.clear()\n newSnapshots.length = 0\n commitResetResumeMetadataImmediately()\n streamErrorVersion++\n unsubscribeStream()\n abortController.abort()\n markError(\n new Error(\n `Electric resume state referenced an unseen row; a full snapshot is required`,\n ),\n )\n }\n\n const processMessages = (messages: Array<Message<T>>): void => {\n if (!isActiveLifecycle() || resumeInvalid) {\n return\n }\n\n if (freshSnapshotPending) {\n freshSnapshotPending = false\n beginSourceTransaction()\n transactionStarted = true\n truncate()\n recordPendingTruncate()\n syncedKeys.clear()\n clearTagTrackingState()\n isResettingSnapshot = true\n resetGeneration++\n }\n\n // Without persistence, core owns pending source transactions and can\n // rebuild this callback's presence overlay from them. Persistence owns\n // queued source transactions until their FIFO turn, so retain the\n // overlay across callbacks instead. A queued truncate still fences off\n // the previous snapshot below.\n if (!metadata?.persistence && !transactionStarted) {\n pendingPresence.clear()\n usesBaseline = true\n for (const pending of collection._state.pendingSyncedTransactions) {\n if (pending.truncate) {\n pendingPresence.clear()\n usesBaseline = false\n }\n for (const operation of pending.operations) {\n pendingPresence.set(operation.key, operation.type !== `delete`)\n }\n }\n for (const message of bufferedMessages) {\n if (isChangeMessage(message)) {\n pendingPresence.set(\n collection.getKeyFromItem(message.value),\n message.headers.operation !== `delete`,\n )\n }\n }\n }\n\n // Track commit point type - up-to-date takes precedence as it also triggers progressive mode atomic swap\n let commitPoint: `up-to-date` | `subset-end` | null = null\n\n lifecycle.beginMatchGeneration(messages)\n\n for (const message of messages) {\n lifecycle.observeMatchMessage(message)\n // A match predicate can synchronously clean up and restart sync.\n // Nothing after that boundary belongs to the replacement session.\n if (!isActiveLifecycle()) return\n\n // Check for txids in the message and add them to our store\n // Skip during buffered initial sync in progressive mode (txids will be extracted during atomic swap)\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), track txids\n // to avoid losing them when messages are written to the existing transaction.\n if (\n hasTxids(message) &&\n (!isBufferingInitialSync() || transactionStarted)\n ) {\n message.headers.txids?.forEach((txid) => newTxids.add(txid))\n }\n\n if (isChangeMessage(message)) {\n const rowId = collection.getKeyFromItem(message.value)\n const operation = message.headers.operation\n const hasKnownRow =\n pendingPresence.get(rowId) ??\n (usesBaseline && collection._state.syncedData.has(rowId))\n if (operation === `update` && !hasKnownRow) {\n // Validate after all earlier events, including tag move-outs.\n // Cancel staged writes before publishing any part of an invalid\n // resumed callback; the next lifecycle must take a full snapshot.\n if (requiresCompleteResume && !isResettingSnapshot) {\n invalidateResume()\n return\n }\n if (!receivesCompleteRows) continue\n }\n recordPendingPresence(rowId, operation !== `delete`)\n if (operation !== `update`) {\n progressiveSnapshotRows.delete(rowId)\n }\n }\n\n if (isChangeMessage(message)) {\n // Check if the message contains schema information\n const schema = message.headers.schema\n if (schema && typeof schema === `string`) {\n // Store the schema for future use if it's a valid string\n relationSchema = schema\n }\n\n // In buffered initial sync of progressive mode, buffer messages instead of writing\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), write\n // directly to it instead of buffering. This prevents orphan transactions.\n if (isBufferingInitialSync() && !transactionStarted) {\n if (message.headers.operation === `update`) {\n const rowId = collection.getKeyFromItem(message.value)\n const snapshotRow = progressiveSnapshotRows.get(rowId)\n if (snapshotRow) {\n bufferedMessages.push(snapshotRow)\n progressiveSnapshotRows.delete(rowId)\n }\n }\n bufferedMessages.push(message)\n } else {\n // Normal processing: write changes immediately\n if (!transactionStarted) {\n beginSourceTransaction()\n transactionStarted = true\n }\n\n processChangeMessage(message)\n }\n } else if (isSnapshotEndMessage(message)) {\n // Track postgres snapshot metadata for resolving awaiting mutations\n // Skip during buffered initial sync (will be extracted during atomic swap)\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), track snapshots\n // to avoid losing them when messages are written to the existing transaction.\n if (!isBufferingInitialSync() || transactionStarted) {\n newSnapshots.push(parseSnapshotMessage(message))\n }\n } else if (isUpToDateMessage(message)) {\n // up-to-date takes precedence - also triggers progressive mode atomic swap\n commitPoint = `up-to-date`\n } else if (isSubsetEndMessage(message)) {\n // subset-end triggers commit but not progressive mode atomic swap\n if (commitPoint !== `up-to-date`) {\n commitPoint = `subset-end`\n }\n } else if (isMoveOutMessage(message)) {\n // Handle move-out event: buffer if buffering, otherwise process immediately\n // EXCEPTION: If a transaction is already started (e.g., from must-refetch), process\n // immediately to avoid orphan transactions.\n if (isBufferingInitialSync() && !transactionStarted) {\n bufferedMessages.push(message)\n } else {\n // Normal processing: process move-out immediately\n transactionStarted = processMoveOutEvent(\n message.headers.patterns,\n beginSourceTransaction,\n write,\n transactionStarted,\n (rowId) => {\n recordPendingPresence(rowId, false)\n syncedKeys.delete(rowId)\n },\n )\n }\n } else if (isMoveInMessage(message)) {\n // Handle move-in event: re-activate conditions for matching rows.\n // Buffer if buffering, otherwise process immediately.\n if (isBufferingInitialSync() && !transactionStarted) {\n bufferedMessages.push(message)\n } else {\n processMoveInEvent(message.headers.patterns)\n }\n } else if (isMustRefetchMessage(message)) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Received must-refetch message, starting transaction with truncate`,\n )\n\n commitResetResumeMetadataImmediately()\n\n // Start a transaction and truncate the collection\n if (!transactionStarted) {\n beginSourceTransaction()\n transactionStarted = true\n }\n\n truncate()\n\n // Clear tag tracking state\n clearTagTrackingState()\n\n // Clear synced keys tracking since we're starting fresh\n syncedKeys.clear()\n recordPendingTruncate()\n isResettingSnapshot = true\n resetGeneration++\n\n // Reset the loadSubset deduplication state since we're starting fresh\n // This ensures that previously loaded predicates don't prevent refetching after truncate\n loadSubsetDedupe?.reset()\n\n // Reset flags so we continue accumulating changes until next up-to-date\n commitPoint = null\n hasReceivedUpToDate = false // Reset for progressive mode (isBufferingInitialSync will reflect this)\n bufferedMessages.length = 0 // Clear buffered messages\n progressiveSnapshotRows.clear()\n }\n }\n\n // A subset completion cannot publish a partial cold-recovery snapshot.\n if (\n needsFullSnapshot &&\n isResettingSnapshot &&\n commitPoint === `subset-end`\n )\n return\n\n if (commitPoint !== null) {\n let applied: SyncAppliedReceipt = true\n const wasBufferingInitialSync = isBufferingInitialSync()\n const finishesReset =\n isResettingSnapshot && commitPoint === `up-to-date`\n const finishingResetGeneration = resetGeneration\n // PROGRESSIVE MODE: Atomic swap on first up-to-date (not subset-end)\n // EXCEPTION: Skip atomic swap if a transaction is already started (e.g., from must-refetch).\n // In that case, do a normal commit to properly close the existing transaction.\n if (\n isBufferingInitialSync() &&\n commitPoint === `up-to-date` &&\n !transactionStarted\n ) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Progressive mode: Performing atomic swap with ${bufferedMessages.length} buffered messages`,\n )\n\n // Start atomic swap transaction\n beginSourceTransaction()\n\n // Truncate to clear all snapshot data\n truncate()\n\n // Clear tag tracking state for atomic swap\n clearTagTrackingState()\n\n // Clear synced keys tracking for atomic swap\n syncedKeys.clear()\n\n // Apply all buffered change messages and extract txids/snapshots\n for (const bufferedMsg of bufferedMessages) {\n if (isChangeMessage(bufferedMsg)) {\n processChangeMessage(bufferedMsg)\n\n // Extract txids from buffered messages (will be committed to store after transaction)\n if (hasTxids(bufferedMsg)) {\n bufferedMsg.headers.txids?.forEach((txid) =>\n newTxids.add(txid),\n )\n }\n } else if (isSnapshotEndMessage(bufferedMsg)) {\n // Extract snapshots from buffered messages (will be committed to store after transaction)\n newSnapshots.push(parseSnapshotMessage(bufferedMsg))\n } else if (isMoveOutMessage(bufferedMsg)) {\n // Process buffered move-out messages during atomic swap\n processMoveOutEvent(\n bufferedMsg.headers.patterns,\n begin,\n write,\n // The swap already opened a transaction, even though the\n // normal-stream transactionStarted flag is still false.\n true,\n (rowId) => {\n recordPendingPresence(rowId, false)\n syncedKeys.delete(rowId)\n },\n )\n } else if (isMoveInMessage(bufferedMsg)) {\n // Process buffered move-in messages during atomic swap\n processMoveInEvent(bufferedMsg.headers.patterns)\n }\n }\n\n // Commit the atomic swap\n stageResumeMetadata()\n applied = commitSourceTransaction()\n\n // Exit buffering phase by marking that we've received up-to-date\n // isBufferingInitialSync() will now return false\n bufferedMessages.length = 0\n progressiveSnapshotRows.clear()\n\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}Progressive mode: Atomic swap complete, now in normal sync mode`,\n )\n } else {\n // Normal mode or on-demand: commit transaction if one was started\n // Both up-to-date and subset-end trigger a commit\n if (transactionStarted) {\n if (!isResettingSnapshot || finishesReset) {\n stageResumeMetadata()\n }\n applied = commitSourceTransaction()\n transactionStarted = false\n } else if (commitPoint === `up-to-date` && metadata) {\n beginSourceTransaction()\n stageResumeMetadata()\n applied = commitSourceTransaction()\n }\n }\n const readyErrorVersion = streamErrorVersion\n if (applied === true) {\n wrappedMarkReady(wasBufferingInitialSync, readyErrorVersion)\n } else {\n void applied.then(\n () =>\n wrappedMarkReady(wasBufferingInitialSync, readyErrorVersion),\n (error: unknown) => {\n if (!isActiveLifecycle() || abortController.signal.aborted) {\n return\n }\n streamErrorVersion++\n unsubscribeStream()\n abortController.abort()\n if (collection.status !== `error`) markError(error)\n },\n )\n }\n\n if (finishesReset) {\n const finishReset = () => {\n if (resetGeneration === finishingResetGeneration) {\n isResettingSnapshot = false\n }\n }\n if (applied === true) {\n finishReset()\n } else {\n void applied.then(finishReset, () => undefined)\n }\n }\n\n // Track that we've received the first up-to-date for progressive mode\n if (commitPoint === `up-to-date`) {\n hasReceivedUpToDate = true\n }\n\n // Stream evidence is the acknowledgement boundary used by mutation\n // handlers. It must publish before a parked applied receipt or the\n // optimistic transaction and its acknowledgement can deadlock.\n if (newTxids.size > 0) {\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}new txids synced from pg %O`,\n Array.from(newTxids),\n )\n }\n newSnapshots.forEach((snapshot) =>\n debug(\n `${collectionId ? `[${collectionId}] ` : ``}new snapshot synced from pg %o`,\n snapshot,\n ),\n )\n lifecycle.publishEvidence(newTxids, newSnapshots)\n newTxids.clear()\n newSnapshots.length = 0\n lifecycle.commitMatches()\n }\n }\n\n unsubscribeStream = stream.subscribe((messages: Array<Message<T>>) => {\n if (!areResumeKeysReady) {\n pendingResumeBatches.push([...messages])\n return\n }\n processMessages(messages)\n })\n\n if (!areResumeKeysReady && resumeKeysPromise) {\n void resumeKeysPromise.then(\n () => {\n if (abortController.signal.aborted) return\n\n areResumeKeysReady = true\n\n const queuedBatches = pendingResumeBatches.splice(0)\n queuedBatches.forEach(processMessages)\n },\n (error: unknown) => {\n if (abortController.signal.aborted) return\n\n pendingResumeBatches.length = 0\n resumeInvalid = true\n commitResetResumeMetadataImmediately()\n streamErrorVersion++\n unsubscribeStream()\n abortController.abort()\n markError(error)\n },\n )\n }\n\n // Return the deduplicated loadSubset if available (on-demand or progressive mode)\n // The loadSubset method is auto-bound, so it can be safely returned directly\n return {\n loadSubset: loadSubsetDedupe?.loadSubset,\n cleanup: () => {\n shapeOptions.signal?.removeEventListener(\n `abort`,\n forwardExternalAbort,\n )\n // Unsubscribe from the stream\n unsubscribeStream()\n // Abort the abort controller to stop the stream\n abortController.abort()\n pendingResumeBatches.length = 0\n // Reset deduplication tracking so collection can load fresh data if restarted\n loadSubsetDedupe?.reset()\n lifecycle.retire(lifecycleEpoch)\n },\n }\n },\n }\n}\n"],"names":["parseTag","parseTagString","persistedResumeState"],"mappings":";;;;;;;AAwEA,MAAM,QAAQ,YAAY,MAAM,gBAAgB;AAKzC,MAAM,6CAA6B,mBAAmB;AAyD7D,SAAS,uBACP,UACkB;AAClB,QAAM,SAAS,SAAS;AACxB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,GAAI,SAAS,EAAE,OAAA,IAAW,CAAA;AAAA,IAC1B,WAAW,MAAM,KAAK,SAAS,SAAS,EAAE,KAAK,CAAC,GAAG,MAAM,IAAI,CAAC;AAAA,EAAA;AAElE;AAEA,SAAS,uBACP,UACA,MACM;AACN,QAAM,SAAS,sBAAsB,IAAI;AACzC,MAAI,CAAC,OAAQ;AAEb,WAAS,sBAAsB,OAAO;AACtC,WAAS,YAAY,IAAI,IAAI,OAAO,SAAS;AAC/C;AAEA,SAAS,yBACP,OACiC;AACjC,MAAI,CA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