@pgxsinkit/react 0.1.32 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,10 +1,127 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/create-hooks.tsx"],
3
+ "sources": ["../src/create-hooks.tsx", "../../client/src/index.ts", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/entity.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/column-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/column.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/table.utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/table.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/subquery.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/tracing-utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/tracing.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/view-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/sql.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/array.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/codecs.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/logger.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/count.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/query-promise.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/count.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/query.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/foreign-keys.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/int.common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/bigint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/bigserial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/boolean.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/char.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/cidr.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/custom.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/date.common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/date.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/double-precision.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/inet.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/integer.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/interval.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/json.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/jsonb.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/line.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/macaddr.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/macaddr8.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/numeric.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/point.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/real.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/serial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/smallint.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/smallserial.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/text.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/time.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/timestamp.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/uuid.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/varchar.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/columns/all.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/casing.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/table.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view-common.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/utils.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/alias.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/selection-proxy.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/delete.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/delete.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/query-builders/query-builder.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view-base.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/errors.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/expressions/conditions.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/sql/expressions/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/relations.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/dialect.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/insert.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/insert.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/query.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/raw.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/raw.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/refresh-materialized-view.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/select.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/query-builders/update.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/update.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/db.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/cache/core/cache.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/async/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/session.js", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pglite/driver.js", "../../contracts/src/apply-strategy.ts", "../../contracts/src/common.ts", "../../../node_modules/.bun/drizzle-orm@1.0.0-rc.4+1d449f410c91d594/node_modules/drizzle-orm/pg-core/view.js", "../../contracts/src/config.ts", "../../../node_modules/drizzle-orm/utils.js", "../../contracts/src/registry.ts", "../../contracts/src/sql-identifier.ts", "../../contracts/src/mutation.ts", "../../contracts/src/sql-defaults.ts", "../../contracts/src/supabase-rls.ts", "../../client/src/debug.ts", "../../client/src/sync/copy.ts", "../../client/src/sync/drizzle-executor.ts", "../../client/src/sync/apply.ts", "../../client/src/sync/metadata-tables.ts", "../../client/src/schema.ts", "../../client/src/local-tables.ts", "../../client/src/local-store.ts", "../../client/src/mutation-state.ts", "../../client/src/mutation.ts", "../../client/src/sync-auth.ts", "../../client/src/sync/index.ts", "../../client/src/sync/shape-inbox.ts", "../../client/src/worker/live-diff.ts", "../src/remap-live-row.ts"],
4
4
  "sourcesContent": [
5
- "import type { LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport type { ClientPGlite, SyncClient } from \"@pgxsinkit/client\";\nimport type { SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\n/**\n * Minimal interface satisfied by every Drizzle select/query builder.\n * Calling `.toSQL()` extracts the SQL string and positional params without\n * executing the query, so they can be fed into PGlite's live query API.\n */\ninterface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n}\n\n/**\n * Creates a set of React hooks and a context provider bound to a specific\n * `SyncTableRegistry` type. Call this once at the module level in your app:\n *\n * ```ts\n * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows } =\n * createSyncClientHooks<typeof mySyncRegistry>();\n * ```\n */\nexport function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {\n const SyncClientContext = createContext<SyncClient<TRegistry> | null>(null);\n\n // ─── Provider ────────────────────────────────────────────────────────────\n\n function SyncClientProvider({ client, children }: { client: SyncClient<TRegistry> | null; children: ReactNode }) {\n return <SyncClientContext.Provider value={client}>{children}</SyncClientContext.Provider>;\n }\n\n function useSyncClient(): SyncClient<TRegistry> {\n const client = useContext(SyncClientContext);\n if (client == null) {\n throw new Error(\"[pgxsinkit] useSyncClient must be called inside <SyncClientProvider>\");\n }\n return client;\n }\n\n // ─── Raw SQL live hooks ───────────────────────────────────────────────────\n\n function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: {\n params?: readonly unknown[];\n ready?: boolean;\n /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */\n pglite?: ClientPGlite;\n },\n ): { rows: TRow[]; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n const pglite = options?.pglite ?? contextClient?.pglite;\n const ready = options?.ready ?? true;\n\n const paramsKey = JSON.stringify(options?.params ?? []);\n const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);\n\n const [state, setState] = useState<{ rows: TRow[]; loading: boolean; error: Error | null }>({\n rows: [],\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || pglite == null) {\n setState({ rows: [], loading: ready, error: null });\n return;\n }\n\n let active = true;\n let liveQuery: LiveQuery<TRow> | undefined;\n let listener: ((results: LiveQueryResults<TRow>) => void) | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n void pglite.live\n .query<TRow>(query, stableParams)\n .then((registered: LiveQuery<TRow>) => {\n if (!active) return registered.unsubscribe();\n liveQuery = registered;\n setState({ rows: registered.initialResults.rows, loading: false, error: null });\n listener = (results) => {\n if (active) setState({ rows: results.rows, loading: false, error: null });\n };\n registered.subscribe(listener);\n return undefined;\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n rows: [],\n loading: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n if (liveQuery) void liveQuery.unsubscribe(listener);\n };\n }, [pglite, query, ready, stableParams]);\n\n return state;\n }\n\n function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },\n ): { row: TRow | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveRows<TRow>(query, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n // ─── Drizzle typed live hooks ─────────────────────────────────────────────\n\n /**\n * Reactive query using a Drizzle select builder. The builder is re-created\n * whenever `deps` changes (same contract as `useEffect`).\n *\n * ```ts\n * const { rows } = useLiveDrizzleRows(\n * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),\n * [],\n * );\n * // rows is fully typed from the view definition — no casts needed\n * ```\n */\n function useLiveDrizzleRows<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): { rows: TRows; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n\n const sqlObj = useMemo(\n () => (contextClient != null ? buildQuery(contextClient).toSQL() : null),\n // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design\n [contextClient, ...deps],\n );\n\n const sqlKey = sqlObj != null ? JSON.stringify(sqlObj) : null;\n\n const [state, setState] = useState<{ rows: TRows; loading: boolean; error: Error | null }>({\n rows: [] as unknown as TRows,\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || contextClient == null || sqlObj == null) {\n setState({ rows: [] as unknown as TRows, loading: ready, error: null });\n return;\n }\n\n let active = true;\n let liveQuery: LiveQuery<TRows[number]> | undefined;\n let listener: ((results: LiveQueryResults<TRows[number]>) => void) | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n void contextClient.pglite.live\n .query<TRows[number]>(sqlObj.sql, sqlObj.params)\n .then((registered: LiveQuery<TRows[number]>) => {\n if (!active) return registered.unsubscribe();\n liveQuery = registered;\n setState({ rows: registered.initialResults.rows as unknown as TRows, loading: false, error: null });\n listener = (results) => {\n if (active) setState({ rows: results.rows as unknown as TRows, loading: false, error: null });\n };\n registered.subscribe(listener);\n return undefined;\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n rows: [] as unknown as TRows,\n loading: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n if (liveQuery) void liveQuery.unsubscribe(listener);\n };\n // sqlKey is a stable JSON snapshot of sql+params; sqlObj is captured inside the effect from sqlKey\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey is the stable proxy for sqlObj\n }, [contextClient, sqlKey, ready]);\n\n return state;\n }\n\n function useLiveDrizzleRow<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): { row: TRows[number] | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveDrizzleRows(buildQuery, deps, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n return {\n SyncClientProvider,\n useSyncClient,\n useLiveRows,\n useLiveRow,\n useLiveDrizzleRows,\n useLiveDrizzleRow,\n };\n}\n"
5
+ "import type { LiveQuery, LiveQueryResults } from \"@electric-sql/pglite/live\";\nimport { createContext, type DependencyList, type ReactNode, useContext, useEffect, useMemo, useState } from \"react\";\n\nimport { type ClientPGlite, type LiveRowsSubscription, type SyncClient, syncDebug } from \"@pgxsinkit/client\";\nimport type { SyncTableName, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { remapLiveRow, type SelectedFields } from \"./remap-live-row\";\n\n/**\n * Minimal interface satisfied by every Drizzle select/query builder.\n * Calling `.toSQL()` extracts the SQL string and positional params without\n * executing the query, so they can be fed into PGlite's live query API. `_.selectedFields` is the\n * select's field metadata, used to remap PGlite's snake_case rows back to the builder's field keys\n * ({@link remapLiveRow}) — without it the typed rows would carry the underlying column names.\n */\ninterface DrizzleSqlBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n readonly _?: { readonly selectedFields?: SelectedFields };\n}\n\n/** Reactive read result. `hydrating` is true while a lazy relation the query reads is being activated. */\ninterface LiveRowsState<TRows> {\n rows: TRows;\n loading: boolean;\n hydrating: boolean;\n error: Error | null;\n}\n\n/**\n * The raw direct-PGlite subscription used only by `useLiveRows`'s explicit-`pglite` override (tests/multi-db).\n * Wraps `pglite.live.query` into the client's {@link LiveRowsSubscription} shape so the hook body treats the\n * override and the seam identically. The normal path goes through `client.subscribeLiveRows`.\n */\nfunction subscribeRawPglite<TRow extends Record<string, unknown>>(\n pglite: ClientPGlite,\n query: string,\n params: unknown[],\n onRows: (rows: TRow[]) => void,\n): Promise<LiveRowsSubscription<TRow>> {\n return pglite.live.query<TRow>(query, params).then((registered: LiveQuery<TRow>) => {\n const listener = (results: LiveQueryResults<TRow>) => onRows(results.rows);\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows,\n unsubscribe: () => void registered.unsubscribe(listener),\n };\n });\n}\n\n/**\n * Creates a set of React hooks and a context provider bound to a specific\n * `SyncTableRegistry` type. Call this once at the module level in your app:\n *\n * ```ts\n * export const { SyncClientProvider, useSyncClient, useLiveRows, useLiveDrizzleRows, useLiveQueryRaw } =\n * createSyncClientHooks<typeof mySyncRegistry>();\n * ```\n */\nexport function createSyncClientHooks<TRegistry extends SyncTableRegistry>() {\n const SyncClientContext = createContext<SyncClient<TRegistry> | null>(null);\n\n // ─── Provider ────────────────────────────────────────────────────────────\n\n function SyncClientProvider({ client, children }: { client: SyncClient<TRegistry> | null; children: ReactNode }) {\n return <SyncClientContext.Provider value={client}>{children}</SyncClientContext.Provider>;\n }\n\n function useSyncClient(): SyncClient<TRegistry> {\n const client = useContext(SyncClientContext);\n if (client == null) {\n throw new Error(\"[pgxsinkit] useSyncClient must be called inside <SyncClientProvider>\");\n }\n return client;\n }\n\n // ─── Raw SQL live hooks ───────────────────────────────────────────────────\n\n /**\n * Reactive raw-SQL query. This is the **unguarded** escape hatch: it does not participate in the\n * lazy-relation safety net (ADR-0021) — a raw string is not parameterised/quoted predictably, so a\n * `lazy` relation referenced here will read empty/stale unless you `client.ensureSynced([...])` first.\n * Prefer {@link useLiveDrizzleRows} / {@link useLiveQueryRaw} for anything touching lazy relations.\n */\n function useLiveRows<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: {\n params?: readonly unknown[];\n ready?: boolean;\n /** Explicit PGlite instance — overrides the context client. Useful in tests or multi-db scenarios. */\n pglite?: ClientPGlite;\n },\n ): { rows: TRow[]; loading: boolean; error: Error | null } {\n const contextClient = useContext(SyncClientContext);\n // An explicit `pglite` override keeps the raw direct-PGlite path (tests/multi-db); otherwise the query\n // runs through the client's live-rows seam, so this hook works against the worker-attached client too\n // (which has no local `pglite`) exactly as against the in-process client (ADR-0032 S2 §4).\n const overridePglite = options?.pglite;\n const ready = options?.ready ?? true;\n\n const paramsKey = JSON.stringify(options?.params ?? []);\n const stableParams = useMemo<unknown[]>(() => JSON.parse(paramsKey) as unknown[], [paramsKey]);\n\n const [state, setState] = useState<{ rows: TRow[]; loading: boolean; error: Error | null }>({\n rows: [],\n loading: ready,\n error: null,\n });\n\n useEffect(() => {\n const canRun = ready && (overridePglite != null || contextClient != null);\n if (!canRun) {\n setState({ rows: [], loading: ready, error: null });\n return;\n }\n\n let active = true;\n let subscription: LiveRowsSubscription<TRow> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, error: null }));\n\n const onRows = (rows: TRow[]) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState({ rows, loading: false, error: null });\n }\n };\n\n // The raw-PGlite override subscribes directly (unchanged); the seam path is the SAME `pglite.live`\n // wrapper the in-process client exposes, so behaviour is identical when no override is given.\n const subscribe = overridePglite\n ? subscribeRawPglite<TRow>(overridePglite, query, stableParams, onRows)\n : contextClient!.subscribeLiveRows<Record<string, unknown>>({ sql: query, params: stableParams }, (rows) =>\n onRows(rows as TRow[]),\n );\n\n void subscribe\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return;\n }\n subscription = registered as LiveRowsSubscription<TRow>;\n setState({ rows: registered.initialRows as TRow[], loading: false, error: null });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({ rows: [], loading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n }, [contextClient, overridePglite, query, ready, stableParams]);\n\n return state;\n }\n\n function useLiveRow<TRow extends Record<string, unknown> = Record<string, unknown>>(\n query: string,\n options?: { params?: readonly unknown[]; ready?: boolean; pglite?: ClientPGlite },\n ): { row: TRow | null; loading: boolean; error: Error | null } {\n const { rows, loading, error } = useLiveRows<TRow>(query, options);\n return { row: rows[0] ?? null, loading, error };\n }\n\n // ─── Drizzle typed live hooks ─────────────────────────────────────────────\n\n /**\n * Shared implementation behind {@link useLiveDrizzleRows} and {@link useLiveQueryRaw}. Builds the query,\n * then `client.prepareQuery` scans the compiled SQL for the lazy relations it reads (∪ the optional\n * `use`), activates + hydrates them, and only then subscribes the live query — so it is never\n * registered against an un-hydrated lazy relation (ADR-0021).\n */\n function useGuardedDrizzleLive<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean; use?: readonly SyncTableName<TRegistry>[] },\n ): LiveRowsState<TRows> {\n const contextClient = useContext(SyncClientContext);\n const ready = options?.ready ?? true;\n const useList = options?.use;\n const useKey = useList != null ? JSON.stringify(useList) : \"\";\n\n const queryInfo = useMemo(\n () => {\n if (contextClient == null) return null;\n const query = buildQuery(contextClient);\n return { sql: query.toSQL(), selectedFields: query._?.selectedFields };\n },\n // buildQuery intentionally excluded; callers control reactivity via deps. Spread is valid and intentional.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- intentional: callers own deps, spread is by design\n [contextClient, ...deps],\n );\n\n const sqlKey = queryInfo != null ? JSON.stringify(queryInfo.sql) : null;\n\n const [state, setState] = useState<LiveRowsState<TRows>>({\n rows: [] as unknown as TRows,\n loading: ready,\n hydrating: ready,\n error: null,\n });\n\n useEffect(() => {\n if (!ready || contextClient == null || queryInfo == null) {\n setState({ rows: [] as unknown as TRows, loading: ready, hydrating: false, error: null });\n return;\n }\n\n const { sql, selectedFields } = queryInfo;\n // PGlite's live query returns rows keyed by the underlying (snake_case) column names; remap them\n // back to the Drizzle select's field keys so the rows match the builder's inferred (camelCase) type.\n const mapRows = (rows: readonly unknown[]): TRows =>\n rows.map((row) => remapLiveRow(selectedFields, row as Record<string, unknown>)) as unknown as TRows;\n\n let active = true;\n let subscription: LiveRowsSubscription<Record<string, unknown>> | undefined;\n\n setState((prev) => ({ rows: prev.rows, loading: true, hydrating: true, error: null }));\n\n // Scan the compiled SQL for the lazy relations the query reads (∪ `use`), activate + hydrate them,\n // THEN subscribe via the client's live-rows seam — so a query is never registered against an\n // un-hydrated lazy relation (ADR-0021), and the same hook drives both the in-process client (seam over\n // `pglite.live`) and the worker-attached client (seam over the bridge, ADR-0032 S2 §4).\n void contextClient\n .prepareQuery({ sql: sql.sql, ...(useList ? { use: useList } : {}) })\n .then(() => {\n if (!active) return undefined;\n setState((prev) => ({ rows: prev.rows, loading: true, hydrating: false, error: null }));\n return contextClient\n .subscribeLiveRows<Record<string, unknown>>(\n { sql: sql.sql, params: sql.params, ...(useList ? { use: useList } : {}) },\n (rows) => {\n if (active) {\n syncDebug(\"live query updated → re-render\", { rows: rows.length });\n setState({ rows: mapRows(rows), loading: false, hydrating: false, error: null });\n }\n },\n )\n .then((registered) => {\n if (!active) {\n registered.unsubscribe();\n return undefined;\n }\n subscription = registered;\n setState({ rows: mapRows(registered.initialRows), loading: false, hydrating: false, error: null });\n return undefined;\n });\n })\n .catch((error: unknown) => {\n if (active) {\n setState({\n rows: [] as unknown as TRows,\n loading: false,\n hydrating: false,\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n active = false;\n subscription?.unsubscribe();\n };\n // sqlKey/useKey are stable JSON snapshots; queryInfo is captured inside the effect.\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- sqlKey/useKey are the stable proxies for queryInfo\n }, [contextClient, sqlKey, useKey, ready]);\n\n return state;\n }\n\n /**\n * Reactive query using a Drizzle select builder. The builder is re-created\n * whenever `deps` changes (same contract as `useEffect`). pgxsinkit scans the compiled SQL and\n * auto-activates any `lazy` relation the query reads — anywhere it appears (FROM, JOIN, subquery,\n * WHERE) — before subscribing. `use` (see {@link useLiveQueryRaw}) is an optional pre-activation hint,\n * not a requirement (ADR-0021).\n *\n * ```ts\n * const { rows } = useLiveDrizzleRows(\n * (c) => c.drizzle.select().from(c.views.todos).orderBy(c.views.todos.createdAtUs),\n * [],\n * );\n * // rows is fully typed from the view definition — no casts needed\n * ```\n */\n function useLiveDrizzleRows<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(buildQuery, deps, options);\n }\n\n function useLiveDrizzleRow<TRows extends readonly unknown[]>(\n buildQuery: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>,\n deps: DependencyList,\n options?: { ready?: boolean },\n ): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useGuardedDrizzleLive(buildQuery, deps, options);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n /**\n * The reactive query for a builder that embeds a raw `sql` fragment (ADR-0021): `use` names the `lazy`\n * relations it reads that the compiled-SQL scan can't see (a bare identifier inside raw SQL), so they\n * are guaranteed activated before it subscribes. The non-live counterpart of\n * `client.queryRaw({ use, build })`. Pure-Drizzle reads use `useLiveDrizzleRows` / `client.query((c) => …)`,\n * which auto-detect every relation and need no `use`.\n *\n * ```ts\n * const { rows, hydrating } = useLiveQueryRaw({\n * use: [\"archive\"],\n * build: (c) => c.drizzle.select().from(archiveTable).where(inArray(archiveTable.id, recentIds)),\n * deps: [recentIds],\n * });\n * ```\n */\n function useLiveQueryRaw<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n }): LiveRowsState<TRows> {\n return useGuardedDrizzleLive(args.build, args.deps ?? [], {\n ...(args.ready != null ? { ready: args.ready } : {}),\n ...(args.use ? { use: args.use } : {}),\n });\n }\n\n function useLiveQueryRawRow<TRows extends readonly unknown[]>(args: {\n use?: readonly SyncTableName<TRegistry>[];\n build: (client: SyncClient<TRegistry>) => DrizzleSqlBuilder<TRows>;\n deps?: DependencyList;\n ready?: boolean;\n }): { row: TRows[number] | null; loading: boolean; hydrating: boolean; error: Error | null } {\n const { rows, loading, hydrating, error } = useLiveQueryRaw(args);\n return { row: rows[0] ?? null, loading, hydrating, error };\n }\n\n return {\n SyncClientProvider,\n useSyncClient,\n useLiveRows,\n useLiveRow,\n useLiveDrizzleRows,\n useLiveDrizzleRow,\n useLiveQueryRaw,\n useLiveQueryRawRow,\n };\n}\n",
6
+ "import { PGlite, type Results } from \"@electric-sql/pglite\";\nimport { live, type PGliteWithLive } from \"@electric-sql/pglite/live\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { defineRelations } from \"drizzle-orm/relations\";\n\nimport type {\n MutationAck,\n MutationDiagnostics,\n RegistryRelations,\n RegistryTables,\n RegistryViews,\n SyncConfigInput,\n SyncRuntimeStatus,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport { getSyncRegistrySchema } from \"@pgxsinkit/contracts\";\n\nimport { type ConvergenceDriver, type ConvergenceTrigger, createConvergenceDriver } from \"./convergence\";\nimport { syncDebug, timeAsync } from \"./debug\";\nimport { assertLazyRefsActivated, buildLazyGuardIndex, findReferencedLazyKeysInSql } from \"./lazy-guard\";\nimport {\n type LocalStoreVersionEvent,\n clearLazyGroupActivation,\n readActivatedLazyGroups,\n reconcileLocalStoreVersion,\n writeLazyGroupActivation,\n} from \"./local-store\";\nimport {\n createMutationRuntime,\n type MutationBatchItem,\n type MutationDetail,\n type MutationKind,\n type WriteUnit,\n} from \"./mutation\";\nimport { buildDesyncTableSql, buildDropReadCacheSql, buildWipeLocalStoreSql, generateLocalSchemaSql } from \"./schema\";\nimport { startConfiguredSync } from \"./shape-sync\";\nimport { createSyncEngine, type SyncEngine } from \"./sync\";\nimport { buildShapeHeaders } from \"./sync-auth\";\n\nexport { generateLocalSchemaSql };\nexport {\n type ConvergenceClient,\n type ConvergenceDriver,\n type ConvergenceDriverOptions,\n type ConvergenceTrigger,\n createBrowserConvergenceTrigger,\n createConvergenceDriver,\n createIntervalConvergenceTrigger,\n} from \"./convergence\";\nexport { instrumentShapeFetch, setSyncDebugSink, syncDebug, timeAsync } from \"./debug\";\nexport {\n type AttachedSyncClient,\n attachSyncClient,\n type AttachSyncClientOptions,\n provisionSyncWorker,\n} from \"./worker/attach-sync-client\";\nexport { defineSyncWorker, type DefineSyncWorkerOptions, type SyncWorkerHost } from \"./worker/define-sync-worker\";\nexport {\n computeLiveDiff,\n type LiveDiffState,\n LiveRowsMaterializer,\n rowKey,\n seedLiveDiffState,\n} from \"./worker/live-diff\";\nexport { createWorkerTokenCache, type WorkerTokenCache } from \"./worker/token-cache\";\nexport {\n type AttachAckPayload,\n type AttachPayload,\n type AuthTokenSnapshot,\n BRIDGE_CHANNEL,\n BRIDGE_PROTOCOL_VERSION,\n type BridgeCodec,\n type BridgeEnvelope,\n type BridgeEvent,\n type BridgeMessageType,\n type BridgePort,\n encodeEnvelope,\n identityCodec,\n isBridgeEnvelope,\n type LiveDiffPayload,\n type LiveInitialPayload,\n postBridgeMessage,\n type ProvisionAckPayload,\n type ProvisionPayload,\n type RpcOp,\n type RpcPayload,\n type RpcResultPayload,\n type SetOnlinePayload,\n type SubscribePayload,\n type TokenRequestPayload,\n type TokenResponsePayload,\n type WakePayload,\n} from \"./worker/protocol\";\nexport {\n assertLazyRefsActivated,\n buildLazyGuardIndex,\n findReferencedLazyKeysInSql,\n type LazyGuardIndex,\n LazyRelationNotActivatedError,\n} from \"./lazy-guard\";\nexport {\n getJournalTable,\n getLocalMetaTable,\n getOverlayTable,\n getReadModelView,\n getSyncedLocalTable,\n getSyncStateView,\n type JournalTable,\n type LocalMetaTable,\n type OverlayTable,\n type ReadModelView,\n type SyncStateView,\n} from \"./local-tables\";\nexport type { LocalStoreVersionEvent };\n\n// The store carries PGlite's own `live` extension (a genuine create-time extension) plus the pgxsinkit\n// sync engine's namespace, attached post-create by `createSyncClient` as the `electric` property (ADR-0032\n// S1) — no longer a create-time extension. The `electric` part is derived from `createSyncEngine`'s real\n// return so the type follows the attached object.\nexport type ClientPGlite = PGliteWithLive & { electric: SyncEngine[\"namespace\"] };\n\n/**\n * The pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), consumed by\n * {@link createClientPGlite} / {@link CreateSyncClientOptions.pgliteBootAssets}. The host fetches +\n * compiles these on an earlier screen and hands the promise in, so `PGlite.create` skips its own lazy\n * asset load — see the field's JSDoc for the accelerator geometry.\n */\nexport interface PgliteBootAssets {\n pgliteWasmModule?: WebAssembly.Module;\n initdbWasmModule?: WebAssembly.Module;\n fsBundle?: Blob;\n}\n\n/**\n * Create the raw local PGlite store the sync client runs on — the SAME `PGlite.create` call\n * {@link createSyncClient} makes internally (the `electric` + `live` extensions, pre-warmed boot-asset\n * consumption, and the `boot pglite.create` rail stamp), extracted so exactly one implementation exists\n * and a host can create the store EAGERLY on an earlier screen. Hand the returned (still-pending)\n * instance to {@link CreateSyncClientOptions.precreatedPglite}: the client then owns schema exec, prepare\n * hooks, journal recovery and store-version reconcile, exactly as its own `dataDir` path does.\n *\n * The instance is deliberately **schemaless** — the registry-derived local schema is role/registry\n * dependent, so it is applied post-create by `createSyncClient`. The eager create buys only the expensive\n * initdb (+ IDBFS open), which is the dominant cold-boot cost once the WASM is pre-warmed.\n *\n * `bootAssets` is the pre-warmed WASM/fs bundle (see {@link CreateSyncClientOptions.pgliteBootAssets}); a\n * rejected warm is caught to `undefined`, so PGlite falls back to loading its own assets — never a failure.\n */\nexport async function createClientPGlite(\n dataDir: string,\n options?: { bootAssets?: Promise<PgliteBootAssets> },\n): Promise<ClientPGlite> {\n // Stamp only the storage scheme (e.g. \"idb:\" / \"memory:\"), never the full path — the path can carry an\n // identity-specific store name, and the boot rail stays monotonic-and-scheme only.\n const dataDirScheme = dataDir.slice(0, dataDir.indexOf(\":\") + 1);\n // Resolve any pre-warmed boot assets BEFORE (and outside) the `boot pglite.create` stamp: the\n // fetch+compile was kicked off on an earlier screen, so this await just retrieves the already-settled\n // result and the stamp measures the create itself. A rejected warm is caught to `undefined` so a failed\n // pre-warm silently falls back to PGlite's own asset loading rather than failing the boot.\n const bootAssets = options?.bootAssets ? await options.bootAssets.catch(() => undefined) : undefined;\n return (await timeAsync(\n \"boot pglite.create\",\n () =>\n // Only PGlite's own `live` extension is a create-time extension; the pgxsinkit sync engine is NOT\n // (ADR-0032 S1) — it is a plain module `createSyncClient` attaches post-create as `pg.electric`. So\n // a store minted here is deliberately ENGINE-LESS by construction: a spare/pre-warmed store (e.g.\n // the board's login-screen mint) carries no engine, no shape streams, and no Electric connections\n // until it is claimed and handed to `createSyncClient`. The `as ClientPGlite` cast reflects that the\n // `electric` namespace is provisioned later, exactly as the registry-derived schema is.\n PGlite.create(dataDir, {\n ...(bootAssets ?? {}),\n extensions: {\n live,\n },\n }),\n { dataDir: dataDirScheme },\n // `as unknown as` because the raw store is deliberately engine-less here (only `live` is a create-time\n // extension); `createSyncClient` provisions the `electric` namespace post-create (ADR-0032 S1).\n )) as unknown as ClientPGlite;\n}\n\nexport interface CreateSyncClientOptions<TRegistry extends SyncTableRegistry> {\n registry: TRegistry;\n electricUrl: string;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /**\n * Static headers added to **every** read-shape and write request, alongside the per-request\n * `Authorization` (which always wins). The toolkit is agnostic about deployment-gateway\n * credentials, so this is the seam for them — e.g. a Supabase Cloud `apikey` header the platform\n * function gateway expects. Sent even when no `getAuthToken` is supplied.\n */\n requestHeaders?: Record<string, string>;\n /**\n * Extra static headers sent on the **write** path only (the mutation-flush POST), merged over\n * {@link requestHeaders} (`{...requestHeaders, ...writeRequestHeaders}`). Read/shape requests never\n * see these. The seam exists because the two ingress points have opposite geometry: the write\n * function is DB-bound, so pinning it to the database's region (e.g. an `x-region` header) keeps its\n * chatty function→DB protocol on a ~1ms loop; the read proxy's upstream is a globally-distributed\n * CDN (Electric Cloud), so pinning reads away from the caller pays intercontinental round trips per\n * catch-up hop. Put region/DB-affinity headers here; keep gateway credentials the reads also need\n * (e.g. `apikey`) in the shared {@link requestHeaders}.\n */\n writeRequestHeaders?: Record<string, string>;\n syncEnabled?: boolean;\n dataDir?: string;\n /**\n * Pre-warmed PGlite boot assets (the WASM modules + filesystem bundle), awaited and passed straight\n * into `PGlite.create`. The intent is to hide PGlite's ~2.5s cold `boot pglite.create` cost —\n * dominated by the WASM fetch+compile — behind user think-time: the host starts fetching/compiling\n * these on an earlier screen (e.g. the login/identity picker) and hands the still-pending promise\n * here, so by the time a store is opened the assets are already resolved and `PGlite.create` skips\n * its own lazy asset load. Ignored when {@link pgliteInstance} is supplied (the caller owns that\n * instance's boot). A rejected/failed warm is caught to `undefined` and never fails the boot — PGlite\n * falls back to loading its own assets, so this is a pure best-effort accelerator.\n */\n pgliteBootAssets?: Promise<PgliteBootAssets>;\n resetSubscriptionKeys?: string[];\n prepareLocalDbBeforeSchema?: (pglite: ClientPGlite) => Promise<void>;\n prepareLocalDb?: (pglite: ClientPGlite) => Promise<void>;\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n onTableInitialSync?: (tableKey: string) => void;\n /**\n * A fully-provisioned PGlite instance the CALLER owns end-to-end. The client runs NONE of its\n * post-create boot steps against it — no schema exec, prepare hooks, or store-version reconcile\n * (journal recovery still runs, as it does on every path). Use it only when the caller has already\n * applied the registry schema itself. Contrast the three PGlite-provenance seams:\n * - {@link dataDir} (default) — the client creates the store AND runs every post-create step.\n * - {@link precreatedPglite} — the caller creates the raw store (via {@link createClientPGlite}), but\n * the client still runs every post-create step (schema/prepare/reconcile), exactly as `dataDir` does.\n * - `pgliteInstance` — the caller creates AND provisions the store; the client runs none of them.\n *\n * Mutually exclusive with {@link precreatedPglite} (supplying both throws).\n */\n pgliteInstance?: ClientPGlite;\n /**\n * A raw PGlite instance the caller created EAGERLY (via {@link createClientPGlite}) — typically on an\n * earlier screen, to hide the ~1.9s cold `initdb`/IDBFS open behind user think-time — but for which the\n * client still owns EVERYTHING else: schema exec, prepare hooks, journal recovery, and store-version\n * reconcile all run exactly as on the {@link dataDir} path. This is the difference from\n * {@link pgliteInstance} (which skips schema/prepare/reconcile because the caller owns them); see that\n * option's JSDoc for the three-way distinction.\n *\n * The promise form lets the still-pending eager create be handed straight in. Precedence/validation:\n * - Supplying both this and {@link pgliteInstance} throws — they claim different ownership.\n * - {@link dataDir} is used ONLY as the fallback store id if this promise REJECTS: a failed eager\n * create is caught, logged on the boot rail, and the normal `dataDir` create path runs instead (also\n * consuming {@link pgliteBootAssets} if provided). The pattern is a pure accelerator, never a boot\n * dependency.\n */\n precreatedPglite?: Promise<ClientPGlite>;\n /**\n * PROVABLY-fresh store hint (ADR-0032 S4 / backlog-0003): the caller guarantees this store is brand-new\n * and schemaless — no prior schema, no synced rows, no persisted subscription state. When set (and sync\n * is enabled, and the client owns schema exec — i.e. not the {@link pgliteInstance} path), the shape\n * catch-up is started BEFORE the local boot phases (schema exec, journal recovery, store-version\n * reconcile) and buffered in memory, with commits gated until those phases finish — so the network\n * catch-up overlaps them instead of running strictly after. On a far-from-database caller this collapses\n * boot from `local-phases + catch-up` toward `max(local-phases, catch-up)`.\n *\n * MUST be set only when freshness is proven, never derived by probing — a claimed schemaless spare (the\n * board's claim path knows: a claimed spare is always fresh; a mapped/returning store never is). A wrong\n * `true` on a warm store would start the streams from offset 0 and skip the subscription-state read,\n * re-snapshotting instead of resuming. Absent/false → the exact sequential path (the default, correct for\n * every warm store).\n */\n freshStore?: boolean;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to the library's built-in cap.\n */\n maxMutationAttempts?: number;\n /**\n * Invoked when mutations are quarantined (permanently rejected by the server, terminal). The library\n * surfaces them here rather than silently dropping or retry-looping (ADR-0006). Surface, then either\n * re-author + resubmit or roll back via {@link SyncClient.discardQuarantined} — which clears the kept\n * overlay + quarantined journal rows so the entity accepts new mutations again.\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when mutations are `conflicted` — a stale write the server declined under the\n * `reject-if-stale` Conflict policy (ADR-0015). The optimistic Overlay is kept, so the app shows a\n * resolution/diff UI and resolves each as a new write (`mutate.update`) or `discardConflict`s it.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked when a pessimistic write-unit is `rejected` (ADR-0022) — a business decline from the\n * authoritative endpoint (capacity/quota/uniqueness). The inverse of `onConflict`: the optimistic Overlay\n * was auto-discarded for the whole unit, so the app surfaces the typed reason rather than a resolve UI.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked on boot when the registry fingerprint differs from the one the local store was\n * provisioned under (ADR-0006). `rebuilt` = the read cache was dropped and rebuilt at the\n * new shape; `deferred` = un-flushed/quarantined writes are still owed, so the rebuild is\n * postponed (and retried on a later boot) rather than dropping owed data.\n */\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n /**\n * Opt-in convergence driver (ADR-0005). Supply a {@link ConvergenceTrigger} (e.g.\n * `createBrowserConvergenceTrigger()`) and the client drives `flush`/`reconcile`/`retryFailed`\n * on the trigger's schedule, started once sync is ready and stopped on `stop()`/`destroy()`.\n * Omit it for fully-manual convergence (the mechanism primitives stay public either way).\n */\n autoSync?: ConvergenceTrigger;\n /** Invoked after each automatic convergence pass with its error, or `null` on success (only when `autoSync` is set). */\n onConvergencePass?: (error: unknown) => void;\n /**\n * Invoked when a read-path sync commit fails after exhausting its retries (ADR-0009 decision 5).\n * The runtime enters the `degraded` phase and holds the read cache at the last applied commit\n * instead of silently diverging from the server; recovery is a later commit or a restart/refetch.\n */\n onSyncError?: (error: Error) => void;\n}\n\nexport interface SyncClientTableHandle<TRegistry extends SyncTableRegistry, TKey extends SyncTableName<TRegistry>> {\n key: TKey;\n mode: TRegistry[TKey][\"mode\"];\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => Promise<void>;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => Promise<void>;\n delete: (entityKey: Record<string, string>) => Promise<void>;\n}\n\n/**\n * A table handle inside a {@link SyncClient.transaction} block (ADR-0022 §2). It *collects* mutations into\n * the open write-unit rather than enqueuing each immediately; the whole set is enqueued atomically when the\n * block's callback returns. The calls are synchronous (collection only) — no per-call await needed.\n */\nexport interface SyncTransactionTableHandle<\n TRegistry extends SyncTableRegistry,\n TKey extends SyncTableName<TRegistry>,\n> {\n create: (input: SyncTableCreateInput<TRegistry, TKey>) => void;\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n delete: (entityKey: Record<string, string>) => void;\n /**\n * An **update-by-key with no local base row** (ADR-0022 addendum). Ordinary `update` requires the entity\n * to be present in the actor's local read model (it seeds the optimistic overlay and captures the base\n * server version); `updateBlind` skips that presence check and writes NO overlay — nothing appears in the\n * read model. Use it when the write target is deliberately EXCLUDED from your read shape (a write-only\n * flow, or an anonymity-scoped moderation write whose row streams only to a different projection), so there\n * is no local row to update and nothing to show optimistically.\n *\n * **Pessimistic-only.** The /unit expander is authoritative for the outcome, so a blind write is meaningful\n * only inside a `transaction({ mode: \"pessimistic\" })` block (or over a statically-pessimistic table). An\n * optimistic-routed blind write has nothing to converge and THROWS at enqueue.\n *\n * The acked journal row **retires without a synced echo** (no visible row ever converges for it), so it does\n * not linger — unlike the seed-a-phantom-row workaround this replaces, whose acked row + overlay lingered\n * forever behind the echo barrier. A `conflicted` blind write stays dischargeable via `discardConflict`; a\n * `rejected` one is surfaced via `onReject`, both with no overlay to clean up.\n */\n updateBlind: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, TKey>) => void;\n}\n\n/** The handle passed to a {@link SyncClient.transaction} callback: collecting table handles for the unit. */\nexport interface SyncTransaction<TRegistry extends SyncTableRegistry> {\n tables: { [TKey in SyncTableName<TRegistry>]: SyncTransactionTableHandle<TRegistry, TKey> };\n}\n\n/**\n * The result of a {@link SyncClient.transaction}. A `pessimistic` block carries the authoritative server\n * `acks` (each `acked` / `conflicted` / `rejected`); an `optimistic` block enqueues atomically and flushes\n * in the background, so its `acks` are empty.\n */\nexport interface SyncTransactionResult {\n acks: MutationAck[];\n}\n\n/** Minimal shape of a Drizzle select builder: inspectable via `.toSQL()` and awaitable for its rows. */\nexport interface DrizzleQueryBuilder<TRows extends readonly unknown[]> extends PromiseLike<TRows> {\n toSQL(): { sql: string; params: unknown[] };\n}\n\n/**\n * The builder callback for a guarded read (ADR-0021): it receives the client and returns a Drizzle\n * select builder. Reach relations through `c.views` / `c.drizzle` / a directly-imported synced table.\n */\nexport type GuardedQueryFn<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> = (\n client: SyncClient<TRegistry>,\n) => DrizzleQueryBuilder<TRows>;\n\n/**\n * A guarded query whose builder MAY embed a raw `sql` template fragment (ADR-0021). A raw fragment can\n * name a lazy relation as a bare/unquoted identifier the compiled-SQL scan cannot see, so declare those\n * relations in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads need no\n * `use` (the scan detects every relation): pass the builder callback directly to `client.query`.\n */\nexport interface GuardedRawQuerySpec<TRegistry extends SyncTableRegistry, TRows extends readonly unknown[]> {\n use?: readonly SyncTableName<TRegistry>[];\n build: GuardedQueryFn<TRegistry, TRows>;\n}\n\n/**\n * Inputs to the read-path safety seam {@link SyncClient.prepareQuery}. The lazy relations a query reads\n * are detected by scanning the compiled `sql` (union with the optional explicit `use`), then activated.\n * Shared by the live React hooks and the non-live facade.\n */\nexport interface PrepareQueryInput<TRegistry extends SyncTableRegistry> {\n /** The compiled (parameterised) Drizzle SQL the query will run — the scan's ground-truth target. */\n sql: string;\n /** Lazy relations to also activate, beyond those scanned from `sql` — a pre-activation hint, not required. */\n use?: readonly SyncTableName<TRegistry>[];\n}\n\n/**\n * The narrow live-rows seam (ADR-0032 S2 §4) both client modes implement so the `@pgxsinkit/react` hooks\n * work against either. Input for a reactive subscription: the compiled SQL + params (from a Drizzle\n * builder's `.toSQL()` or a raw string) and the result's `pkColumns` (drives worker-side diff keying;\n * omit for a keyless query). The in-process client runs it directly over `pglite.live`; the worker-attached\n * client runs the live query in the worker and streams DIFFs across the bridge.\n */\nexport interface SubscribeLiveRowsInput {\n sql: string;\n params: readonly unknown[];\n /** The result's PK columns — the diff-keying identity across the bridge (§4). Omit for a keyless query. */\n pkColumns?: readonly string[];\n /**\n * Lazy relations (ADR-0021) to activate before the query runs — forwarded to the worker so it can\n * `prepareQuery` before registering the live query (the tab's own `prepareQuery` is a no-op against the\n * worker bridge). Ignored by the in-process client, whose `prepareQuery` already ran on the tab.\n */\n use?: readonly string[];\n}\n\n/** A handle to a live-rows subscription: the initial ordered snapshot plus an idempotent unsubscribe. */\nexport interface LiveRowsSubscription<TRow> {\n initialRows: TRow[];\n unsubscribe: () => void;\n}\n\nexport interface SyncClient<TRegistry extends SyncTableRegistry> {\n drizzle: PgliteDatabase<RegistryRelations<TRegistry>>;\n pglite: ClientPGlite;\n views: RegistryViews<TRegistry>;\n tables: {\n [TKey in SyncTableName<TRegistry>]: SyncClientTableHandle<TRegistry, TKey>;\n };\n ready: Promise<void>;\n status: SyncRuntimeStatus;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n /**\n * Wipe the entire local store (synced cache + overlay + journal) and close the handle\n * (ADR-0005). Refuses if mutations are still owed to the server unless `force` is set, so\n * it never silently drops un-flushed writes. Distinct from `stop()`, which only halts sync.\n */\n destroy: (options?: { force?: boolean }) => Promise<void>;\n /**\n * Drop and rebuild the reconstructible synced read cache, preserving the overlay and\n * mutation journal (ADR-0006). The next sync refills it. Use to recover from a corrupt or\n * stale read cache without losing un-flushed writes.\n */\n dropReadCache: () => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n mutate: {\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>) => Promise<void>;\n };\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. Use when the user abandons a\n * stale edit instead of resolving it as a new write.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entry and kept optimistic\n * Overlay, so the Read model falls back to the synced (server) value. The rollback path for a write\n * the server permanently rejected — e.g. an RLS policy denial (42501) routed to quarantine. After the\n * discard the phantom optimistic row is gone and the entity accepts new mutations again (no longer\n * blocked behind the quarantined head). Symmetric to {@link SyncClient.discardConflict}; the overlay\n * is kept when another still-owed write depends on it. No-op for an entity with no quarantined entry.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n diagnostics: (table?: SyncTableName<TRegistry>) => Promise<{ mutation: MutationDiagnostics }>;\n /**\n * The INSPECTION read surface (debug pages, REPLs, ad-hoc counts) — identical on the in-process and\n * worker-attached client (on the latter the statement runs in the worker). The statement runs raw\n * against the local store: it BYPASSES the mutation journal and optimistic overlay, and any write it\n * issues stays local and will NOT converge. For app data reads prefer the live-rows hooks /\n * {@link subscribeLiveRows} (or the guarded {@link query} family); reach for this only to look at the\n * store, not to read app state or mutate it.\n */\n rawQuery: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n /** {@link rawQuery} for multi-statement SQL, returning one {@link Results} per statement. */\n rawExec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n /**\n * Run a one-shot (non-live) typed **pure-Drizzle** query with the lazy-relation safety net (ADR-0021).\n * Pass the builder callback directly — pgxsinkit scans the compiled SQL and activates + awaits every\n * lazy relation it reads (FROM, JOIN, subquery, WHERE) before it runs, and the tripwire rejects any\n * lazy relation the SQL still references but that is not active, so the result is never silently\n * empty/stale. The guaranteed-safe alternative to a bare `client.drizzle` read. If the builder embeds\n * a raw `sql` template fragment, use {@link queryRaw} and declare the lazy relations in `use`.\n */\n query: <TRows extends readonly unknown[]>(build: GuardedQueryFn<TRegistry, TRows>) => Promise<TRows>;\n /** {@link query} returning the first row, or null when empty. */\n queryRow: <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * {@link query} for a builder that embeds a raw `sql` template fragment (ADR-0021). The compiled-SQL\n * scan can miss a lazy relation named as a bare/unquoted identifier inside raw SQL, so declare those\n * in `use` — they are activated and awaited before the query runs. Pure-Drizzle reads should use\n * {@link query} instead (no `use` needed).\n */\n queryRaw: <TRows extends readonly unknown[]>(spec: GuardedRawQuerySpec<TRegistry, TRows>) => Promise<TRows>;\n /** {@link queryRaw} returning the first row, or null when empty. */\n queryRawRow: <TRows extends readonly unknown[]>(\n spec: GuardedRawQuerySpec<TRegistry, TRows>,\n ) => Promise<TRows[number] | null>;\n /**\n * Activate one or more lazy relations (ADR-0021): open their consistency-group subscription if held\n * out of the eager boot, resolving once their initial sync completes. Idempotent — eager or\n * already-started relations resolve immediately. Use to pre-activate before a raw/`client.drizzle`\n * read, or as the manual escape hatch the tripwire points to.\n */\n ensureSynced: (keys: readonly SyncTableName<TRegistry>[]) => Promise<void>;\n /**\n * Whether a relation's group has started and hydrated (ADR-0021). False for a still-dormant `lazy`\n * relation; true for eager relations once boot completes (and always when sync is disabled).\n */\n isSynced: (key: SyncTableName<TRegistry>) => boolean;\n /**\n * Revert a `lazy` relation to dormant (ADR-0021 §2) — the inverse of on-demand activation: stop its\n * consistency group's stream, clear any persisted `lazy + persistent` activation (so the next boot\n * holds it dormant again), and clean-truncate its local read cache. A later reference re-activates it\n * from scratch. Refuses when the relation is `eager` (always-on, would immediately re-sync) or owes\n * the server unsettled writes (the truncate would drop them — flush or discard first). The reclaim\n * primitive a host wires to navigation/idle for a rarely-opened lazy view; for an `ephemeral`\n * relation, idle-eviction is otherwise automatic at session end.\n */\n desync: (key: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The read-path safety seam (ADR-0021): scan the compiled `sql` for the lazy relations it reads\n * (∪ the optional `use`), activate them, and await their initial sync — so a lazy relation\n * auto-activates on *any* reference (FROM, JOIN, subquery, WHERE). Resolves once it is safe to run the\n * query; a backstop throws {@link LazyRelationNotActivatedError} only if a referenced relation could\n * not be activated. Exposed for the React live hooks (which own their query build); `query`/`queryRow`\n * are the higher-level non-live wrappers. Raw, non-Drizzle SQL is out of scope — pass `use`, or\n * `ensureSynced` first.\n */\n prepareQuery: (input: PrepareQueryInput<TRegistry>) => Promise<void>;\n /**\n * Author an atomic write-**unit** (ADR-0022 §2). The callback receives collecting table handles; every\n * mutation it issues is tagged into one unit and enqueued atomically when the callback returns.\n *\n * - `mode: \"pessimistic\"` — **server-authoritative**: the unit flush-routes to the authoritative endpoint\n * and this call resolves only once the server has decided. The result's `acks` carry each member's\n * outcome — `acked`, `conflicted` (overlay kept, ADR-0015), or `rejected` (overlay auto-discarded for\n * the whole unit, surfaced via `onReject`, ADR-0022 §4). Throws on transport failure (overlay kept). A\n * pessimistic block may also issue {@link SyncTransactionTableHandle.updateBlind} — an update-by-key with\n * no local base row and no overlay, for a write target excluded from the actor's read shape.\n * - `mode: \"optimistic\"` — an atomic batch enqueue that flushes in the background (empty `acks`).\n */\n transaction: (\n options: { mode: WriteMode },\n run: (tx: SyncTransaction<TRegistry>) => void | Promise<void>,\n ) => Promise<SyncTransactionResult>;\n /**\n * Per-group readiness (ADR-0032 decision 6): a promise resolving the moment the given table's\n * consistency group is up-to-date. Resolves immediately for an already-ready (or sync-disabled)\n * group; stays pending for a still-dormant `lazy` relation until it is activated and caught up. The\n * opt-in progressive-paint signal beside the all-eager-groups `ready` gate. `status.groups` carries the\n * same readiness as a synchronous snapshot.\n */\n groupReady: (table: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * The live-rows seam (ADR-0032 S2 §4): register a reactive query and receive its initial ordered\n * snapshot plus subsequent updates via `onRows`. The React live hooks consume THIS (not `pglite.live`\n * directly), so they run unchanged against both the in-process client (which implements it over\n * `pglite.live`) and the worker-attached client (which implements it over the bridge). Prefer the\n * higher-level `@pgxsinkit/react` hooks; this is the lower-level primitive they build on.\n */\n subscribeLiveRows: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n input: SubscribeLiveRowsInput,\n onRows: (rows: TRow[]) => void,\n ) => Promise<LiveRowsSubscription<TRow>>;\n}\n\nexport type { MutationBatchItem, MutationDetail, MutationDiagnostics, MutationKind };\n\n/**\n * The structured-clone-safe subset of PGlite's `QueryOptions` the inspection surface carries. Kept\n * narrow ON PURPOSE: on a worker-attached client the options object crosses the bridge via\n * `postMessage`, so function-valued options (`parsers`, `serializers`, `onNotice`) can never be part\n * of this contract. `rowMode: \"array\"` is what `@electric-sql/pglite-repl` asks for on every exec.\n */\nexport interface RawQueryOptions {\n rowMode?: \"object\" | \"array\";\n}\n\n/** The `{ query, exec }` duck `@electric-sql/pglite-repl` drives, backed by a client's inspection surface. */\nexport interface ReplInspectionSurface {\n query: (sql: string, params?: unknown[], options?: RawQueryOptions) => Promise<Results>;\n exec: (sql: string, options?: RawQueryOptions) => Promise<Results[]>;\n}\n\n/**\n * Shape a {@link SyncClient}'s inspection surface (`rawQuery`/`rawExec`) as the `{ query, exec }` duck\n * `@electric-sql/pglite-repl` needs. Identical on the in-process and worker-attached client — on the latter\n * each statement routes through the worker bridge, so the REPL works even though `client.pglite` is\n * unavailable. Cast the result at the `<Repl pg={...}>` prop (the REPL types the prop as a full `PGlite`).\n * The surface is registry-independent, so it accepts any client's `rawQuery`/`rawExec` pair.\n */\nexport function replAdapter(\n client: Pick<SyncClient<SyncTableRegistry>, \"rawQuery\" | \"rawExec\">,\n): ReplInspectionSurface {\n return {\n // Thread the options through UNMODIFIED — the REPL execs with `{ rowMode: \"array\" }` and renders\n // each row with `row.map`, so dropping the options here breaks every REPL statement.\n query: (sql, params, options) => client.rawQuery(sql, params, options),\n exec: (sql, options) => client.rawExec(sql, options),\n };\n}\n\nexport async function createSyncClient<const TRegistry extends SyncTableRegistry>(\n options: CreateSyncClientOptions<TRegistry>,\n): Promise<SyncClient<TRegistry>> {\n const status: SyncRuntimeStatus = {\n phase: \"booting\",\n isRunning: false,\n };\n\n let resolveReady!: () => void;\n const ready = new Promise<void>((resolve) => {\n resolveReady = resolve;\n });\n\n if (options.pgliteInstance && options.precreatedPglite) {\n throw new Error(\n \"createSyncClient: pass at most one of `pgliteInstance` or `precreatedPglite` — they claim different ownership of the post-create boot steps (schema exec, prepare hooks, store-version reconcile).\",\n );\n }\n\n // Bind the boot-asset option once for the two create paths (fresh `dataDir`, and the `precreatedPglite`\n // reject-fallback), so both consume the same pre-warm.\n const createBootAssets = options.pgliteBootAssets ? { bootAssets: options.pgliteBootAssets } : undefined;\n const fallbackDataDir = options.dataDir ?? \"idb://pgxsinkit-overlay-v1\";\n\n let pglite: ClientPGlite;\n if (options.pgliteInstance) {\n // The caller created AND provisioned this store; the client runs NONE of the post-create boot steps\n // (schema/prepare/reconcile) — see the `pgliteInstance` JSDoc.\n pglite = options.pgliteInstance;\n } else if (options.precreatedPglite) {\n // The caller created the raw store eagerly via `createClientPGlite`; the client still owns every\n // post-create step below. A REJECTED eager create must never fail the boot: fall back to the normal\n // `dataDir` create here, so the pattern stays a pure accelerator.\n pglite = await options.precreatedPglite.catch((error: unknown) => {\n syncDebug(\"boot precreated pglite rejected — falling back to dataDir create\", {\n error: error instanceof Error ? error.message : String(error),\n });\n return createClientPGlite(fallbackDataDir, createBootAssets);\n });\n } else {\n pglite = await createClientPGlite(fallbackDataDir, createBootAssets);\n }\n\n // Attach the sync engine explicitly, over the already-created instance, on ALL three provenance paths\n // (pgliteInstance, precreatedPglite, dataDir) — ADR-0032 S1. The engine is no longer a create-time\n // extension, so the raw store (a `createClientPGlite` mint, or a caller's own instance) carries no\n // `electric` namespace until this point; the property assignment gives `ClientPGlite` its exact former\n // structural shape (live + electric) so every `pglite.electric.…` call site is unchanged. It is attached\n // BEFORE the schema/prepare steps below so a `prepareLocalDb` hook sees the same `.electric` it did when\n // the extension provided it at create time. `engine.close` (the former extension close hook — abort every\n // shape stream) is kept private to this client and run explicitly by `stop`/`destroy` at the same moment\n // `pglite.close()` used to trigger it.\n const engine: SyncEngine = await createSyncEngine(pglite);\n (pglite as { electric: SyncEngine[\"namespace\"] }).electric = engine.namespace;\n\n const syncEnabled = options.syncEnabled ?? true;\n // Whether the read path's first initial sync has completed, so a recovery from `auth-needed` returns to\n // the right steady-state phase (`ready` if already caught up, else `syncing`).\n let initialSyncCompleted = false;\n // Why the runtime is `degraded` (#4). A read-stream error degraded clears on the next successful batch; a\n // commit-failure degraded is sticky (a fetch can succeed while applies still fail), so a bare\n // `onSyncActivity` must not clear it.\n let degradedReason: \"stream\" | \"commit\" | null = null;\n\n // ─── Fresh-store prefetch overlap (ADR-0032 S4 / backlog-0003) ─────────────────────────────────────\n // On a PROVABLY-FRESH store (the caller's `freshStore` hint — a claimed schemaless spare) the shape\n // catch-up needs none of the local boot phases, so start it NOW and gate its commits on `dbReady`, which\n // we resolve once schema exec + journal recovery + store-version reconcile complete. The network then\n // overlaps those phases instead of running strictly after them. Gated to the schema-owning paths (the\n // `pgliteInstance` path runs no schema step, so it has nothing to hide); warm stores keep the exact\n // sequential path. See the `freshStore` option's JSDoc for who sets the hint (the board's claim path).\n const overlapPrefetch = syncEnabled && options.freshStore === true && !options.pgliteInstance;\n let openDbGate: () => void = () => {};\n const dbReady = overlapPrefetch\n ? new Promise<void>((resolve) => {\n openDbGate = resolve;\n })\n : null;\n\n // The sync-start options, built once and used by BOTH the overlap early-start and the sequential start —\n // the only per-call difference is the promoted-lazy set (empty on a fresh store) and the overlap gate.\n const buildStartOptions = (promotedGroups: ReadonlySet<string>): Parameters<typeof startConfiguredSync>[1] => ({\n syncConfig: buildSyncConfigFromRegistry(options.registry, options.electricUrl),\n registry: options.registry,\n promotedGroups,\n ...(dbReady ? { dbReady } : {}),\n // Persist a durable lazy group's activation on first on-demand start, so the next boot promotes it.\n onLazyActivated: (groupKey) => {\n void writeLazyGroupActivation(pglite, options.registry, groupKey);\n },\n // The read path resolves the token per request (ADR-0013), not frozen at boot — so a long-lived session\n // never wedges on JWT expiry. Read and write share one token lifecycle.\n ...(options.getAuthToken || options.requestHeaders\n ? {\n shapeHeaders: buildShapeHeaders({\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),\n }),\n }\n : {}),\n ...(options.onTableInitialSync ? { onTableInitialSync: options.onTableInitialSync } : {}),\n // Per-group readiness (ADR-0032 decision 6): mirror each group's catch-up into `status.groups` and\n // re-emit, so an app can drive progressive per-group paint off `status` (and `client.groupReady`).\n onGroupReady: (groupKey) => {\n status.groups = { ...(status.groups ?? {}), [groupKey]: true };\n options.onStatusChange?.(status);\n },\n onInitialSync: () => {\n initialSyncCompleted = true;\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n // Boot complete: the first initial sync landed and `ready` is about to resolve. One monotonic stamp\n // closes the boot rail opened by `boot pglite.create` (the stamp itself is the number).\n syncDebug(\"boot client ready\");\n resolveReady();\n },\n onSyncError: (error) => {\n // A sync commit exhausted its retries (ADR-0009 decision 5): go degraded and surface it, rather than\n // letting the read cache silently diverge from the server. Sticky (see below).\n status.phase = \"degraded\";\n degradedReason = \"commit\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n options.onSyncError?.(error);\n },\n // #4: a terminal/transient NON-auth read-stream error → `degraded`, so the runtime never keeps reporting\n // healthy while the read stream has stalled. Does not override the more-actionable `auth-needed`, nor a\n // commit-failure degraded. Cleared on the next successful batch below.\n onReadStreamError: (error) => {\n // Never mask the more-actionable auth-needed, nor a sticky commit-failure degraded (its lastError is\n // the more serious signal — a stream blip must not overwrite it).\n if (status.phase === \"auth-needed\") return;\n if (status.phase === \"degraded\" && degradedReason === \"commit\") return;\n // Enter, or refresh, a stream-degraded status. Refreshing keeps `lastError` pointing at the most\n // recent stream fault (and re-emits) rather than freezing on the first one, so a stream that fails one\n // way then another reports the current cause (observability).\n status.phase = \"degraded\";\n degradedReason = \"stream\";\n status.lastError = error.message;\n options.onStatusChange?.(status);\n },\n // Clear a recoverable status (auth-needed, or a read-stream degraded) the moment a batch is delivered\n // again. A commit-failure degraded is NOT cleared here — a fetch can succeed while applies keep failing,\n // so only `onSyncError` clearing (a clean commit) would lift it.\n onSyncActivity: () => {\n if (status.phase === \"auth-needed\" || (status.phase === \"degraded\" && degradedReason === \"stream\")) {\n degradedReason = null;\n status.phase = initialSyncCompleted ? \"ready\" : \"syncing\";\n options.onStatusChange?.(status);\n }\n },\n // ADR-0013 Phase 3: surface a persistent read-path auth failure as a distinct `auth-needed` status (the\n // app prompts re-login) while the stream keeps retrying for a fresh token. Only wired when a token\n // provider exists — without one there is no auth lifecycle to track.\n ...(options.getAuthToken\n ? {\n onAuthError: () => {\n if (status.phase !== \"auth-needed\") {\n status.phase = \"auth-needed\";\n options.onStatusChange?.(status);\n }\n },\n }\n : {}),\n });\n\n // Overlap: kick the shape streams off BEFORE schema exec (they buffer catch-up into the memory inbox,\n // commits gated on `dbReady`). A fresh store has no persisted lazy activations and no subscriptions to\n // reset, so both DB reads the sequential path makes first are skipped here.\n let earlySync: ReturnType<typeof startConfiguredSync> | null = null;\n if (overlapPrefetch) {\n status.isRunning = true;\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n earlySync = startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(new Set()),\n );\n }\n\n if (!options.pgliteInstance) {\n if (options.prepareLocalDbBeforeSchema) {\n const prepareBeforeSchema = options.prepareLocalDbBeforeSchema;\n await timeAsync(\"boot prepare(before-schema)\", () => prepareBeforeSchema(pglite));\n }\n\n const schemaSql = generateLocalSchemaSql(options.registry);\n await timeAsync(\"boot local schema\", () => pglite.exec(schemaSql));\n\n if (options.prepareLocalDb) {\n const prepareLocalDb = options.prepareLocalDb;\n await timeAsync(\"boot prepare(local-db)\", () => prepareLocalDb(pglite));\n }\n }\n\n // The write path's headers are the shared base plus the write-only overrides (region/DB-affinity):\n // `{...requestHeaders, ...writeRequestHeaders}`. The read/shape path keeps `requestHeaders` alone\n // (below), so `writeRequestHeaders` never reach reads — the two ingress points pin independently.\n const writePathHeaders =\n options.requestHeaders || options.writeRequestHeaders\n ? { ...(options.requestHeaders ?? {}), ...(options.writeRequestHeaders ?? {}) }\n : undefined;\n\n const mutationRuntime = createMutationRuntime({\n db: pglite,\n registry: options.registry,\n writeUrl: options.writeUrl,\n ...(options.getAuthToken ? { getAuthToken: options.getAuthToken } : {}),\n ...(writePathHeaders ? { requestHeaders: writePathHeaders } : {}),\n ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),\n ...(options.onQuarantine ? { onQuarantine: options.onQuarantine } : {}),\n ...(options.onConflict ? { onConflict: options.onConflict } : {}),\n ...(options.onReject ? { onReject: options.onReject } : {}),\n });\n\n // Reclaim any in-flight mutations interrupted by a previous shutdown (ADR-0005), then\n // reconcile the local store against the current registry fingerprint before sync starts\n // (ADR-0006). Skipped when the caller supplies their own pglite (they own its schema).\n await timeAsync(\"boot journal recovery\", () => mutationRuntime.recoverSending());\n\n let versionEvent: LocalStoreVersionEvent | null = null;\n\n if (!options.pgliteInstance) {\n versionEvent = await timeAsync(\"boot store-version reconcile\", () =>\n reconcileLocalStoreVersion({\n db: pglite,\n registry: options.registry,\n runtime: mutationRuntime,\n ...(options.onSchemaChange ? { onSchemaChange: options.onSchemaChange } : {}),\n }),\n );\n }\n\n const drizzleDb = createDrizzleDatabase(pglite, buildSchema(options.registry));\n // Static index of the registry's lazy relations (ADR-0021), driving the read-path safety net.\n const lazyGuardIndex = buildLazyGuardIndex(options.registry);\n\n let sync: Awaited<ReturnType<typeof startConfiguredSync>> | null = null;\n let convergenceDriver: ConvergenceDriver | null = null;\n\n status.isRunning = true;\n\n // Open the overlap commit gate now the local store is ready (schema exec + journal recovery + reconcile\n // done): the catch-up the streams prefetched during those phases now drains in one commit train. A no-op\n // on the sequential path (`openDbGate` is the empty default there).\n openDbGate();\n\n if (syncEnabled) {\n if (earlySync) {\n // Overlap path: the shape streams have been prefetching since before schema exec; adopt the handle\n // (it resolves as soon as the streams are subscribed — catch-up drains via the gate just lifted, and\n // `onInitialSync` still gates `ready` on a fully-consistent first paint).\n sync = await earlySync;\n } else {\n // Sequential path (warm store / no fresh hint): the exact pre-S4 ordering — reset any rebuilt\n // subscriptions, promote durable lazy groups, then start (catch-up strictly after the local phases).\n // After a read-cache rebuild the Electric subscription bookkeeping is stale (it would believe the\n // dropped shapes are still caught up and never backfill), so reset every shape subscription to force a\n // fresh re-stream (ADR-0006).\n const resetKeys =\n versionEvent?.status === \"rebuilt\"\n ? [...(options.resetSubscriptionKeys ?? []), ...allGroupSubscriptionKeys(options.registry)]\n : options.resetSubscriptionKeys;\n await resetSubscriptionsIfRequested(pglite, resetKeys);\n\n status.phase = \"syncing\";\n options.onStatusChange?.(status);\n\n // Promote any `lazy + persistent` group activated on a previous boot back into the eager set\n // (ADR-0021 §2); the sync engine does no DB read of its own.\n const promotedGroups = await readActivatedLazyGroups(pglite, options.registry);\n\n sync = await timeAsync(\"boot sync start\", () =>\n startConfiguredSync(\n pglite as unknown as Parameters<typeof startConfiguredSync>[0],\n buildStartOptions(promotedGroups),\n ),\n );\n }\n } else {\n status.phase = \"ready\";\n options.onStatusChange?.(status);\n resolveReady();\n }\n\n if (options.autoSync) {\n convergenceDriver = createConvergenceDriver({\n client: {\n flush: () => mutationRuntime.flush(),\n reconcile: () => mutationRuntime.reconcile(),\n },\n trigger: options.autoSync,\n ...(options.onConvergencePass ? { onPass: options.onConvergencePass } : {}),\n });\n\n // Start driving convergence once the initial sync is ready, so a pass never races the\n // first shape load. stop()/destroy() halt it.\n void ready.then(() => convergenceDriver?.start());\n }\n\n // Event-driven convergence: the moment a mutation is enqueued, ask the driver to run a pass so the\n // write flushes immediately rather than waiting for the trigger's next interval tick. This is what\n // lets the interval be a rare fallback (and so run far less often). No-op when `autoSync` is off — the\n // caller drives `flush`/`reconcile` itself.\n const requestConvergence = () => convergenceDriver?.requestPass();\n const mutate: SyncClient<TRegistry>[\"mutate\"] = {\n create: async (table, input) => {\n await mutationRuntime.create(table, input);\n requestConvergence();\n },\n update: async (table, entityKey, patch) => {\n await mutationRuntime.update(table, entityKey, patch);\n requestConvergence();\n },\n delete: async (table, entityKey) => {\n await mutationRuntime.delete(table, entityKey);\n requestConvergence();\n },\n batch: async (items) => {\n await mutationRuntime.batch(items);\n requestConvergence();\n },\n };\n\n // ─── Lazy-relation activation + the declared-safe query facade (ADR-0021) ──────────────────────\n const ensureSynced: SyncClient<TRegistry>[\"ensureSynced\"] = async (keys) => {\n const activeSync = sync;\n if (activeSync == null || keys.length === 0) return;\n const groupKeys = new Set<string>();\n for (const key of keys) {\n const groupKey = activeSync.groupKeyForTable(key);\n if (groupKey != null) groupKeys.add(groupKey);\n }\n await Promise.all([...groupKeys].map((groupKey) => activeSync.ensureGroupStarted(groupKey)));\n };\n\n const isSynced: SyncClient<TRegistry>[\"isSynced\"] = (key) => {\n const activeSync = sync;\n // Sync disabled → local-only: reads hit whatever is in the local store, so nothing is \"dormant\".\n if (activeSync == null) return true;\n return activeSync.isTableStarted(key);\n };\n\n const desync: SyncClient<TRegistry>[\"desync\"] = async (key) => {\n const entry = options.registry[key];\n if (entry == null) throw new Error(`desync: unknown table ${String(key)}`);\n if (entry.subscription !== \"lazy\") {\n throw new Error(\n `desync('${String(key)}') refused: only a lazy relation can be desynced — an eager relation is always-on and would immediately re-sync.`,\n );\n }\n\n // ADR-0021 §2/§4: desync operates on the whole consistency GROUP — a group is one subscription / one\n // transaction frontier, so reverting one member to dormant reverts them all. Gather the group's tables\n // (a table with no `consistencyGroup` is its own singleton group).\n const targetGroup = entry.consistencyGroup;\n const groupTableKeys = (\n targetGroup == null\n ? [key]\n : (Object.keys(options.registry) as SyncTableName<TRegistry>[]).filter(\n (candidate) => options.registry[candidate]!.consistencyGroup === targetGroup,\n )\n ) as SyncTableName<TRegistry>[];\n\n // Refuse if ANY writable member owes the server unsent/unsettled writes: the truncate clears the\n // journal, so dropping un-acked local intent would be silent data loss. Flush (or discard) those first.\n let owed = 0;\n for (const member of groupTableKeys) {\n if (options.registry[member]!.mode === \"readonly\") continue;\n const stats = await mutationRuntime.readMutationStats(member);\n owed +=\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n }\n if (owed > 0) {\n throw new Error(\n `desync('${String(key)}') refused: ${owed} unsettled mutation(s) in the group's local journal. Flush or discard them first.`,\n );\n }\n\n const activeSync = sync;\n // The group key IS the Electric subscription key (`consistencyGroup ?? shapeKey`); fall back to the\n // registry derivation when sync is disabled.\n const groupKey = activeSync?.groupKeyForTable(key) ?? entry.consistencyGroup ?? entry.shape?.shapeKey;\n // Stop the stream BEFORE truncating so a live shape can't re-populate the rows we just cleared, and\n // revert the durable promotion (a no-op for ephemeral, which never persisted a flag) so the next boot\n // holds the relation dormant again.\n if (activeSync != null && groupKey != null) activeSync.stopGroup(groupKey);\n if (groupKey != null) await clearLazyGroupActivation(pglite, options.registry, groupKey);\n // CRITICAL: delete the group's persisted Electric subscription so a later re-activation re-streams the\n // shape from scratch. Without this it would resume from the old cursor and never re-send the rows we\n // truncate below — leaving the relation permanently missing its pre-desync data.\n if (groupKey != null) await resetSubscriptionsIfRequested(pglite, [groupKey]);\n // Clean-truncate every member's local cluster.\n for (const member of groupTableKeys) {\n await pglite.exec(buildDesyncTableSql(options.registry, member as string));\n }\n };\n\n const transaction: SyncClient<TRegistry>[\"transaction\"] = async ({ mode }, run) => {\n // The block's table handles only COLLECT mutations; the whole set is enqueued atomically as one unit.\n const collected: MutationBatchItem<TRegistry>[] = [];\n const txTables = Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n create: (input: unknown) => {\n collected.push({ table: tableKey, kind: \"create\", input } as MutationBatchItem<TRegistry>);\n },\n update: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({ table: tableKey, kind: \"update\", entityKey, patch } as MutationBatchItem<TRegistry>);\n },\n updateBlind: (entityKey: Record<string, string>, patch: unknown) => {\n collected.push({\n table: tableKey,\n kind: \"update\",\n entityKey,\n patch,\n blind: true,\n } as MutationBatchItem<TRegistry>);\n },\n delete: (entityKey: Record<string, string>) => {\n collected.push({ table: tableKey, kind: \"delete\", entityKey } as MutationBatchItem<TRegistry>);\n },\n },\n ]),\n ) as SyncTransaction<TRegistry>[\"tables\"];\n\n await run({ tables: txTables });\n\n if (collected.length === 0) {\n return { acks: [] };\n }\n\n const unit: WriteUnit = { id: globalThis.crypto.randomUUID(), mode };\n await mutationRuntime.batch(collected, unit);\n\n if (mode === \"optimistic\") {\n // An atomic batch enqueue; the background convergence loop flushes it (no foreground answer).\n void mutationRuntime.flush();\n return { acks: [] };\n }\n\n // Pessimistic: flush-route this unit to the authoritative endpoint and await the per-mutation result.\n return await mutationRuntime.flushUnit(unit.id);\n };\n\n const prepareQuery: SyncClient<TRegistry>[\"prepareQuery\"] = async ({ sql, use }) => {\n // Scan the compiled SQL for the lazy relations it reads (∪ the explicit `use`) and activate them.\n // The compiled SQL is ground truth and Drizzle quotes every relation, so any reference — FROM, JOIN,\n // subquery, WHERE — is caught; over-matching is bounded and harmless (one spurious persistent\n // subscription at worst, never a wrong result). Detection and activation are one step (ADR-0021).\n const toActivate = new Set<string>(use ?? []);\n for (const key of findReferencedLazyKeysInSql(sql, lazyGuardIndex)) toActivate.add(key);\n await ensureSynced([...toActivate] as SyncTableName<TRegistry>[]);\n // Backstop: if a referenced lazy relation is somehow still not active (a failed start, or no group),\n // throw rather than let the query read empty/stale. In the normal path everything scanned was just\n // activated, so this passes.\n assertLazyRefsActivated({\n sql,\n index: lazyGuardIndex,\n isActive: (key) => isSynced(key as SyncTableName<TRegistry>),\n });\n };\n\n const runGuardedQuery = async <TRows extends readonly unknown[]>(\n build: GuardedQueryFn<TRegistry, TRows>,\n use?: readonly SyncTableName<TRegistry>[],\n ): Promise<TRows> => {\n const builder = build(client);\n await prepareQuery({ sql: builder.toSQL().sql, ...(use ? { use } : {}) });\n return builder;\n };\n\n const client: SyncClient<TRegistry> = {\n drizzle: drizzleDb,\n pglite,\n views: buildViews(options.registry),\n tables: Object.fromEntries(\n Object.keys(options.registry).map((tableKey) => [\n tableKey,\n {\n key: tableKey,\n mode: options.registry[tableKey as SyncTableName<TRegistry>]!.mode,\n create: (input: SyncTableCreateInput<TRegistry, typeof tableKey>) =>\n mutate.create(tableKey as SyncTableName<TRegistry>, input),\n update: (entityKey: Record<string, string>, patch: SyncTableUpdateInput<TRegistry, typeof tableKey>) =>\n mutate.update(tableKey as SyncTableName<TRegistry>, entityKey, patch),\n delete: (entityKey: Record<string, string>) => mutate.delete(tableKey as SyncTableName<TRegistry>, entityKey),\n },\n ]),\n ) as SyncClient<TRegistry>[\"tables\"],\n ready,\n status,\n start: async () => {\n await ready;\n },\n stop: async () => {\n // Await any in-flight convergence pass before closing PGlite, so a pass never queries a\n // closed handle.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n // Tear the engine down (abort every shape stream) immediately before closing the DB — the exact\n // point PGlite's own close used to invoke the former extension's close hook (ADR-0032 S1). Order\n // preserved: convergence stop → sync unsubscribe → status → engine close → pglite close.\n await engine.close();\n await pglite.close();\n },\n destroy: async (destroyOptions) => {\n if (!destroyOptions?.force) {\n const stats = await mutationRuntime.readMutationStats();\n const owed =\n stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount + stats.conflictedCount;\n\n if (owed > 0) {\n throw new Error(\n `destroy() refused: ${owed} mutation(s) still owed to the server. Flush them first or call destroy({ force: true }).`,\n );\n }\n }\n\n // Drain any in-flight convergence pass before wiping, so a pass never writes into a store\n // being torn down underneath it.\n await convergenceDriver?.stop();\n sync?.unsubscribe();\n status.isRunning = false;\n options.onStatusChange?.(status);\n await pglite.exec(buildWipeLocalStoreSql(options.registry));\n // Same teardown ordering as `stop`: abort the engine's streams before closing the DB, the moment\n // the former extension close hook fired during `pglite.close()` (ADR-0032 S1).\n await engine.close();\n await pglite.close();\n },\n dropReadCache: async () => {\n await pglite.exec(buildDropReadCacheSql(options.registry));\n await pglite.exec(generateLocalSchemaSql(options.registry));\n // Reset the Electric subscriptions so the rebuilt synced tables re-stream from scratch\n // rather than the bookkeeping believing they are already caught up (ADR-0006).\n await resetSubscriptionsIfRequested(pglite, allGroupSubscriptionKeys(options.registry));\n },\n flush: (table) => mutationRuntime.flush(table),\n reconcile: (table) => mutationRuntime.reconcile(table),\n retryFailed: (table) => mutationRuntime.retryFailed(table),\n recoverSending: (table) => mutationRuntime.recoverSending(table),\n readMutationDetails: (table) => mutationRuntime.readMutationDetails(table),\n mutate,\n discardConflict: (table, entityKey) => mutationRuntime.discardConflict(table, entityKey),\n discardQuarantined: (table, entityKey) => mutationRuntime.discardQuarantined(table, entityKey),\n diagnostics: async (table) => ({\n mutation: await mutationRuntime.readMutationStats(table),\n }),\n // Inspection surface (see the interface doc): straight through to the underlying store, no journal /\n // overlay involvement. The worker facade runs the identical call inside the worker's own client.\n rawQuery: (sql, params, options) => pglite.query(sql, params as unknown[] | undefined, options),\n rawExec: (sql, options) => pglite.exec(sql, options),\n query: (build) => runGuardedQuery(build),\n queryRow: async (build) => {\n const rows = await runGuardedQuery(build);\n return rows[0] ?? null;\n },\n queryRaw: (spec) => runGuardedQuery(spec.build, spec.use),\n queryRawRow: async (spec) => {\n const rows = await runGuardedQuery(spec.build, spec.use);\n return rows[0] ?? null;\n },\n ensureSynced,\n isSynced,\n desync,\n prepareQuery,\n transaction,\n groupReady: async (table) => {\n const activeSync = sync;\n // Sync disabled → local-only: every relation is trivially \"ready\" (nothing to await).\n if (activeSync == null) return;\n const groupKey = activeSync.groupKeyForTable(table as string);\n if (groupKey == null) return;\n await activeSync.groupReady(groupKey);\n },\n // The live-rows seam over PGlite's own `live` extension (ADR-0032 S2 §4) — the EXACT call the React\n // hooks made inline before the seam existed (`pglite.live.query` → `initialResults.rows` + `subscribe`),\n // so the in-process path is unchanged. `pkColumns` is unused here: PGlite's live query already diffs\n // incrementally against its own materialized state; the column set only matters for the worker bridge.\n subscribeLiveRows: async ({ sql, params }, onRows) => {\n const registered = await pglite.live.query<Record<string, unknown>>(sql, params as unknown[]);\n const listener = (results: { rows: Record<string, unknown>[] }) => {\n onRows(results.rows as never);\n };\n registered.subscribe(listener);\n return {\n initialRows: registered.initialResults.rows as never,\n unsubscribe: () => {\n void registered.unsubscribe(listener);\n },\n };\n },\n };\n\n return client;\n}\n\n/**\n * Every persisted subscription key declared by the registry — one per consistency group (ADR-0009\n * decision 2), not per table. Grouped tables share a subscription-state row keyed by their group;\n * ungrouped tables are singleton groups keyed by their own `shapeKey`. Deduped, since several tables\n * collapse onto one group key.\n */\nfunction allGroupSubscriptionKeys<TRegistry extends SyncTableRegistry>(registry: TRegistry): string[] {\n const keys = Object.values(registry)\n .filter((entry) => typeof entry.shape?.shapeKey === \"string\" && entry.shape.shapeKey.length > 0)\n .map((entry) => entry.consistencyGroup ?? entry.shape!.shapeKey);\n return [...new Set(keys)];\n}\n\nasync function resetSubscriptionsIfRequested(pglite: ClientPGlite, keys: string[] | undefined) {\n if (!keys || keys.length === 0) {\n return;\n }\n\n const uniqueKeys = [...new Set(keys.map((key) => key.trim()).filter((key) => key.length > 0))];\n\n if (uniqueKeys.length === 0) {\n return;\n }\n\n await pglite.electric.initMetadataTables();\n await Promise.all(uniqueKeys.map((key) => pglite.electric.deleteSubscription(key)));\n}\n\nfunction createDrizzleDatabase<TRegistry extends SyncTableRegistry>(\n client: ClientPGlite,\n schema: RegistryTables<TRegistry>,\n) {\n const relations = defineRelations(schema) as RegistryRelations<TRegistry>;\n\n const createDatabase = drizzle as unknown as (config: {\n client: ClientPGlite;\n relations: RegistryRelations<TRegistry>;\n }) => PgliteDatabase<RegistryRelations<TRegistry>>;\n\n return createDatabase({ client, relations });\n}\n\nfunction buildSchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction buildViews<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.fromEntries(\n Object.entries(registry).flatMap(([key, entry]) => (entry.view != null ? [[key, entry.view]] : [])),\n ) as RegistryViews<TRegistry>;\n}\n\n/**\n * The tab-side READ handles a worker-attached client exposes (ADR-0032 S2): a build-only Drizzle instance\n * plus the registry views. On the attach client, Drizzle is used only to COMPILE queries to SQL\n * (`.toSQL()`) on the tab — execution happens in the worker via the live-rows bridge / RPC — so it is\n * constructed over a stub client that is never invoked (`construct` stores the client without calling it).\n * The same builders `createSyncClient` uses, so a query built on either client compiles identically.\n */\nexport function buildRegistryReadHandles<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): { drizzle: PgliteDatabase<RegistryRelations<TRegistry>>; views: RegistryViews<TRegistry> } {\n const stubClient = {} as ClientPGlite;\n return {\n drizzle: createDrizzleDatabase(stubClient, buildSchema(registry)),\n views: buildViews(registry),\n };\n}\n\nfunction buildSyncConfigFromRegistry<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n electricUrl: string,\n): SyncConfigInput {\n return {\n electricUrl,\n localSchema: getSyncRegistrySchema(registry),\n tables: Object.fromEntries(Object.entries(registry).map(([key, entry]) => [key, buildSyncTableInput(entry, key)])),\n };\n}\n\nfunction buildSyncTableInput(entry: SyncTableEntry, tableKey: string) {\n const clientProjection = getClientProjection(entry, tableKey);\n\n return {\n name: tableKey,\n mode: entry.mode,\n primaryKey: entry.primaryKey,\n ...(entry.shape !== undefined ? { shape: entry.shape } : {}),\n clientProjection,\n // The read-path apply ladder (strategy + json casts) is resolved by the engine directly from the\n // registry entry via `resolveApplyTarget` (ADR-0029 D1/D2) — `deriveSyncColumnTypes` /\n // `classifyTableApplyStrategy` on the model, never carried through this config surface.\n // Carry the consistency group (ADR-0009 decision 2) so the sync starter buckets grouped tables\n // onto one MultiShapeStream; absent → singleton group.\n ...(entry.consistencyGroup ? { consistencyGroup: entry.consistencyGroup } : {}),\n // Carry the lifecycle axes (ADR-0021) so the sync starter can hold lazy groups out of the eager\n // boot set and provision ephemeral clusters as TEMP; absent → eager/persistent (today's path).\n ...(entry.subscription ? { subscription: entry.subscription } : {}),\n ...(entry.retention ? { retention: entry.retention } : {}),\n };\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n",
7
+ "//#region src/entity.ts\nconst entityKind = Symbol.for(\"drizzle:entityKind\");\nconst hasOwnEntityKind = Symbol.for(\"drizzle:hasOwnEntityKind\");\nfunction is(value, type) {\n\tif (!value || typeof value !== \"object\") return false;\n\tif (value instanceof type) return true;\n\tif (!Object.prototype.hasOwnProperty.call(type, entityKind)) throw new Error(`Class \"${type.name ?? \"<unknown>\"}\" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);\n\tlet cls = Object.getPrototypeOf(value)?.constructor;\n\tif (cls) while (cls) {\n\t\tif (entityKind in cls && cls[entityKind] === type[entityKind]) return true;\n\t\tcls = Object.getPrototypeOf(cls);\n\t}\n\treturn false;\n}\n\n//#endregion\nexport { entityKind, hasOwnEntityKind, is };\n//# sourceMappingURL=entity.js.map",
8
+ "//#region src/column-common.ts\nconst OriginalColumn = Symbol.for(\"drizzle:OriginalColumn\");\n\n//#endregion\nexport { OriginalColumn };\n//# sourceMappingURL=column-common.js.map",
9
+ "import { entityKind } from \"./entity.js\";\nimport { OriginalColumn } from \"./column-common.js\";\n\n//#region src/column.ts\nconst noop = (v) => v;\nnoop.isNoop = true;\nvar Column = class {\n\tstatic [entityKind] = \"Column\";\n\t/** @internal */\n\tcodec;\n\tname;\n\tkeyAsName;\n\tprimary;\n\tnotNull;\n\tdefault;\n\tdefaultFn;\n\tonUpdateFn;\n\thasDefault;\n\tisUnique;\n\tuniqueName;\n\tuniqueType;\n\tdataType;\n\tcolumnType;\n\tenumValues = void 0;\n\tgenerated = void 0;\n\tgeneratedIdentity = void 0;\n\tlength;\n\tisLengthExact;\n\tisAlias;\n\t/** @internal */\n\tconfig;\n\t/** @internal */\n\ttable;\n\t/** @internal */\n\tonInit() {}\n\tconstructor(table, config) {\n\t\tthis.config = config;\n\t\tthis.onInit();\n\t\tthis.table = table;\n\t\tthis.name = config.name;\n\t\tthis.isAlias = false;\n\t\tthis.keyAsName = config.keyAsName;\n\t\tthis.notNull = config.notNull;\n\t\tthis.default = config.default;\n\t\tthis.defaultFn = config.defaultFn;\n\t\tthis.onUpdateFn = config.onUpdateFn;\n\t\tthis.hasDefault = config.hasDefault;\n\t\tthis.primary = config.primaryKey;\n\t\tthis.isUnique = config.isUnique;\n\t\tthis.uniqueName = config.uniqueName;\n\t\tthis.uniqueType = config.uniqueType;\n\t\tthis.dataType = config.dataType;\n\t\tthis.columnType = config.columnType;\n\t\tthis.generated = config.generated;\n\t\tthis.generatedIdentity = config.generatedIdentity;\n\t\tthis.length = config[\"length\"];\n\t\tthis.isLengthExact = config[\"isLengthExact\"];\n\t}\n\tmapFromDriverValue = noop;\n\tmapToDriverValue = noop;\n\t/** @internal */\n\tpostBuild() {\n\t\treturn this;\n\t}\n\t/** @internal */\n\tshouldDisableInsert() {\n\t\treturn this.config.generated !== void 0 && this.config.generated.type !== \"byDefault\";\n\t}\n\t/** @internal */\n\t[OriginalColumn]() {\n\t\treturn this;\n\t}\n};\nfunction getColumnTable(column) {\n\treturn column.table;\n}\n\n//#endregion\nexport { Column, getColumnTable };\n//# sourceMappingURL=column.js.map",
10
+ "//#region src/table.utils.ts\n/** @internal */\nconst TableName = Symbol.for(\"drizzle:Name\");\n\n//#endregion\nexport { TableName };\n//# sourceMappingURL=table.utils.js.map",
11
+ "import { entityKind } from \"./entity.js\";\nimport { TableName } from \"./table.utils.js\";\n\n//#region src/table.ts\n/** @internal */\nconst TableSchema = Symbol.for(\"drizzle:Schema\");\n/** @internal */\nconst TableColumns = Symbol.for(\"drizzle:Columns\");\n/** @internal */\nconst ExtraConfigColumns = Symbol.for(\"drizzle:ExtraConfigColumns\");\n/** @internal */\nconst OriginalName = Symbol.for(\"drizzle:OriginalName\");\n/** @internal */\nconst BaseName = Symbol.for(\"drizzle:BaseName\");\n/** @internal */\nconst IsAlias = Symbol.for(\"drizzle:IsAlias\");\n/** @internal */\nconst ExtraConfigBuilder = Symbol.for(\"drizzle:ExtraConfigBuilder\");\nconst IsDrizzleTable = Symbol.for(\"drizzle:IsDrizzleTable\");\nvar Table = class {\n\tstatic [entityKind] = \"Table\";\n\t/** @internal */\n\tstatic Symbol = {\n\t\tName: TableName,\n\t\tSchema: TableSchema,\n\t\tOriginalName,\n\t\tColumns: TableColumns,\n\t\tExtraConfigColumns,\n\t\tBaseName,\n\t\tIsAlias,\n\t\tExtraConfigBuilder\n\t};\n\t/**\n\t* @internal\n\t* Can be changed if the table is aliased.\n\t*/\n\t[TableName];\n\t/**\n\t* @internal\n\t* Used to store the original name of the table, before any aliasing.\n\t*/\n\t[OriginalName];\n\t/** @internal */\n\t[TableSchema];\n\t/** @internal */\n\t[TableColumns];\n\t/** @internal */\n\t[ExtraConfigColumns];\n\t/**\n\t* @internal\n\t* Used to store the table name before the transformation via the `tableCreator` functions.\n\t*/\n\t[BaseName];\n\t/** @internal */\n\t[IsAlias] = false;\n\t/** @internal */\n\t[IsDrizzleTable] = true;\n\t/** @internal */\n\t[ExtraConfigBuilder] = void 0;\n\tconstructor(name, schema, baseName) {\n\t\tthis[TableName] = this[OriginalName] = name;\n\t\tthis[TableSchema] = schema;\n\t\tthis[BaseName] = baseName;\n\t}\n};\nfunction isTable(table) {\n\treturn typeof table === \"object\" && table !== null && IsDrizzleTable in table;\n}\nfunction getTableName(table) {\n\treturn table[TableName];\n}\nfunction getTableUniqueName(table) {\n\treturn `${table[TableSchema] ?? \"public\"}.${table[TableName]}`;\n}\n\n//#endregion\nexport { BaseName, ExtraConfigBuilder, ExtraConfigColumns, IsAlias, OriginalName, Table, TableColumns, TableSchema, getTableName, getTableUniqueName, isTable };\n//# sourceMappingURL=table.js.map",
12
+ "import { entityKind } from \"./entity.js\";\n\n//#region src/subquery.ts\nvar Subquery = class {\n\tstatic [entityKind] = \"Subquery\";\n\tconstructor(sql, fields, alias, isWith = false, usedTables = []) {\n\t\tthis._ = {\n\t\t\tbrand: \"Subquery\",\n\t\t\tsql,\n\t\t\tselectedFields: fields,\n\t\t\talias,\n\t\t\tisWith,\n\t\t\tusedTables\n\t\t};\n\t}\n};\nvar WithSubquery = class extends Subquery {\n\tstatic [entityKind] = \"WithSubquery\";\n};\n\n//#endregion\nexport { Subquery, WithSubquery };\n//# sourceMappingURL=subquery.js.map",
13
+ "//#region src/tracing-utils.ts\nfunction iife(fn, ...args) {\n\treturn fn(...args);\n}\n\n//#endregion\nexport { iife };\n//# sourceMappingURL=tracing-utils.js.map",
14
+ "import { iife } from \"./tracing-utils.js\";\nimport { npmVersion } from \"./version.js\";\n\n//#region src/tracing.ts\nconst hasTelemetry = false;\n/** @internal */\nconst tracer = { startActiveSpan(name, fn) {\n\treturn fn();\n} };\n\n//#endregion\nexport { hasTelemetry, tracer };\n//# sourceMappingURL=tracing.js.map",
15
+ "//#region src/view-common.ts\nconst ViewBaseConfig = Symbol.for(\"drizzle:ViewBaseConfig\");\n\n//#endregion\nexport { ViewBaseConfig };\n//# sourceMappingURL=view-common.js.map",
16
+ "import { Column } from \"../column.js\";\nimport { IsAlias, OriginalName, Table, TableColumns, TableSchema } from \"../table.js\";\nimport { entityKind, is } from \"../entity.js\";\nimport { Subquery } from \"../subquery.js\";\nimport { TableName } from \"../table.utils.js\";\nimport { tracer } from \"../tracing.js\";\nimport { ViewBaseConfig } from \"../view-common.js\";\n\n//#region src/sql/sql.ts\n/**\n* This class is used to indicate a primitive param value that is used in `sql` tag.\n* It is only used on type level and is never instantiated at runtime.\n* If you see a value of this type in the code, its runtime value is actually the primitive param value.\n*/\nvar FakePrimitiveParam = class {\n\tstatic [entityKind] = \"FakePrimitiveParam\";\n};\nfunction isSQLWrapper(value) {\n\treturn value !== null && value !== void 0 && typeof value.getSQL === \"function\";\n}\nfunction mergeQueries(queries) {\n\tconst result = {\n\t\tsql: \"\",\n\t\tparams: []\n\t};\n\tfor (const query of queries) {\n\t\tresult.sql += query.sql;\n\t\tresult.params.push(...query.params);\n\t}\n\treturn result;\n}\nfunction _mergeQueries(queries) {\n\tconst result = {\n\t\tsql: \"\",\n\t\tparams: []\n\t};\n\tconst sqls = [];\n\tfor (const query of queries) {\n\t\tsqls.push(query.sql);\n\t\tresult.params.push(...query.params);\n\t}\n\tresult._sql = Object.assign(sqls, { raw: sqls });\n\treturn result;\n}\nvar StringChunk = class {\n\tstatic [entityKind] = \"StringChunk\";\n\tvalue;\n\tconstructor(value) {\n\t\tthis.value = Array.isArray(value) ? value : [value];\n\t}\n\tgetSQL() {\n\t\treturn new SQL([this]);\n\t}\n};\nvar SQL = class SQL {\n\tstatic [entityKind] = \"SQL\";\n\t/** @internal */\n\tdecoder = noopDecoder;\n\t/** @internal */\n\tshouldInlineParams = false;\n\t/** @internal */\n\tusedTables = [];\n\tconstructor(queryChunks) {\n\t\tthis.queryChunks = queryChunks;\n\t\tfor (const chunk of queryChunks) if (is(chunk, Table)) {\n\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\t\t\tthis.usedTables.push(schemaName === void 0 ? chunk[Table.Symbol.Name] : schemaName + \".\" + chunk[Table.Symbol.Name]);\n\t\t}\n\t}\n\tappend(query) {\n\t\tthis.queryChunks.push(...query.queryChunks);\n\t\treturn this;\n\t}\n\ttoQuery(config) {\n\t\treturn tracer.startActiveSpan(\"drizzle.buildSQL\", (span) => {\n\t\t\tconst query = this.buildQueryFromSourceParams(this.queryChunks, config);\n\t\t\tspan?.setAttributes({\n\t\t\t\t\"drizzle.query.text\": query.sql,\n\t\t\t\t\"drizzle.query.params\": JSON.stringify(query.params)\n\t\t\t});\n\t\t\treturn query;\n\t\t});\n\t}\n\tbuildQueryFromSourceParams(chunks, _config) {\n\t\tconst config = Object.assign({}, _config, {\n\t\t\tinlineParams: _config.inlineParams || this.shouldInlineParams,\n\t\t\tparamStartIndex: _config.paramStartIndex || { value: 0 }\n\t\t});\n\t\tconst { escapeName, escapeParam, codecs, inlineParams, paramStartIndex, invokeSource } = config;\n\t\tconst mappedChunks = chunks.map((chunk) => {\n\t\t\tif (is(chunk, StringChunk)) return {\n\t\t\t\tsql: chunk.value.join(\"\"),\n\t\t\t\tparams: []\n\t\t\t};\n\t\t\tif (is(chunk, Name)) return {\n\t\t\t\tsql: escapeName(chunk.value),\n\t\t\t\tparams: []\n\t\t\t};\n\t\t\tif (chunk === void 0) return {\n\t\t\t\tsql: \"\",\n\t\t\t\tparams: []\n\t\t\t};\n\t\t\tif (Array.isArray(chunk)) {\n\t\t\t\tconst result = [new StringChunk(\"(\")];\n\t\t\t\tfor (const [i, p] of chunk.entries()) {\n\t\t\t\t\tresult.push(p);\n\t\t\t\t\tif (i < chunk.length - 1) result.push(new StringChunk(\", \"));\n\t\t\t\t}\n\t\t\t\tresult.push(new StringChunk(\")\"));\n\t\t\t\treturn this.buildQueryFromSourceParams(result, config);\n\t\t\t}\n\t\t\tif (is(chunk, SQL)) return this.buildQueryFromSourceParams(chunk.queryChunks, {\n\t\t\t\t...config,\n\t\t\t\tinlineParams: inlineParams || chunk.shouldInlineParams\n\t\t\t});\n\t\t\tif (is(chunk, Table)) {\n\t\t\t\tconst schemaName = chunk[Table.Symbol.Schema];\n\t\t\t\tconst tableName = chunk[Table.Symbol.Name];\n\t\t\t\tif (invokeSource === \"mssql-view-with-schemabinding\") return {\n\t\t\t\t\tsql: (schemaName === void 0 ? escapeName(\"dbo\") : escapeName(schemaName)) + \".\" + escapeName(tableName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === void 0 || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + \".\" + escapeName(tableName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (is(chunk, Column)) {\n\t\t\t\tconst columnName = chunk.name;\n\t\t\t\tif (_config.invokeSource === \"indexes\") return {\n\t\t\t\t\tsql: escapeName(columnName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t\tconst schemaName = invokeSource === \"mssql-check\" ? void 0 : chunk.table[Table.Symbol.Schema];\n\t\t\t\treturn {\n\t\t\t\t\tsql: chunk.isAlias ? escapeName(chunk.name) : chunk.table[IsAlias] || schemaName === void 0 ? escapeName(chunk.table[Table.Symbol.Name]) + \".\" + escapeName(columnName) : escapeName(schemaName) + \".\" + escapeName(chunk.table[Table.Symbol.Name]) + \".\" + escapeName(columnName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (is(chunk, View)) {\n\t\t\t\tconst schemaName = chunk[ViewBaseConfig].schema;\n\t\t\t\tconst viewName = chunk[ViewBaseConfig].name;\n\t\t\t\treturn {\n\t\t\t\t\tsql: schemaName === void 0 || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + \".\" + escapeName(viewName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (is(chunk, Param)) {\n\t\t\t\tif (is(chunk.value, SQL)) return this.buildQueryFromSourceParams([chunk.value], config);\n\t\t\t\tconst useCodecs = codecs && is(chunk.encoder, Column);\n\t\t\t\tif (is(chunk.value, Placeholder)) {\n\t\t\t\t\tconst escaped = escapeParam(paramStartIndex.value++, chunk);\n\t\t\t\t\tchunk.codec = useCodecs ? (value) => codecs.apply(chunk.encoder, \"normalizeParam\", value) : void 0;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tsql: useCodecs ? codecs.apply(chunk.encoder, \"castParam\", escaped) : escaped,\n\t\t\t\t\t\tparams: [chunk]\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlet mappedValue;\n\t\t\t\tif (chunk.value === null) mappedValue = chunk.value;\n\t\t\t\telse {\n\t\t\t\t\tmappedValue = chunk.encoder.mapToDriverValue.isNoop ? chunk.value : chunk.encoder.mapToDriverValue(chunk.value);\n\t\t\t\t\tif (is(mappedValue, SQL)) return this.buildQueryFromSourceParams([mappedValue], config);\n\t\t\t\t\tif (useCodecs) mappedValue = codecs.apply(chunk.encoder, \"normalizeParam\", mappedValue);\n\t\t\t\t}\n\t\t\t\tif (inlineParams) return {\n\t\t\t\t\tsql: this.mapInlineParam(mappedValue, config),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t\tconst escaped = escapeParam(paramStartIndex.value++, mappedValue);\n\t\t\t\treturn {\n\t\t\t\t\tsql: useCodecs ? codecs.apply(chunk.encoder, \"castParam\", escaped) : escaped,\n\t\t\t\t\tparams: [mappedValue]\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (is(chunk, Placeholder)) return {\n\t\t\t\tsql: escapeParam(paramStartIndex.value++, chunk),\n\t\t\t\tparams: [chunk]\n\t\t\t};\n\t\t\tif (is(chunk, SQL.Aliased) && chunk.fieldAlias !== void 0) return {\n\t\t\t\tsql: (chunk.origin !== void 0 ? escapeName(chunk.origin) + \".\" : \"\") + escapeName(chunk.fieldAlias),\n\t\t\t\tparams: []\n\t\t\t};\n\t\t\tif (is(chunk, Subquery)) {\n\t\t\t\tif (chunk._.isWith) return {\n\t\t\t\t\tsql: escapeName(chunk._.alias),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk(\"(\"),\n\t\t\t\t\tchunk._.sql,\n\t\t\t\t\tnew StringChunk(\") \"),\n\t\t\t\t\tnew Name(chunk._.alias)\n\t\t\t\t], config);\n\t\t\t}\n\t\t\tif (typeof chunk === \"function\" && \"enumName\" in chunk) {\n\t\t\t\tif (\"schema\" in chunk && chunk.schema) return {\n\t\t\t\t\tsql: escapeName(chunk.schema) + \".\" + escapeName(chunk.enumName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t\treturn {\n\t\t\t\t\tsql: escapeName(chunk.enumName),\n\t\t\t\t\tparams: []\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (isSQLWrapper(chunk)) {\n\t\t\t\tif (chunk.shouldOmitSQLParens?.()) return this.buildQueryFromSourceParams([chunk.getSQL()], config);\n\t\t\t\treturn this.buildQueryFromSourceParams([\n\t\t\t\t\tnew StringChunk(\"(\"),\n\t\t\t\t\tchunk.getSQL(),\n\t\t\t\t\tnew StringChunk(\")\")\n\t\t\t\t], config);\n\t\t\t}\n\t\t\tif (inlineParams) return {\n\t\t\t\tsql: this.mapInlineParam(chunk, config),\n\t\t\t\tparams: []\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsql: escapeParam(paramStartIndex.value++, chunk),\n\t\t\t\tparams: [chunk]\n\t\t\t};\n\t\t});\n\t\tif (_config.tagged) return _mergeQueries(mappedChunks);\n\t\treturn mergeQueries(mappedChunks);\n\t}\n\tmapInlineParam(chunk, { escapeString }) {\n\t\tif (chunk === null) return \"null\";\n\t\tif (typeof chunk === \"number\" || typeof chunk === \"boolean\" || typeof chunk === \"bigint\") return chunk.toString();\n\t\tif (typeof chunk === \"string\") return escapeString(chunk);\n\t\tif (typeof chunk === \"object\") {\n\t\t\tconst mappedValueAsString = chunk.toString();\n\t\t\tif (mappedValueAsString === \"[object Object]\") return escapeString(JSON.stringify(chunk));\n\t\t\treturn escapeString(mappedValueAsString);\n\t\t}\n\t\tthrow new Error(\"Unexpected param value: \" + chunk);\n\t}\n\tgetSQL() {\n\t\treturn this;\n\t}\n\tas(alias) {\n\t\tif (alias === void 0) return this;\n\t\treturn new SQL.Aliased(this, alias);\n\t}\n\tmapWith(decoder) {\n\t\tthis.decoder = typeof decoder === \"function\" ? { mapFromDriverValue: decoder } : decoder;\n\t\treturn this;\n\t}\n\tnullable() {\n\t\treturn this;\n\t}\n\tinlineParams() {\n\t\tthis.shouldInlineParams = true;\n\t\treturn this;\n\t}\n\t/**\n\t* This method is used to conditionally include a part of the query.\n\t*\n\t* @param condition - Condition to check\n\t* @returns itself if the condition is `true`, otherwise `undefined`\n\t*/\n\tif(condition) {\n\t\treturn condition ? this : void 0;\n\t}\n};\n/**\n* Any DB name (table, column, index etc.)\n*/\nvar Name = class {\n\tstatic [entityKind] = \"Name\";\n\tbrand;\n\tconstructor(value) {\n\t\tthis.value = value;\n\t}\n\tgetSQL() {\n\t\treturn new SQL([this]);\n\t}\n};\n/**\n* Any DB name (table, column, index etc.)\n* @deprecated Use `sql.identifier` instead.\n*/\nfunction name(value) {\n\treturn new Name(value);\n}\nfunction isDriverValueEncoder(value) {\n\treturn typeof value === \"object\" && value !== null && \"mapToDriverValue\" in value && typeof value.mapToDriverValue === \"function\";\n}\nconst noopDecoder = { mapFromDriverValue: (value) => value };\nnoopDecoder.mapFromDriverValue.isNoop = true;\nconst noopEncoder = { mapToDriverValue: (value) => value };\nnoopEncoder.mapToDriverValue.isNoop = true;\nfunction isNoop(mapper) {\n\treturn mapper.isNoop;\n}\nconst noopMapper = {\n\t...noopDecoder,\n\t...noopEncoder\n};\n/** Parameter value that is optionally bound to an encoder (for example, a column). */\nvar Param = class {\n\tstatic [entityKind] = \"Param\";\n\tbrand;\n\t/**\n\t* @param value - Parameter value\n\t* @param encoder - Encoder to convert the value to a driver parameter\n\t*/\n\tconstructor(value, encoder = noopEncoder, codec) {\n\t\tthis.value = value;\n\t\tthis.encoder = encoder;\n\t\tthis.codec = codec;\n\t}\n\tgetSQL() {\n\t\treturn new SQL([this]);\n\t}\n};\n/** @deprecated Use `sql.param` instead. */\nfunction param(value, encoder) {\n\treturn new Param(value, encoder);\n}\nfunction sql(strings, ...params) {\n\tconst queryChunks = [];\n\tif (params.length > 0 || strings.length > 0 && strings[0] !== \"\") queryChunks.push(new StringChunk(strings[0]));\n\tfor (const [paramIndex, param] of params.entries()) queryChunks.push(param, new StringChunk(strings[paramIndex + 1]));\n\treturn new SQL(queryChunks);\n}\n(function(_sql) {\n\tfunction empty() {\n\t\treturn new SQL([]);\n\t}\n\t_sql.empty = empty;\n\tfunction fromList(list) {\n\t\treturn new SQL(list);\n\t}\n\t_sql.fromList = fromList;\n\tfunction raw(str) {\n\t\treturn new SQL([new StringChunk(str)]);\n\t}\n\t_sql.raw = raw;\n\tfunction join(chunks, separator) {\n\t\tconst result = [];\n\t\tfor (const [i, chunk] of chunks.entries()) {\n\t\t\tif (i > 0 && separator !== void 0) result.push(separator);\n\t\t\tresult.push(chunk);\n\t\t}\n\t\treturn new SQL(result);\n\t}\n\t_sql.join = join;\n\tfunction identifier(value) {\n\t\treturn new Name(value);\n\t}\n\t_sql.identifier = identifier;\n\tfunction placeholder(name) {\n\t\treturn new Placeholder(name);\n\t}\n\t_sql.placeholder = placeholder;\n\tfunction param(value, encoder) {\n\t\treturn new Param(value, encoder);\n\t}\n\t_sql.param = param;\n\tfunction comment(input) {\n\t\tconst encoded = sqlCommenter(input);\n\t\tif (!encoded.length) return void 0;\n\t\treturn sql.raw(encoded);\n\t}\n\t_sql.comment = comment;\n})(sql || (sql = {}));\nfunction sqlCommenter(input) {\n\tconst encoded = sqlCommenter.encodeInput(input);\n\tif (!encoded.length) return \"\";\n\treturn `/*${encoded}*/`;\n}\n(function(_sqlCommenter) {\n\tfunction merge(input1, input2) {\n\t\tlet encoded;\n\t\tif (typeof input1 === \"object\" && typeof input2 === \"object\") encoded = encodeInput({\n\t\t\t...input1,\n\t\t\t...input2\n\t\t});\n\t\telse if (input1 && input2) encoded = [encodeInput(input1), encodeInput(input2)].filter((i) => i.length).join(\",\");\n\t\telse if (input2) encoded = encodeInput(input2);\n\t\telse if (input1) encoded = encodeInput(input1);\n\t\telse return \"\";\n\t\tif (!encoded.length) return \"\";\n\t\treturn `/*${encoded}*/`;\n\t}\n\t_sqlCommenter.merge = merge;\n\tfunction encodeInput(input) {\n\t\tif (typeof input === \"string\") {\n\t\t\tif (!input.length) return input;\n\t\t\treturn sanitizeStringInput(input);\n\t\t}\n\t\tconst parts = [];\n\t\tfor (const [key, value] of Object.entries(input)) {\n\t\t\tif (value === null || value === void 0 || value === \"\") continue;\n\t\t\tconst encodedKey = sanitizeObjectElement(key);\n\t\t\tconst encodedValue = sanitizeObjectElement(String(value));\n\t\t\tparts.push(`${encodedKey}='${encodedValue}'`);\n\t\t}\n\t\tif (!parts.length) return \"\";\n\t\treturn parts.sort().join(\",\");\n\t}\n\t_sqlCommenter.encodeInput = encodeInput;\n\tfunction sanitizeObjectElement(key) {\n\t\treturn encodeURIComponent(key).replace(/'/g, `\\\\'`);\n\t}\n\t_sqlCommenter.sanitizeObjectElement = sanitizeObjectElement;\n\tfunction sanitizeStringInput(input) {\n\t\treturn input.replace(/\\/\\*/g, \"/ *\").replace(/\\*\\//g, \"* /\");\n\t}\n\t_sqlCommenter.sanitizeStringInput = sanitizeStringInput;\n})(sqlCommenter || (sqlCommenter = {}));\n(function(_SQL) {\n\tclass Aliased {\n\t\tstatic [entityKind] = \"SQL.Aliased\";\n\t\t/** @internal */\n\t\tisSelectionField = false;\n\t\t/** @internal */\n\t\torigin;\n\t\tconstructor(sql, fieldAlias) {\n\t\t\tthis.sql = sql;\n\t\t\tthis.fieldAlias = fieldAlias;\n\t\t}\n\t\tgetSQL() {\n\t\t\treturn this.sql;\n\t\t}\n\t\t/** @internal */\n\t\tclone() {\n\t\t\treturn new Aliased(this.sql, this.fieldAlias);\n\t\t}\n\t}\n\t_SQL.Aliased = Aliased;\n})(SQL || (SQL = {}));\nvar Placeholder = class {\n\tstatic [entityKind] = \"Placeholder\";\n\tconstructor(name) {\n\t\tthis.name = name;\n\t}\n\tgetSQL() {\n\t\treturn new SQL([this]);\n\t}\n};\n/** @deprecated Use `sql.placeholder` instead. */\nfunction placeholder(name) {\n\treturn new Placeholder(name);\n}\nfunction fillPlaceholders(params, values) {\n\treturn params.map((p) => {\n\t\tif (is(p, Placeholder)) {\n\t\t\tif (!(p.name in values)) throw new Error(`No value for placeholder \"${p.name}\" was provided`);\n\t\t\treturn values[p.name];\n\t\t}\n\t\tif (is(p, Param) && is(p.value, Placeholder)) {\n\t\t\tif (!(p.value.name in values)) throw new Error(`No value for placeholder \"${p.value.name}\" was provided`);\n\t\t\tconst value = values[p.value.name];\n\t\t\tif (value === null) return value;\n\t\t\tconst mapped = p.encoder.mapToDriverValue.isNoop ? value : p.encoder.mapToDriverValue(value);\n\t\t\treturn p.codec ? p.codec(mapped) : mapped;\n\t\t}\n\t\treturn p;\n\t});\n}\nconst IsDrizzleView = Symbol.for(\"drizzle:IsDrizzleView\");\nvar View = class {\n\tstatic [entityKind] = \"View\";\n\t/** @internal */\n\t[ViewBaseConfig];\n\t/** @internal */\n\t[IsDrizzleView] = true;\n\t/** @internal */\n\tget [TableName]() {\n\t\treturn this[ViewBaseConfig].name;\n\t}\n\t/** @internal */\n\tget [TableSchema]() {\n\t\treturn this[ViewBaseConfig].schema;\n\t}\n\t/** @internal */\n\tget [IsAlias]() {\n\t\treturn this[ViewBaseConfig].isAlias;\n\t}\n\t/** @internal */\n\tget [OriginalName]() {\n\t\treturn this[ViewBaseConfig].originalName;\n\t}\n\t/** @internal */\n\tget [TableColumns]() {\n\t\treturn this[ViewBaseConfig].selectedFields;\n\t}\n\tconstructor({ name, schema, selectedFields, query }) {\n\t\tthis[ViewBaseConfig] = {\n\t\t\tname,\n\t\t\toriginalName: name,\n\t\t\tschema,\n\t\t\tselectedFields,\n\t\t\tquery,\n\t\t\tisExisting: !query,\n\t\t\tisAlias: false\n\t\t};\n\t}\n};\nfunction isView(view) {\n\treturn typeof view === \"object\" && view !== null && IsDrizzleView in view;\n}\nfunction getViewName(view) {\n\treturn view[ViewBaseConfig].name;\n}\nColumn.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\nSubquery.prototype.getSQL = function() {\n\treturn new SQL([this]);\n};\n\n//#endregion\nexport { FakePrimitiveParam, Name, Param, Placeholder, SQL, StringChunk, View, fillPlaceholders, getViewName, isDriverValueEncoder, isNoop, isSQLWrapper, isView, name, noopDecoder, noopEncoder, noopMapper, param, placeholder, sql, sqlCommenter };\n//# sourceMappingURL=sql.js.map",
17
+ "import { is } from \"./entity.js\";\nimport { Column } from \"./column.js\";\nimport { Table, getTableName } from \"./table.js\";\nimport { Param, SQL, View } from \"./sql/sql.js\";\nimport { Subquery } from \"./subquery.js\";\nimport { ViewBaseConfig } from \"./view-common.js\";\n\n//#region src/utils.ts\n/** @internal */\nfunction mapResultRow(columns, row, joinsNotNullableMap) {\n\tconst nullifyMap = {};\n\tconst result = columns.reduce((result, { path, field, codec, arrayDimensions }, columnIndex) => {\n\t\tlet decoder;\n\t\tif (is(field, Column)) decoder = field;\n\t\telse if (is(field, SQL)) decoder = field.decoder;\n\t\telse if (is(field, Subquery)) decoder = field._.sql.decoder;\n\t\telse decoder = field.sql.decoder;\n\t\tlet node = result;\n\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) if (pathChunkIndex < path.length - 1) {\n\t\t\tif (!(pathChunk in node)) node[pathChunk] = {};\n\t\t\tnode = node[pathChunk];\n\t\t} else {\n\t\t\tconst rawValue = row[columnIndex];\n\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(codec ? codec(rawValue, arrayDimensions) : rawValue);\n\t\t\tif (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n\t\t\t\tconst objectName = path[0];\n\t\t\t\tif (!(objectName in nullifyMap)) nullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\telse if (typeof nullifyMap[objectName] === \"string\" && nullifyMap[objectName] !== getTableName(field.table)) nullifyMap[objectName] = false;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}, {});\n\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) if (typeof tableName === \"string\" && !joinsNotNullableMap[tableName]) result[objectName] = null;\n\t}\n\treturn result;\n}\n/** @internal bypass bundle-time filtering */\nconst FnConstructor = Object.getPrototypeOf(() => null).constructor;\n/** @internal */\nfunction makeJitQueryMapperInner(columns, joinsNotNullableMap = {}) {\n\tconst preFn = [];\n\tconst fn = [];\n\tfn.push(`const [ ${columns.map((_, i) => `c${i}`).join(\", \")} ] = rows[i];`);\n\tconst nullifyMap = {};\n\tconst objectIds = {};\n\tconst decodes = Array.from({ length: columns.length });\n\tfor (let idx = 0; idx < columns.length; ++idx) {\n\t\tconst { field, path, codec, arrayDimensions } = columns[idx];\n\t\tlet decoder;\n\t\tlet decoderStr;\n\t\tlet decoderFieldDestructure;\n\t\tlet isColumn = false;\n\t\tif (is(field, Column)) {\n\t\t\tisColumn = true;\n\t\t\tdecoder = field;\n\t\t\tdecoderFieldDestructure = `field: decoder${idx}`;\n\t\t} else if (is(field, SQL)) {\n\t\t\tdecoder = field.decoder;\n\t\t\tdecoderFieldDestructure = `field: { decoder: decoder${idx} }`;\n\t\t} else if (is(field, Subquery)) {\n\t\t\tdecoder = field._.sql.decoder;\n\t\t\tdecoderFieldDestructure = `field: { _: { sql: { decoder: decoder${idx} } } }`;\n\t\t} else {\n\t\t\tdecoder = field.sql.decoder;\n\t\t\tdecoderFieldDestructure = `field: { sql: { decoder: decoder${idx} } }`;\n\t\t}\n\t\tdecoderStr = `decoder${idx}.mapFromDriverValue`;\n\t\tif (decoder.mapFromDriverValue.isNoop) decoderStr = \"\";\n\t\tif (decoderStr) preFn.push(`const { ${decoderFieldDestructure}${codec ? `, codec: codec${idx}` : \"\"} } = columns[${idx}];`);\n\t\telse if (codec) preFn.push(`const { codec: codec${idx} } = columns[${idx}];`);\n\t\tconst colStr = `c${idx}`;\n\t\tlet decodedValue = colStr;\n\t\tif (codec) decodedValue = `codec${idx}(${decodedValue}, ${arrayDimensions})`;\n\t\tif (decoderStr) decodedValue = `${decoderStr}(${decodedValue})`;\n\t\tdecodes[idx] = colStr === decodedValue ? `${colStr}` : `${colStr} === null ? ${colStr} : ${decodedValue}`;\n\t\tif (path.length !== 2 || !isColumn) continue;\n\t\tif (objectIds[path[0]] === void 0) objectIds[path[0]] = [`c${idx}`];\n\t\telse objectIds[path[0]]?.push(`c${idx}`);\n\t\tconst [objectName] = path;\n\t\tconst tableName = getTableName(field.table);\n\t\tnullifyMap[objectName] = joinsNotNullableMap[tableName] ? false : typeof nullifyMap[objectName] === \"string\" ? nullifyMap[objectName] === tableName ? tableName : false : tableName;\n\t}\n\tfn.push(`mapped[i] = {`);\n\tlet currentObjectPath = [];\n\tfor (let idx = 0; idx < columns.length; ++idx) {\n\t\tconst { path } = columns[idx];\n\t\tconst jsonPath = path.map((e) => JSON.stringify(e));\n\t\tconst decodedValue = decodes[idx];\n\t\tconst objectPath = path.slice(0, -1);\n\t\tlet commonLen = 0;\n\t\twhile (commonLen < currentObjectPath.length && commonLen < objectPath.length && currentObjectPath[commonLen] === objectPath[commonLen]) commonLen++;\n\t\tfor (let d = currentObjectPath.length - 1; d >= commonLen; --d) fn.push(`${\"\t\".repeat(d + 1)}},`);\n\t\tfor (let d = commonLen; d < objectPath.length; ++d) fn.push(`${\"\t\".repeat(d + 1)}${jsonPath[d]}: ${d === 0 && objectPath.length === 1 && typeof nullifyMap[path[0]] === \"string\" ? `${objectIds[path[0]]?.map((c) => `${c} === null`).join(\" && \")} ? null : {` : \"{\"}`);\n\t\tcurrentObjectPath = objectPath;\n\t\tfn.push(`${\"\t\".repeat(path.length)}${jsonPath[path.length - 1]}: ${decodedValue},`);\n\t}\n\tfor (let d = currentObjectPath.length - 1; d >= 0; --d) fn.push(`${\"\t\".repeat(d + 1)}},`);\n\tfn.push(`};`);\n\treturn `${preFn.length ? `${preFn.join(\"\\n\t\")}\\n\\t` : \"\"}for (let i = 0; i < length; ++i) {\n\t\t${fn.join(\"\\n\t\t\")}\n\t}`;\n}\nfunction makeJitQueryMapper(columns, joinsNotNullableMap) {\n\tconst internals = `\\t\"use strict\";\n\tconst { columns } = this;\n\tconst { length } = rows;\n\tconst mapped = Array.from({ length });\n\t${makeJitQueryMapperInner(columns, joinsNotNullableMap)}\n\treturn mapped;\n\t//# sourceURL=drizzle:jit-query-mapper`;\n\treturn Object.assign(new FnConstructor(\"rows\", internals).bind({ columns }), { body: `function jitQueryMapper (rows) {\\n${internals}\\n}` });\n}\n/** @internal */\nfunction jitCompatCheck(isEnabled) {\n\tif (!isEnabled) return false;\n\ttry {\n\t\tconst res = new FnConstructor(\"input\", \"\\\"use strict\\\"; return input;\")(true);\n\t\tif (res !== true) {\n\t\t\tconsole.warn(\"Unable to use jit mappers due to incompatibility: corrupted jit function output.\\nFalling back to premade mappers.\\nError details:\");\n\t\t\tconsole.error(`Expected to receive \\`true\\`, got: ${res}`);\n\t\t}\n\t\treturn true;\n\t} catch (e) {\n\t\tconsole.warn(\"Unable to use jit mappers due to incompatibility.\\nFalling back to premade mappers.\\nError details:\");\n\t\tconsole.error(e);\n\t\treturn false;\n\t}\n}\nfunction makeDefaultQueryMapper(columns, joinsNotNullableMap) {\n\tconst interpretedData = columns.map(({ field, codec, arrayDimensions, path }) => {\n\t\tlet processNullifyMap;\n\t\tlet decoderSrc;\n\t\tif (is(field, Column)) {\n\t\t\tdecoderSrc = field;\n\t\t\tif (joinsNotNullableMap && path.length === 2) {\n\t\t\t\tconst objectName = path[0];\n\t\t\t\tprocessNullifyMap = (nullifyMap, value) => {\n\t\t\t\t\tif (!(objectName in nullifyMap)) nullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\t\telse if (typeof nullifyMap[objectName] === \"string\" && nullifyMap[objectName] !== getTableName(field.table)) nullifyMap[objectName] = false;\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (is(field, SQL)) decoderSrc = field.decoder;\n\t\telse if (is(field, Subquery)) decoderSrc = field._.sql.decoder;\n\t\telse decoderSrc = field.sql.decoder;\n\t\tlet decoder;\n\t\tif (decoderSrc.mapFromDriverValue.isNoop) decoder = codec ? (v) => codec(v, arrayDimensions) : void 0;\n\t\telse decoder = codec ? (v) => decoderSrc.mapFromDriverValue(codec(v, arrayDimensions)) : (v) => decoderSrc.mapFromDriverValue(v);\n\t\treturn [decoder, processNullifyMap];\n\t});\n\treturn ((rows) => rows.map((row) => {\n\t\tconst nullifyMap = {};\n\t\tconst result = columns.reduce((result, { path }, columnIndex) => {\n\t\t\tlet node = result;\n\t\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) if (pathChunkIndex < path.length - 1) {\n\t\t\t\tif (!(pathChunk in node)) node[pathChunk] = {};\n\t\t\t\tnode = node[pathChunk];\n\t\t\t} else {\n\t\t\t\tconst [decoder, processNullifyMap] = interpretedData[columnIndex];\n\t\t\t\tconst rawValue = row[columnIndex];\n\t\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder ? decoder(rawValue) : rawValue;\n\t\t\t\tprocessNullifyMap?.(nullifyMap, value);\n\t\t\t}\n\t\t\treturn result;\n\t\t}, {});\n\t\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) if (typeof tableName === \"string\" && !joinsNotNullableMap[tableName]) result[objectName] = null;\n\t\t}\n\t\treturn result;\n\t}));\n}\nfunction make$ReturningResponseMapper(returningIds, generatedIds) {\n\tif (!returningIds) return;\n\treturn ({ insertId, affectedRows }) => {\n\t\tconst returningResponse = [];\n\t\tlet j = 0;\n\t\tfor (let i = insertId; i < insertId + affectedRows; i++) {\n\t\t\tfor (const column of returningIds) {\n\t\t\t\tconst key = returningIds[0].path[0];\n\t\t\t\tif (is(column.field, Column)) {\n\t\t\t\t\tif (column.field.primary && column.field.autoIncrement) returningResponse.push({ [key]: i });\n\t\t\t\t\tif (column.field.defaultFn && generatedIds) returningResponse.push({ [key]: generatedIds[j][key] });\n\t\t\t\t}\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\treturn returningResponse;\n\t};\n}\n/** @internal */\nfunction orderSelectedFields(fields, pathPrefix, codecs) {\n\treturn Object.entries(fields).reduce((result, [name, field]) => {\n\t\tif (typeof name !== \"string\") return result;\n\t\tconst newPath = pathPrefix ? [...pathPrefix, name] : [name];\n\t\tif (is(field, Column)) result.push({\n\t\t\tpath: newPath,\n\t\t\tfield,\n\t\t\tcodec: codecs?.get(field, \"normalize\"),\n\t\t\tarrayDimensions: field.dimensions,\n\t\t\tcolumn: field\n\t\t});\n\t\telse if (is(field, SQL) || is(field, SQL.Aliased)) {\n\t\t\tconst col = getColumnFromDecoder(field);\n\t\t\tresult.push(col ? {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield,\n\t\t\t\tcodec: codecs?.get(col, \"normalize\"),\n\t\t\t\tarrayDimensions: col.dimensions,\n\t\t\t\tcolumn: col\n\t\t\t} : {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield\n\t\t\t});\n\t\t} else if (is(field, Subquery)) {\n\t\t\tlet column;\n\t\t\tconst entry = Object.values(field._.selectedFields)[0];\n\t\t\tlet fieldDecoder;\n\t\t\tif (is(entry, Column)) {\n\t\t\t\tcolumn = entry;\n\t\t\t\tfieldDecoder = entry;\n\t\t\t} else if (is(entry, SQL)) {\n\t\t\t\tcolumn = getColumnFromDecoder(entry);\n\t\t\t\tfieldDecoder = entry.decoder;\n\t\t\t} else {\n\t\t\t\tcolumn = getColumnFromDecoder(entry);\n\t\t\t\tfieldDecoder = entry.sql.decoder;\n\t\t\t}\n\t\t\tif (fieldDecoder) field._.sql.decoder = fieldDecoder;\n\t\t\tresult.push(column ? {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield,\n\t\t\t\tcodec: codecs?.get(column, \"normalize\"),\n\t\t\t\tarrayDimensions: column.dimensions,\n\t\t\t\tcolumn\n\t\t\t} : {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield\n\t\t\t});\n\t\t} else if (is(field, Table)) result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath, codecs));\n\t\telse result.push(...orderSelectedFields(field, newPath, codecs));\n\t\treturn result;\n\t}, []);\n}\nfunction getColumnFromDecoder(source) {\n\tconst query = source.getSQL();\n\tif (is(query.decoder, Column)) return query.decoder;\n}\nfunction haveSameKeys(left, right) {\n\tconst leftKeys = Object.keys(left);\n\tconst rightKeys = Object.keys(right);\n\tif (leftKeys.length !== rightKeys.length) return false;\n\tfor (const [index, key] of leftKeys.entries()) if (key !== rightKeys[index]) return false;\n\treturn true;\n}\n/** @internal */\nfunction mapUpdateSet(table, values) {\n\tconst entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {\n\t\tif (is(value, SQL) || is(value, Column)) return [key, value];\n\t\telse return [key, new Param(value, table[Table.Symbol.Columns][key])];\n\t});\n\tif (entries.length === 0) throw new Error(\"No values to set\");\n\treturn Object.fromEntries(entries);\n}\n/** @internal */\nfunction applyMixins(baseClass, extendedClasses) {\n\tfor (const extendedClass of extendedClasses) for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n\t\tif (name === \"constructor\") continue;\n\t\tObject.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null));\n\t}\n}\n/**\n* @deprecated\n* Use `getColumns` instead\n*/\nfunction getTableColumns(table) {\n\treturn table[Table.Symbol.Columns];\n}\nfunction getViewSelectedFields(view) {\n\treturn view[ViewBaseConfig].selectedFields;\n}\nfunction getColumns(table) {\n\treturn is(table, Table) ? table[Table.Symbol.Columns] : is(table, View) ? table[ViewBaseConfig].selectedFields : table._.selectedFields;\n}\n/** @internal */\nfunction getTableLikeName(table) {\n\treturn is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];\n}\n/** @internal */\nfunction getColumnNameAndConfig(a, b) {\n\treturn {\n\t\tname: typeof a === \"string\" && a.length > 0 ? a : \"\",\n\t\tconfig: typeof a === \"object\" ? a : b\n\t};\n}\nfunction isConfig(data) {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tif (data.constructor.name !== \"Object\") return false;\n\tif (\"logger\" in data) {\n\t\tconst type = typeof data[\"logger\"];\n\t\tif (type !== \"boolean\" && (type !== \"object\" || typeof data[\"logger\"][\"logQuery\"] !== \"function\") && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"schema\" in data) {\n\t\tconst type = typeof data[\"schema\"];\n\t\tif (type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"relations\" in data) {\n\t\tconst type = typeof data[\"relations\"];\n\t\tif (type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"connection\" in data) {\n\t\tconst type = typeof data[\"connection\"];\n\t\tif (type !== \"string\" && type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"client\" in data) {\n\t\tconst type = typeof data[\"client\"];\n\t\tif (type !== \"object\" && type !== \"function\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"jit\" in data) {\n\t\tconst type = typeof data[\"jit\"];\n\t\tif (type !== \"boolean\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"codecs\" in data) {\n\t\tconst type = typeof data[\"connection\"];\n\t\tif (type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (Object.keys(data).length === 0) return true;\n\treturn false;\n}\nconst textDecoder = typeof TextDecoder === \"undefined\" ? null : new TextDecoder();\nfunction assertUnreachable(_x) {\n\tthrow new Error(\"Didn't expect to get here\");\n}\nfunction isWithEnum(value) {\n\treturn (typeof value === \"object\" && value !== null || typeof value === \"function\") && \"enumValues\" in value && Array.isArray(value.enumValues) && value.enumValues.length > 0;\n}\nconst CONSTANTS = {\n\tINT8_MIN: -128,\n\tINT8_MAX: 127,\n\tINT8_UNSIGNED_MAX: 255,\n\tINT16_MIN: -32768,\n\tINT16_MAX: 32767,\n\tINT16_UNSIGNED_MAX: 65535,\n\tINT24_MIN: -8388608,\n\tINT24_MAX: 8388607,\n\tINT24_UNSIGNED_MAX: 16777215,\n\tINT32_MIN: -2147483648,\n\tINT32_MAX: 2147483647,\n\tINT32_UNSIGNED_MAX: 4294967295,\n\tINT48_MIN: -0x800000000000,\n\tINT48_MAX: 0x7fffffffffff,\n\tINT48_UNSIGNED_MAX: 0xffffffffffff,\n\tINT64_MIN: -9223372036854775808n,\n\tINT64_MAX: 9223372036854775807n,\n\tINT64_UNSIGNED_MAX: 18446744073709551615n\n};\nfunction base64ToUint8Array(base64) {\n\tif (!base64) return new Uint8Array(0);\n\tconst binary = atob(base64);\n\tconst len = binary.length;\n\tconst bytes = new Uint8Array(len);\n\tfor (let i = 0; i < len; ++i) bytes[i] = binary.charCodeAt(i);\n\treturn bytes;\n}\n\n//#endregion\nexport { CONSTANTS, FnConstructor, applyMixins, assertUnreachable, base64ToUint8Array, getColumnFromDecoder, getColumnNameAndConfig, getColumns, getTableColumns, getTableLikeName, getViewSelectedFields, haveSameKeys, isConfig, isWithEnum, jitCompatCheck, make$ReturningResponseMapper, makeDefaultQueryMapper, makeJitQueryMapper, mapResultRow, mapUpdateSet, orderSelectedFields, textDecoder };\n//# sourceMappingURL=utils.js.map",
18
+ "//#region src/pg-core/array.ts\nfunction parsePgArrayValue(arrayString, startFrom, inQuotes) {\n\tfor (let i = startFrom; i < arrayString.length; i++) {\n\t\tconst char = arrayString[i];\n\t\tif (char === \"\\\\\") {\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\"\") return [arrayString.slice(startFrom, i).replace(/\\\\/g, \"\"), i + 1];\n\t\tif (inQuotes) continue;\n\t\tif (char === \",\" || char === \"}\") return [arrayString.slice(startFrom, i).replace(/\\\\/g, \"\"), i];\n\t}\n\treturn [arrayString.slice(startFrom).replace(/\\\\/g, \"\"), arrayString.length];\n}\nfunction parsePgNestedArray(arrayString, startFrom = 0) {\n\tconst result = [];\n\tlet i = startFrom;\n\tlet lastCharIsComma = false;\n\twhile (i < arrayString.length) {\n\t\tconst char = arrayString[i];\n\t\tif (char === \",\") {\n\t\t\tif (lastCharIsComma || i === startFrom) result.push(\"\");\n\t\t\tlastCharIsComma = true;\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tlastCharIsComma = false;\n\t\tif (char === \"\\\\\") {\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"\\\"\") {\n\t\t\tconst [value, startFrom] = parsePgArrayValue(arrayString, i + 1, true);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\t\tif (char === \"}\") return [result, i + 1];\n\t\tif (char === \"{\") {\n\t\t\tconst [value, startFrom] = parsePgNestedArray(arrayString, i + 1);\n\t\t\tresult.push(value);\n\t\t\ti = startFrom;\n\t\t\tcontinue;\n\t\t}\n\t\tconst [value, newStartFrom] = parsePgArrayValue(arrayString, i, false);\n\t\tresult.push(value);\n\t\ti = newStartFrom;\n\t}\n\treturn [result, i];\n}\nfunction parsePgArray(arrayString) {\n\tconst [result] = parsePgNestedArray(arrayString, 1);\n\treturn result;\n}\nfunction makePgArray(array) {\n\treturn `{${array.map((item) => {\n\t\tif (Array.isArray(item)) return makePgArray(item);\n\t\tif (typeof item === \"string\") return `\"${item.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, \"\\\\\\\"\")}\"`;\n\t\treturn `${item}`;\n\t}).join(\",\")}}`;\n}\n\n//#endregion\nexport { makePgArray, parsePgArray, parsePgNestedArray };\n//# sourceMappingURL=array.js.map",
19
+ "//#region src/pg-core/columns/postgis_extension/utils.ts\nfunction hexToBytes(hex) {\n\tconst bytes = [];\n\tfor (let c = 0; c < hex.length; c += 2) bytes.push(Number.parseInt(hex.slice(c, c + 2), 16));\n\treturn new Uint8Array(bytes);\n}\nfunction bytesToFloat64(bytes, offset) {\n\tconst buffer = /* @__PURE__ */ new ArrayBuffer(8);\n\tconst view = new DataView(buffer);\n\tfor (let i = 0; i < 8; i++) view.setUint8(i, bytes[offset + i]);\n\treturn view.getFloat64(0, true);\n}\nfunction parseEWKB(hex) {\n\tconst bytes = hexToBytes(hex);\n\tlet offset = 0;\n\tconst byteOrder = bytes[offset];\n\toffset += 1;\n\tconst view = new DataView(bytes.buffer);\n\tconst geomType = view.getUint32(offset, byteOrder === 1);\n\toffset += 4;\n\tlet srid;\n\tif (geomType & 536870912) {\n\t\tsrid = view.getUint32(offset, byteOrder === 1);\n\t\toffset += 4;\n\t}\n\tif ((geomType & 65535) === 1) {\n\t\tconst x = bytesToFloat64(bytes, offset);\n\t\toffset += 8;\n\t\tconst y = bytesToFloat64(bytes, offset);\n\t\toffset += 8;\n\t\treturn {\n\t\t\tsrid,\n\t\t\tpoint: [x, y]\n\t\t};\n\t}\n\tthrow new Error(\"Unsupported geometry type\");\n}\n\n//#endregion\nexport { parseEWKB };\n//# sourceMappingURL=utils.js.map",
20
+ "import { entityKind } from \"./entity.js\";\n\n//#region src/codecs.ts\nconst noopCodecs = {};\nconst arrayToItemTypeCodecNameMap = {\n\tcast: \"cast\",\n\tcastArray: \"cast\",\n\tcastInJson: \"castInJson\",\n\tcastArrayInJson: \"castInJson\",\n\tcastParam: \"castParam\",\n\tcastArrayParam: \"castParam\",\n\tnormalize: \"normalize\",\n\tnormalizeArray: \"normalize\",\n\tnormalizeInJson: \"normalizeInJson\",\n\tnormalizeArrayInJson: \"normalizeInJson\",\n\tnormalizeParam: \"normalizeParam\",\n\tnormalizeParamArray: \"normalizeParam\"\n};\nconst itemToArrayTypeCodecNameMap = {\n\tcast: \"castArray\",\n\tcastArray: \"castArray\",\n\tcastInJson: \"castArrayInJson\",\n\tcastArrayInJson: \"castArrayInJson\",\n\tcastParam: \"castArrayParam\",\n\tcastArrayParam: \"castArrayParam\",\n\tnormalize: \"normalizeArray\",\n\tnormalizeArray: \"normalizeArray\",\n\tnormalizeInJson: \"normalizeArrayInJson\",\n\tnormalizeArrayInJson: \"normalizeArrayInJson\",\n\tnormalizeParam: \"normalizeParamArray\",\n\tnormalizeParamArray: \"normalizeParamArray\"\n};\nvar CodecsCollection = class {\n\tstatic [entityKind] = \"CodecsCollection\";\n\tconstructor(resolveTypes, codecs = noopCodecs) {\n\t\tthis.resolveTypes = resolveTypes;\n\t\tthis.codecs = codecs;\n\t}\n\tget(column, type, override) {\n\t\tconst sqlType = override ?? column.codec;\n\t\tif (!sqlType) return void 0;\n\t\tconst codecType = column.dimensions ? itemToArrayTypeCodecNameMap[type] : arrayToItemTypeCodecNameMap[type];\n\t\treturn this.codecs[sqlType]?.[codecType];\n\t}\n\tapply(column, type, value, override) {\n\t\tconst sqlType = override ?? column.codec;\n\t\tif (!sqlType) return value;\n\t\tconst codecType = column.dimensions ? itemToArrayTypeCodecNameMap[type] : arrayToItemTypeCodecNameMap[type];\n\t\tconst codec = this.codecs[sqlType]?.[codecType];\n\t\tif (!codec) return value;\n\t\tif (codecType === \"castParam\" || codecType === \"castArrayParam\") return codec(value, column, column.dimensions);\n\t\treturn codec(value, column.dimensions);\n\t}\n};\nfunction refineCodecs(source, extension = {}) {\n\tconst keys = new Set([...Object.keys(source), ...Object.keys(extension)]).values();\n\tconst result = {};\n\tfor (const k of keys) {\n\t\tif (!(k in extension)) {\n\t\t\tresult[k] = source[k] ? { ...source[k] } : void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!(k in source) || extension[k] === void 0) {\n\t\t\tresult[k] = extension[k] ? { ...extension[k] } : void 0;\n\t\t\tcontinue;\n\t\t}\n\t\tconst innerKeys = new Set([...Object.keys(extension[k]), ...Object.keys(source[k] ?? {})]).values();\n\t\tresult[k] = {};\n\t\tfor (const ik of innerKeys) result[k][ik] = ik in extension[k] ? extension[k][ik] : source[k]?.[ik];\n\t}\n\treturn result;\n}\n\n//#endregion\nexport { CodecsCollection, noopCodecs, refineCodecs };\n//# sourceMappingURL=codecs.js.map",
21
+ "import { makePgArray, parsePgArray } from \"./array.js\";\nimport { parseEWKB } from \"./columns/postgis_extension/utils.js\";\nimport { refineCodecs } from \"../codecs.js\";\nimport { sql } from \"../sql/sql.js\";\n\n//#region src/pg-core/codecs.ts\nconst PG_ALIAS_TO_TYPE_MAP = {\n\tint2: \"smallint\",\n\tinteger: \"int\",\n\tint4: \"int\",\n\tint8: \"bigint\",\n\tdecimal: \"numeric\",\n\treal: \"float4\",\n\tdouble: \"float8\",\n\t\"double precision\": \"float8\",\n\tserial2: \"smallserial\",\n\tserial4: \"serial\",\n\tserial8: \"bigserial\",\n\tcharacter: \"char\",\n\t\"character varying\": \"varchar\",\n\t\"time with time zone\": \"timetz\",\n\t\"time without time zone\": \"time\",\n\t\"timestamp with time zone\": \"timestamptz\",\n\t\"timestamp without time zone\": \"timestamp\",\n\tboolean: \"bool\",\n\t\"bit varying\": \"varbit\"\n};\nfunction resolvePgTypeAlias(type) {\n\treturn PG_ALIAS_TO_TYPE_MAP[type] ?? type;\n}\nconst unionsTypeTable = {\n\tsmallint: {\n\t\tsmallint: \"smallint\",\n\t\tint: \"int\",\n\t\tbigint: \"bigint:number\",\n\t\t\"bigint:number\": \"bigint:number\",\n\t\t\"bigint:string\": \"bigint:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"smallint\",\n\t\tserial: \"int\",\n\t\tbigserial: \"bigint:number\",\n\t\t\"bigserial:number\": \"bigint:number\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\tint: {\n\t\tsmallint: \"int\",\n\t\tint: \"int\",\n\t\tbigint: \"bigint:number\",\n\t\t\"bigint:number\": \"bigint:number\",\n\t\t\"bigint:string\": \"bigint:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"int\",\n\t\tserial: \"int\",\n\t\tbigserial: \"bigint:number\",\n\t\t\"bigserial:number\": \"bigint:number\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\tbigint: {\n\t\tsmallint: \"bigint\",\n\t\tint: \"bigint\",\n\t\tbigint: \"bigint\",\n\t\t\"bigint:number\": \"bigint\",\n\t\t\"bigint:string\": \"bigint\",\n\t\tnumeric: \"numeric:bigint\",\n\t\t\"numeric:number\": \"numeric:bigint\",\n\t\t\"numeric:bigint\": \"numeric:bigint\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"bigint\",\n\t\tserial: \"bigint\",\n\t\tbigserial: \"bigint\",\n\t\t\"bigserial:number\": \"bigint\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\t\"bigint:number\": {\n\t\tsmallint: \"bigint:number\",\n\t\tint: \"bigint:number\",\n\t\tbigint: \"bigint:number\",\n\t\t\"bigint:number\": \"bigint:number\",\n\t\t\"bigint:string\": \"bigint:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"bigint:number\",\n\t\tserial: \"bigint:number\",\n\t\tbigserial: \"bigint:number\",\n\t\t\"bigserial:number\": \"bigint:number\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\t\"bigint:string\": {\n\t\tsmallint: \"bigint:string\",\n\t\tint: \"bigint:string\",\n\t\tbigint: \"bigint:string\",\n\t\t\"bigint:number\": \"bigint:string\",\n\t\t\"bigint:string\": \"bigint:string\",\n\t\tnumeric: \"numeric\",\n\t\t\"numeric:number\": \"numeric\",\n\t\t\"numeric:bigint\": \"numeric\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"bigint:string\",\n\t\tserial: \"bigint:string\",\n\t\tbigserial: \"bigint:string\",\n\t\t\"bigserial:number\": \"bigint:string\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\tnumeric: {\n\t\tsmallint: \"numeric\",\n\t\tint: \"numeric\",\n\t\tbigint: \"numeric\",\n\t\t\"bigint:number\": \"numeric\",\n\t\t\"bigint:string\": \"numeric\",\n\t\tnumeric: \"numeric\",\n\t\t\"numeric:number\": \"numeric\",\n\t\t\"numeric:bigint\": \"numeric\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"numeric\",\n\t\tserial: \"numeric\",\n\t\tbigserial: \"numeric\",\n\t\t\"bigserial:number\": \"numeric\"\n\t},\n\t\"numeric:number\": {\n\t\tsmallint: \"numeric:number\",\n\t\tint: \"numeric:number\",\n\t\tbigint: \"numeric:number\",\n\t\t\"bigint:number\": \"numeric:number\",\n\t\t\"bigint:string\": \"numeric:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"numeric:number\",\n\t\tserial: \"numeric:number\",\n\t\tbigserial: \"numeric:number\",\n\t\t\"bigserial:number\": \"numeric:number\"\n\t},\n\t\"numeric:bigint\": {\n\t\tsmallint: \"numeric:bigint\",\n\t\tint: \"numeric:bigint\",\n\t\tbigint: \"numeric:bigint\",\n\t\t\"bigint:number\": \"numeric:bigint\",\n\t\t\"bigint:string\": \"numeric:bigint\",\n\t\tnumeric: \"numeric:bigint\",\n\t\t\"numeric:number\": \"numeric:bigint\",\n\t\t\"numeric:bigint\": \"numeric:bigint\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"numeric:bigint\",\n\t\tserial: \"numeric:bigint\",\n\t\tbigserial: \"numeric:bigint\",\n\t\t\"bigserial:number\": \"numeric:bigint\"\n\t},\n\tfloat4: {\n\t\tsmallint: \"float4\",\n\t\tint: \"float4\",\n\t\tbigint: \"float4\",\n\t\t\"bigint:number\": \"float4\",\n\t\t\"bigint:string\": \"float4\",\n\t\tnumeric: \"float4\",\n\t\t\"numeric:number\": \"float4\",\n\t\t\"numeric:bigint\": \"float4\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"float4\",\n\t\tserial: \"float4\",\n\t\tbigserial: \"float4\",\n\t\t\"bigserial:number\": \"float4\"\n\t},\n\tfloat8: {\n\t\tsmallint: \"float8\",\n\t\tint: \"float8\",\n\t\tbigint: \"float8\",\n\t\t\"bigint:number\": \"float8\",\n\t\t\"bigint:string\": \"float8\",\n\t\tnumeric: \"float8\",\n\t\t\"numeric:number\": \"float8\",\n\t\t\"numeric:bigint\": \"float8\",\n\t\tfloat4: \"float8\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"float8\",\n\t\tserial: \"float8\",\n\t\tbigserial: \"float8\",\n\t\t\"bigserial:number\": \"float8\"\n\t},\n\tmoney: { money: \"money\" },\n\tsmallserial: {\n\t\tsmallint: \"smallint\",\n\t\tint: \"int\",\n\t\tbigint: \"bigint:number\",\n\t\t\"bigint:number\": \"bigint:number\",\n\t\t\"bigint:string\": \"bigint:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"smallint\",\n\t\tserial: \"int\",\n\t\tbigserial: \"bigint:number\",\n\t\t\"bigserial:number\": \"bigint:number\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\tserial: {\n\t\tsmallint: \"int\",\n\t\tint: \"int\",\n\t\tbigint: \"bigint:number\",\n\t\t\"bigint:number\": \"bigint:number\",\n\t\t\"bigint:string\": \"bigint:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"int\",\n\t\tserial: \"int\",\n\t\tbigserial: \"bigint:number\",\n\t\t\"bigserial:number\": \"bigint:number\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\tbigserial: {\n\t\tsmallint: \"bigint\",\n\t\tint: \"bigint\",\n\t\tbigint: \"bigint\",\n\t\t\"bigint:number\": \"bigint\",\n\t\t\"bigint:string\": \"bigint\",\n\t\tnumeric: \"numeric:bigint\",\n\t\t\"numeric:number\": \"numeric:bigint\",\n\t\t\"numeric:bigint\": \"numeric:bigint\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"bigint\",\n\t\tserial: \"bigint\",\n\t\tbigserial: \"bigint\",\n\t\t\"bigserial:number\": \"bigint\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\t\"bigserial:number\": {\n\t\tsmallint: \"bigint:number\",\n\t\tint: \"bigint:number\",\n\t\tbigint: \"bigint:number\",\n\t\t\"bigint:number\": \"bigint:number\",\n\t\t\"bigint:string\": \"bigint:number\",\n\t\tnumeric: \"numeric:number\",\n\t\t\"numeric:number\": \"numeric:number\",\n\t\t\"numeric:bigint\": \"numeric:number\",\n\t\tfloat4: \"float4\",\n\t\tfloat8: \"float8\",\n\t\tsmallserial: \"bigint:number\",\n\t\tserial: \"bigint:number\",\n\t\tbigserial: \"bigint:number\",\n\t\t\"bigserial:number\": \"bigint:number\",\n\t\toid: \"oid\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regprocedure\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoperator\",\n\t\tregclass: \"regclass\",\n\t\tregtype: \"regtype\",\n\t\tregrole: \"regrole\",\n\t\tregnamespace: \"regnamespace\",\n\t\tregconfig: \"regconfig\",\n\t\tregdictionary: \"regdictionary\"\n\t},\n\tchar: {\n\t\tchar: \"char\",\n\t\tvarchar: \"char\",\n\t\ttext: \"char\"\n\t},\n\tvarchar: {\n\t\tchar: \"varchar\",\n\t\tvarchar: \"varchar\",\n\t\ttext: \"varchar\"\n\t},\n\ttext: {\n\t\tchar: \"text\",\n\t\tvarchar: \"text\",\n\t\ttext: \"text\"\n\t},\n\tbytea: { bytea: \"bytea\" },\n\tdate: {\n\t\tdate: \"date\",\n\t\t\"date:string\": \"date\",\n\t\ttimestamp: \"timestamp\",\n\t\t\"timestamp:string\": \"timestamp\",\n\t\ttimestamptz: \"timestamptz\",\n\t\t\"timestamptz:string\": \"timestamptz\"\n\t},\n\t\"date:string\": {\n\t\tdate: \"date:string\",\n\t\t\"date:string\": \"date:string\",\n\t\ttimestamp: \"timestamp:string\",\n\t\t\"timestamp:string\": \"timestamp:string\",\n\t\ttimestamptz: \"timestamptz:string\",\n\t\t\"timestamptz:string\": \"timestamptz:string\"\n\t},\n\ttime: {\n\t\ttime: \"time\",\n\t\ttimetz: \"timetz\"\n\t},\n\ttimetz: {\n\t\ttime: \"timetz\",\n\t\ttimetz: \"timetz\"\n\t},\n\ttimestamp: {\n\t\tdate: \"timestamp\",\n\t\t\"date:string\": \"timestamp\",\n\t\ttimestamp: \"timestamp\",\n\t\t\"timestamp:string\": \"timestamp\",\n\t\ttimestamptz: \"timestamptz\",\n\t\t\"timestamptz:string\": \"timestamptz\"\n\t},\n\t\"timestamp:string\": {\n\t\tdate: \"timestamp:string\",\n\t\t\"date:string\": \"timestamp:string\",\n\t\ttimestamp: \"timestamp:string\",\n\t\t\"timestamp:string\": \"timestamp:string\",\n\t\ttimestamptz: \"timestamptz:string\",\n\t\t\"timestamptz:string\": \"timestamptz:string\"\n\t},\n\ttimestamptz: {\n\t\tdate: \"timestamptz\",\n\t\t\"date:string\": \"timestamptz\",\n\t\ttimestamp: \"timestamptz\",\n\t\t\"timestamp:string\": \"timestamptz\",\n\t\ttimestamptz: \"timestamptz\",\n\t\t\"timestamptz:string\": \"timestamptz\"\n\t},\n\t\"timestamptz:string\": {\n\t\tdate: \"timestamptz:string\",\n\t\t\"date:string\": \"timestamptz:string\",\n\t\ttimestamp: \"timestamptz:string\",\n\t\t\"timestamp:string\": \"timestamptz:string\",\n\t\ttimestamptz: \"timestamptz:string\",\n\t\t\"timestamptz:string\": \"timestamptz:string\"\n\t},\n\tinterval: {\n\t\tinterval: \"interval\",\n\t\t\"interval:tuple\": \"interval\"\n\t},\n\t\"interval:tuple\": {\n\t\tinterval: \"interval:tuple\",\n\t\t\"interval:tuple\": \"interval:tuple\"\n\t},\n\tbool: { bool: \"bool\" },\n\tenum: { enum: \"enum\" },\n\tpoint: {\n\t\tpoint: \"point\",\n\t\t\"point:tuple\": \"point\"\n\t},\n\t\"point:tuple\": {\n\t\tpoint: \"point:tuple\",\n\t\t\"point:tuple\": \"point:tuple\"\n\t},\n\tline: {\n\t\tline: \"line\",\n\t\t\"line:tuple\": \"line\"\n\t},\n\t\"line:tuple\": {\n\t\tline: \"line:tuple\",\n\t\t\"line:tuple\": \"line:tuple\"\n\t},\n\tlseg: { lseg: \"lseg\" },\n\tbox: { box: \"box\" },\n\tpath: { path: \"path\" },\n\tpolygon: { polygon: \"polygon\" },\n\tcircle: { circle: \"circle\" },\n\tcidr: {\n\t\tcidr: \"cidr\",\n\t\tinet: \"inet\"\n\t},\n\tinet: {\n\t\tcidr: \"inet\",\n\t\tinet: \"inet\"\n\t},\n\tmacaddr: {\n\t\tmacaddr: \"macaddr\",\n\t\tmacaddr8: \"macaddr\"\n\t},\n\tmacaddr8: {\n\t\tmacaddr: \"macaddr8\",\n\t\tmacaddr8: \"macaddr8\"\n\t},\n\tbit: {\n\t\tbit: \"bit\",\n\t\tvarbit: \"bit\"\n\t},\n\tvarbit: {\n\t\tbit: \"varbit\",\n\t\tvarbit: \"varbit\"\n\t},\n\ttsvector: { tsvector: \"tsvector\" },\n\ttsquery: { tsquery: \"tsquery\" },\n\tuuid: { uuid: \"uuid\" },\n\txml: { xml: \"xml\" },\n\tjson: { json: \"json\" },\n\tjsonb: { jsonb: \"jsonb\" },\n\tint4range: { int4range: \"int4range\" },\n\tint8range: { int8range: \"int8range\" },\n\tnumrange: { numrange: \"numrange\" },\n\ttsrange: { tsrange: \"tsrange\" },\n\ttstzrange: { tstzrange: \"tstzrange\" },\n\tdaterange: { daterange: \"daterange\" },\n\tint4multirange: { int4multirange: \"int4multirange\" },\n\tint8multirange: { int8multirange: \"int8multirange\" },\n\tnummultirange: { nummultirange: \"nummultirange\" },\n\ttsmultirange: { tsmultirange: \"tsmultirange\" },\n\ttstzmultirange: { tstzmultirange: \"tstzmultirange\" },\n\tdatemultirange: { datemultirange: \"datemultirange\" },\n\toid: {\n\t\tsmallint: \"oid\",\n\t\tint: \"oid\",\n\t\tbigint: \"oid\",\n\t\t\"bigint:number\": \"oid\",\n\t\t\"bigint:string\": \"oid\",\n\t\tsmallserial: \"oid\",\n\t\tserial: \"oid\",\n\t\tbigserial: \"oid\",\n\t\t\"bigserial:number\": \"oid\",\n\t\toid: \"oid\",\n\t\tregproc: \"oid\",\n\t\tregprocedure: \"oid\",\n\t\tregoper: \"oid\",\n\t\tregoperator: \"oid\",\n\t\tregclass: \"oid\",\n\t\tregtype: \"oid\",\n\t\tregrole: \"oid\",\n\t\tregnamespace: \"oid\",\n\t\tregconfig: \"oid\",\n\t\tregdictionary: \"oid\"\n\t},\n\tregproc: {\n\t\tsmallint: \"regproc\",\n\t\tint: \"regproc\",\n\t\tbigint: \"regproc\",\n\t\t\"bigint:number\": \"regproc\",\n\t\t\"bigint:string\": \"regproc\",\n\t\tsmallserial: \"regproc\",\n\t\tserial: \"regproc\",\n\t\tbigserial: \"regproc\",\n\t\t\"bigserial:number\": \"regproc\",\n\t\toid: \"regproc\",\n\t\tregproc: \"regproc\",\n\t\tregprocedure: \"regproc\"\n\t},\n\tregprocedure: {\n\t\tsmallint: \"regprocedure\",\n\t\tint: \"regprocedure\",\n\t\tbigint: \"regprocedure\",\n\t\t\"bigint:number\": \"regprocedure\",\n\t\t\"bigint:string\": \"regprocedure\",\n\t\tsmallserial: \"regprocedure\",\n\t\tserial: \"regprocedure\",\n\t\tbigserial: \"regprocedure\",\n\t\t\"bigserial:number\": \"regprocedure\",\n\t\toid: \"regprocedure\",\n\t\tregproc: \"regprocedure\",\n\t\tregprocedure: \"regprocedure\"\n\t},\n\tregoper: {\n\t\tsmallint: \"regoper\",\n\t\tint: \"regoper\",\n\t\tbigint: \"regoper\",\n\t\t\"bigint:number\": \"regoper\",\n\t\t\"bigint:string\": \"regoper\",\n\t\tsmallserial: \"regoper\",\n\t\tserial: \"regoper\",\n\t\tbigserial: \"regoper\",\n\t\t\"bigserial:number\": \"regoper\",\n\t\toid: \"regoper\",\n\t\tregoper: \"regoper\",\n\t\tregoperator: \"regoper\"\n\t},\n\tregoperator: {\n\t\tsmallint: \"regoperator\",\n\t\tint: \"regoperator\",\n\t\tbigint: \"regoperator\",\n\t\t\"bigint:number\": \"regoperator\",\n\t\t\"bigint:string\": \"regoperator\",\n\t\tsmallserial: \"regoperator\",\n\t\tserial: \"regoperator\",\n\t\tbigserial: \"regoperator\",\n\t\t\"bigserial:number\": \"regoperator\",\n\t\toid: \"regoperator\",\n\t\tregoper: \"regoperator\",\n\t\tregoperator: \"regoperator\"\n\t},\n\tregclass: {\n\t\tsmallint: \"regclass\",\n\t\tint: \"regclass\",\n\t\tbigint: \"regclass\",\n\t\t\"bigint:number\": \"regclass\",\n\t\t\"bigint:string\": \"regclass\",\n\t\tsmallserial: \"regclass\",\n\t\tserial: \"regclass\",\n\t\tbigserial: \"regclass\",\n\t\t\"bigserial:number\": \"regclass\",\n\t\toid: \"regclass\",\n\t\tregclass: \"regclass\"\n\t},\n\tregtype: {\n\t\tsmallint: \"regtype\",\n\t\tint: \"regtype\",\n\t\tbigint: \"regtype\",\n\t\t\"bigint:number\": \"regtype\",\n\t\t\"bigint:string\": \"regtype\",\n\t\tsmallserial: \"regtype\",\n\t\tserial: \"regtype\",\n\t\tbigserial: \"regtype\",\n\t\t\"bigserial:number\": \"regtype\",\n\t\toid: \"regtype\",\n\t\tregtype: \"regtype\"\n\t},\n\tregrole: {\n\t\tsmallint: \"regrole\",\n\t\tint: \"regrole\",\n\t\tbigint: \"regrole\",\n\t\t\"bigint:number\": \"regrole\",\n\t\t\"bigint:string\": \"regrole\",\n\t\tsmallserial: \"regrole\",\n\t\tserial: \"regrole\",\n\t\tbigserial: \"regrole\",\n\t\t\"bigserial:number\": \"regrole\",\n\t\toid: \"regrole\",\n\t\tregrole: \"regrole\"\n\t},\n\tregnamespace: {\n\t\tsmallint: \"regnamespace\",\n\t\tint: \"regnamespace\",\n\t\tbigint: \"regnamespace\",\n\t\t\"bigint:number\": \"regnamespace\",\n\t\t\"bigint:string\": \"regnamespace\",\n\t\tsmallserial: \"regnamespace\",\n\t\tserial: \"regnamespace\",\n\t\tbigserial: \"regnamespace\",\n\t\t\"bigserial:number\": \"regnamespace\",\n\t\toid: \"regnamespace\",\n\t\tregnamespace: \"regnamespace\"\n\t},\n\tregconfig: {\n\t\tsmallint: \"regconfig\",\n\t\tint: \"regconfig\",\n\t\tbigint: \"regconfig\",\n\t\t\"bigint:number\": \"regconfig\",\n\t\t\"bigint:string\": \"regconfig\",\n\t\tsmallserial: \"regconfig\",\n\t\tserial: \"regconfig\",\n\t\tbigserial: \"regconfig\",\n\t\t\"bigserial:number\": \"regconfig\",\n\t\toid: \"regconfig\",\n\t\tregconfig: \"regconfig\"\n\t},\n\tregdictionary: {\n\t\tsmallint: \"regdictionary\",\n\t\tint: \"regdictionary\",\n\t\tbigint: \"regdictionary\",\n\t\t\"bigint:number\": \"regdictionary\",\n\t\t\"bigint:string\": \"regdictionary\",\n\t\tsmallserial: \"regdictionary\",\n\t\tserial: \"regdictionary\",\n\t\tbigserial: \"regdictionary\",\n\t\t\"bigserial:number\": \"regdictionary\",\n\t\toid: \"regdictionary\",\n\t\tregdictionary: \"regdictionary\"\n\t}\n};\nconst castToText = (name) => sql`${name}::text`;\nconst castToTextArr = (name, arrayDimensions) => sql`${name}::text${sql.raw(\"[]\".repeat(arrayDimensions))}`;\n/** Used for cases when casting requires to unwrap and rebuild arrays\n*\n* @example\n* string_mtx::text[][] // can be casted to array directly\n*\n* encode(bytea_mtx, 'base64')[][] // invalid syntax, cast requires unwrapping and rebuilding array\n*/\nconst arrayCompatCast = (cast) => (name, arrayDimensions) => {\n\tif (!arrayDimensions) return cast(name);\n\tconst aliases = [];\n\tfor (let i = 0; i < arrayDimensions; i++) aliases.push(sql.identifier(`s${i}`));\n\tlet indexed = name;\n\tfor (const alias of aliases) indexed = sql`${indexed}[${alias}]`;\n\tlet expression = sql`array(\\\nselect ${cast(indexed)} \\\nfrom generate_subscripts(${name}, ${sql.raw(arrayDimensions.toString())}) ${aliases[arrayDimensions - 1]} \\\norder by ${aliases[arrayDimensions - 1]})`;\n\tfor (let dim = arrayDimensions - 1; dim > 0; dim--) expression = sql`array(\\\nselect ${expression} \\\nfrom generate_subscripts(${name}, ${sql.raw(dim.toString())}) ${aliases[dim - 1]} \\\norder by ${aliases[dim - 1]})`;\n\treturn sql`case when ${name} is null then null else ${expression} end`;\n};\n/** Used to recursively apply value normalizer to array of unknown dimensions */\nconst arrayCompatNormalize = (normalize) => {\n\tconst loop = (value, arrayDimensions) => {\n\t\tconst innerDimensions = arrayDimensions - 1;\n\t\tif (arrayDimensions > 1) for (let i = 0; i < value.length; ++i) loop(value[i], innerDimensions);\n\t\telse for (let i = 0; i < value.length; ++i) value[i] = normalize(value[i]);\n\t\treturn value;\n\t};\n\treturn loop;\n};\n/** Doesn't mutate original data - used for insertions */\nconst arrayCompatNormalizeInput = (normalize, transformToPgArray = false) => {\n\tconst loop = (value, arrayDimensions) => {\n\t\tconst innerDimensions = arrayDimensions - 1;\n\t\tconst out = Array.from({ length: value.length });\n\t\tif (arrayDimensions > 1) for (let i = 0; i < value.length; ++i) out[i] = loop(value[i], innerDimensions);\n\t\telse for (let i = 0; i < value.length; ++i) out[i] = normalize(value[i]);\n\t\treturn out;\n\t};\n\treturn transformToPgArray ? (v, d) => makePgArray(loop(v, d)) : loop;\n};\n/** Parses a raw PG array text representation, then applies a per-item normalizer */\nconst parsePgArrayAndNormalize = (normalize) => {\n\tconst codec = arrayCompatNormalize(normalize);\n\treturn (value, arrayDimensions) => codec(parsePgArray(value), arrayDimensions);\n};\nconst parseLineTuple = (v) => {\n\tconst [a, b, c] = v.slice(1, -1).split(\",\");\n\treturn [\n\t\tNumber.parseFloat(a),\n\t\tNumber.parseFloat(b),\n\t\tNumber.parseFloat(c)\n\t];\n};\nconst parseLineABC = (v) => {\n\tconst [a, b, c] = v.slice(1, -1).split(\",\");\n\treturn {\n\t\ta: Number.parseFloat(a),\n\t\tb: Number.parseFloat(b),\n\t\tc: Number.parseFloat(c)\n\t};\n};\nconst parsePointTuple = (v) => {\n\tconst [x, y] = v.slice(1, -1).split(\",\");\n\treturn [Number.parseFloat(x), Number.parseFloat(y)];\n};\nconst parsePointXY = (v) => {\n\tconst [x, y] = v.slice(1, -1).split(\",\");\n\treturn {\n\t\tx: Number.parseFloat(x),\n\t\ty: Number.parseFloat(y)\n\t};\n};\nconst parseGeometryTuple = (v) => parseEWKB(v).point;\nconst parseGeometryXY = (v) => {\n\tconst parsed = parseEWKB(v);\n\treturn {\n\t\tx: parsed.point[0],\n\t\ty: parsed.point[1]\n\t};\n};\nconst textToDate = (v) => new Date(v);\nconst textToDateWithTz = (v) => /* @__PURE__ */ new Date(v + \"+0000\");\nconst parsePgVector = (v) => {\n\tconst body = v.slice(1, -1);\n\tif (body.length === 0) return [];\n\treturn body.split(\",\").map(Number.parseFloat);\n};\nconst genericPgCodecs = {\n\tbytea: {\n\t\tcastInJson: (name) => sql`encode(${name}, 'base64')`,\n\t\tcastArrayInJson: arrayCompatCast((name) => sql`encode(${name}, 'base64')`),\n\t\tnormalizeInJson: (v) => Buffer.from(v, \"base64\"),\n\t\tnormalizeArrayInJson: arrayCompatNormalize((v) => Buffer.from(v, \"base64\"))\n\t},\n\tbigint: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalizeInJson: BigInt,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(BigInt)\n\t},\n\t\"bigint:number\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: Number,\n\t\tnormalizeArray: arrayCompatNormalize(Number),\n\t\tnormalizeInJson: Number,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(Number)\n\t},\n\t\"bigint:string\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr\n\t},\n\tbigserial: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalizeInJson: BigInt,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(BigInt),\n\t\tnormalize: BigInt,\n\t\tnormalizeArray: arrayCompatNormalize(BigInt)\n\t},\n\t\"bigserial:number\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: Number,\n\t\tnormalizeArray: arrayCompatNormalize(Number),\n\t\tnormalizeInJson: Number,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(Number)\n\t},\n\tdate: {\n\t\tnormalizeInJson: textToDate,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(textToDate)\n\t},\n\t\"date:string\": {},\n\tenum: {\n\t\tcastArray: castToTextArr,\n\t\tnormalizeParamArray: makePgArray\n\t},\n\t\"geometry(point)\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: parseGeometryXY,\n\t\tnormalizeArray: arrayCompatNormalize(parseGeometryXY),\n\t\tnormalizeInJson: parseGeometryXY,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parseGeometryXY)\n\t},\n\t\"geometry(point):tuple\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: parseGeometryTuple,\n\t\tnormalizeArray: arrayCompatNormalize(parseGeometryTuple),\n\t\tnormalizeInJson: parseGeometryTuple,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parseGeometryTuple)\n\t},\n\tinterval: { castArrayInJson: castToTextArr },\n\tjson: { normalizeParamArray: arrayCompatNormalizeInput((v) => JSON.stringify(v), true) },\n\tjsonb: { normalizeParamArray: arrayCompatNormalizeInput((v) => JSON.stringify(v), true) },\n\tline: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: parseLineABC,\n\t\tnormalizeArray: arrayCompatNormalize(parseLineABC),\n\t\tnormalizeInJson: parseLineABC,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parseLineABC)\n\t},\n\t\"line:tuple\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: parseLineTuple,\n\t\tnormalizeArray: arrayCompatNormalize(parseLineTuple),\n\t\tnormalizeInJson: parseLineTuple,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parseLineTuple)\n\t},\n\tnumeric: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tcastArray: castToTextArr\n\t},\n\t\"numeric:number\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tcastArray: castToTextArr,\n\t\tnormalize: Number,\n\t\tnormalizeArray: arrayCompatNormalize(Number),\n\t\tnormalizeInJson: Number,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(Number)\n\t},\n\t\"numeric:bigint\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tcastArray: castToTextArr,\n\t\tnormalize: BigInt,\n\t\tnormalizeArray: arrayCompatNormalize(BigInt),\n\t\tnormalizeInJson: BigInt,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(BigInt)\n\t},\n\tpoint: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: parsePointXY,\n\t\tnormalizeArray: arrayCompatNormalize(parsePointXY),\n\t\tnormalizeInJson: parsePointXY,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parsePointXY)\n\t},\n\t\"point:tuple\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalize: parsePointTuple,\n\t\tnormalizeArray: arrayCompatNormalize(parsePointTuple),\n\t\tnormalizeInJson: parsePointTuple,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parsePointTuple)\n\t},\n\ttimestamp: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalizeInJson: textToDateWithTz,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(textToDateWithTz)\n\t},\n\ttimestamptz: {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr,\n\t\tnormalizeInJson: textToDate,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(textToDate)\n\t},\n\t\"timestamp:string\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr\n\t},\n\t\"timestamptz:string\": {\n\t\tcastInJson: castToText,\n\t\tcastArrayInJson: castToTextArr\n\t},\n\thalfvec: {\n\t\tnormalize: parsePgVector,\n\t\tnormalizeArray: parsePgArrayAndNormalize(parsePgVector),\n\t\tnormalizeInJson: parsePgVector,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parsePgVector)\n\t},\n\tvector: {\n\t\tnormalize: parsePgVector,\n\t\tnormalizeArray: parsePgArrayAndNormalize(parsePgVector),\n\t\tnormalizeInJson: parsePgVector,\n\t\tnormalizeArrayInJson: arrayCompatNormalize(parsePgVector)\n\t}\n};\nconst refineGenericPgCodecs = (extension) => refineCodecs(genericPgCodecs, extension);\n\n//#endregion\nexport { arrayCompatCast, arrayCompatNormalize, arrayCompatNormalizeInput, castToText, castToTextArr, genericPgCodecs, parseGeometryTuple, parseGeometryXY, parseLineABC, parseLineTuple, parsePgArrayAndNormalize, parsePgVector, parsePointTuple, parsePointXY, refineGenericPgCodecs, resolvePgTypeAlias, textToDate, textToDateWithTz, unionsTypeTable };\n//# sourceMappingURL=codecs.js.map",
22
+ "import { base64ToUint8Array } from \"../utils.js\";\nimport { makePgArray, parsePgArray } from \"../pg-core/array.js\";\nimport { arrayCompatNormalize, castToText, castToTextArr, genericPgCodecs, parseGeometryTuple, parseGeometryXY, parsePgArrayAndNormalize, refineGenericPgCodecs, textToDate, textToDateWithTz } from \"../pg-core/codecs.js\";\n\n//#region src/pglite/codecs.ts\nconst pgliteCodecs = refineGenericPgCodecs({\n\tbigint: {\n\t\tcast: castToText,\n\t\tcastArray: castToTextArr,\n\t\tnormalize: BigInt,\n\t\tnormalizeArray: arrayCompatNormalize(BigInt)\n\t},\n\t\"bigint:string\": {\n\t\tcast: castToText,\n\t\tcastArray: castToTextArr\n\t},\n\t\"bigint:number\": {\n\t\tcast: castToText,\n\t\tcastArray: castToTextArr\n\t},\n\tbigserial: {\n\t\tnormalize: BigInt,\n\t\tnormalizeArray: arrayCompatNormalize(BigInt),\n\t\tcast: castToText,\n\t\tcastArray: castToTextArr\n\t},\n\t\"bigserial:number\": {\n\t\tcast: castToText,\n\t\tcastArray: castToTextArr\n\t},\n\tbytea: {\n\t\tnormalizeInJson: typeof Buffer === \"undefined\" ? base64ToUint8Array : genericPgCodecs.bytea?.normalizeInJson,\n\t\tnormalizeArrayInJson: typeof Buffer === \"undefined\" ? arrayCompatNormalize(base64ToUint8Array) : genericPgCodecs.bytea?.normalizeArrayInJson,\n\t\tnormalize: typeof Buffer === \"undefined\" ? void 0 : (v) => Buffer.from(v),\n\t\tnormalizeArray: typeof Buffer === \"undefined\" ? void 0 : arrayCompatNormalize((v) => Buffer.from(v))\n\t},\n\tinterval: { castArray: castToTextArr },\n\tdate: {\n\t\tcastArray: castToTextArr,\n\t\tnormalize: textToDate,\n\t\tnormalizeArray: arrayCompatNormalize(textToDate)\n\t},\n\t\"date:string\": { castArray: castToTextArr },\n\ttimestamp: {\n\t\tcastArray: castToTextArr,\n\t\tnormalize: textToDateWithTz,\n\t\tnormalizeArray: arrayCompatNormalize(textToDateWithTz)\n\t},\n\ttimestamptz: {\n\t\tcastArray: castToTextArr,\n\t\tnormalize: textToDate,\n\t\tnormalizeArray: arrayCompatNormalize(textToDate)\n\t},\n\t\"timestamp:string\": { castArray: castToTextArr },\n\t\"timestamptz:string\": { castArray: castToTextArr },\n\tjson: { normalizeParam: (v) => typeof v === \"object\" ? v : JSON.stringify(v) },\n\tjsonb: { normalizeParam: (v) => typeof v === \"object\" ? v : JSON.stringify(v) },\n\t\"geometry(point)\": {\n\t\tnormalizeArray: parsePgArrayAndNormalize(parseGeometryXY),\n\t\tcastParam: (name) => `${name}::geometry`,\n\t\tcastArrayParam: (name, _column, dimensions) => `${name}::geometry${\"[]\".repeat(dimensions)}`,\n\t\tnormalizeParamArray: makePgArray\n\t},\n\t\"geometry(point):tuple\": {\n\t\tnormalizeArray: parsePgArrayAndNormalize(parseGeometryTuple),\n\t\tcastParam: (name) => `${name}::geometry`,\n\t\tcastArrayParam: (name, _column, dimensions) => `${name}::geometry${\"[]\".repeat(dimensions)}`,\n\t\tnormalizeParamArray: makePgArray\n\t},\n\thalfvec: {\n\t\tcastParam: (name) => `${name}::halfvec`,\n\t\tcastArrayParam: (name, _column, dimensions) => `${name}::halfvec${\"[]\".repeat(dimensions)}`,\n\t\tnormalizeParamArray: makePgArray\n\t},\n\tvector: {\n\t\tcastParam: (name) => `${name}::vector`,\n\t\tcastArrayParam: (name, _column, dimensions) => `${name}::vector${\"[]\".repeat(dimensions)}`,\n\t\tnormalizeParamArray: makePgArray\n\t},\n\tsparsevec: {\n\t\tnormalizeArray: parsePgArray,\n\t\tcastParam: (name) => `${name}::sparsevec`,\n\t\tcastArrayParam: (name, _column, dimensions) => `${name}::sparsevec${\"[]\".repeat(dimensions)}`,\n\t\tnormalizeParamArray: makePgArray\n\t}\n});\n\n//#endregion\nexport { pgliteCodecs };\n//# sourceMappingURL=codecs.js.map",
23
+ "import { entityKind } from \"./entity.js\";\n\n//#region src/logger.ts\nvar ConsoleLogWriter = class {\n\tstatic [entityKind] = \"ConsoleLogWriter\";\n\twrite(message) {\n\t\tconsole.log(message);\n\t}\n};\nvar DefaultLogger = class {\n\tstatic [entityKind] = \"DefaultLogger\";\n\twriter;\n\tconstructor(config) {\n\t\tthis.writer = config?.writer ?? new ConsoleLogWriter();\n\t}\n\tlogQuery(query, params) {\n\t\tconst stringifiedParams = params.map((p) => {\n\t\t\ttry {\n\t\t\t\treturn JSON.stringify(p);\n\t\t\t} catch {\n\t\t\t\treturn String(p);\n\t\t\t}\n\t\t});\n\t\tconst paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(\", \")}]` : \"\";\n\t\tthis.writer.write(`Query: ${query}${paramsStr}`);\n\t}\n};\nvar NoopLogger = class {\n\tstatic [entityKind] = \"NoopLogger\";\n\tlogQuery() {}\n};\n\n//#endregion\nexport { ConsoleLogWriter, DefaultLogger, NoopLogger };\n//# sourceMappingURL=logger.js.map",
24
+ "import { entityKind } from \"../../entity.js\";\nimport { SQL, sql } from \"../../sql/sql.js\";\n\n//#region src/pg-core/query-builders/count.ts\nvar PgCountBuilder = class PgCountBuilder extends SQL {\n\tstatic [entityKind] = \"PgCountBuilder\";\n\tdialect;\n\tstatic buildCount(source, filters, parens) {\n\t\tconst query = sql`select count(*) from ${source}${sql` where ${filters}`.if(filters)}`;\n\t\treturn parens ? sql`(${query})` : query;\n\t}\n\tconstructor(countConfig) {\n\t\tsuper(PgCountBuilder.buildCount(countConfig.source, countConfig.filters, true).queryChunks);\n\t\tthis.countConfig = countConfig;\n\t\tthis.dialect = countConfig.dialect;\n\t\tthis.mapWith((e) => {\n\t\t\tif (typeof e === \"number\") return e;\n\t\t\treturn Number(e ?? 0);\n\t\t});\n\t}\n\texecutableSql;\n\tbuild() {\n\t\tif (!this.executableSql) {\n\t\t\tconst { source, filters } = this.countConfig;\n\t\t\tthis.executableSql = PgCountBuilder.buildCount(source, filters);\n\t\t}\n\t\treturn this.dialect.sqlToQuery(this.executableSql);\n\t}\n};\n\n//#endregion\nexport { PgCountBuilder };\n//# sourceMappingURL=count.js.map",
25
+ "import { entityKind } from \"./entity.js\";\n\n//#region src/query-promise.ts\nvar QueryPromise = class {\n\tstatic [entityKind] = \"QueryPromise\";\n\t[Symbol.toStringTag] = \"QueryPromise\";\n\tcatch(onRejected) {\n\t\treturn this.then(void 0, onRejected);\n\t}\n\tfinally(onFinally) {\n\t\treturn this.then((value) => {\n\t\t\tonFinally?.();\n\t\t\treturn value;\n\t\t}, (reason) => {\n\t\t\tonFinally?.();\n\t\t\tthrow reason;\n\t\t});\n\t}\n\tthen(onFulfilled, onRejected) {\n\t\treturn this.execute().then(onFulfilled, onRejected);\n\t}\n};\n\n//#endregion\nexport { QueryPromise };\n//# sourceMappingURL=query-promise.js.map",
26
+ "import { PgCountBuilder } from \"../query-builders/count.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/count.ts\nvar PgAsyncCountBuilder = class extends PgCountBuilder {\n\tstatic [entityKind] = \"PgAsyncCountBuilder\";\n\tsession;\n\tconstructor({ source, dialect, filters, session }) {\n\t\tsuper({\n\t\t\tsource,\n\t\t\tdialect,\n\t\t\tfilters\n\t\t});\n\t\tthis.session = session;\n\t}\n\texecute(placeholderValues) {\n\t\treturn this.session.prepareQuery(this.build(), \"arrays\", false, (rows) => {\n\t\t\tconst v = rows[0]?.[0];\n\t\t\tif (typeof v === \"number\") return v;\n\t\t\treturn v ? Number(v) : 0;\n\t\t}).execute(placeholderValues);\n\t}\n};\napplyMixins(PgAsyncCountBuilder, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncCountBuilder };\n//# sourceMappingURL=count.js.map",
27
+ "import { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/query-builders/query.ts\nvar RelationalQueryBuilder = class {\n\tstatic [entityKind] = \"PgRelationalQueryBuilderV2\";\n\tconstructor(schema, table, tableConfig, dialect, session, parseJson, builder = PgRelationalQuery) {\n\t\tthis.schema = schema;\n\t\tthis.table = table;\n\t\tthis.tableConfig = tableConfig;\n\t\tthis.dialect = dialect;\n\t\tthis.session = session;\n\t\tthis.parseJson = parseJson;\n\t\tthis.builder = builder;\n\t}\n\tfindMany(config) {\n\t\treturn new this.builder(this.schema, this.table, this.tableConfig, this.dialect, this.session, config ?? true, \"many\", this.parseJson);\n\t}\n\tfindFirst(config) {\n\t\treturn new this.builder(this.schema, this.table, this.tableConfig, this.dialect, this.session, config ?? true, \"first\", this.parseJson);\n\t}\n};\nvar PgRelationalQuery = class {\n\tstatic [entityKind] = \"PgRelationalQueryV2\";\n\tconstructor(schema, table, tableConfig, dialect, session, config, mode, parseJson) {\n\t\tthis.schema = schema;\n\t\tthis.table = table;\n\t\tthis.tableConfig = tableConfig;\n\t\tthis.dialect = dialect;\n\t\tthis.session = session;\n\t\tthis.config = config;\n\t\tthis.mode = mode;\n\t\tthis.parseJson = parseJson;\n\t}\n\t_getQuery() {\n\t\treturn this.dialect.buildRelationalQuery({\n\t\t\tschema: this.schema,\n\t\t\ttable: this.table,\n\t\t\ttableConfig: this.tableConfig,\n\t\t\tqueryConfig: this.config,\n\t\t\tmode: this.mode\n\t\t});\n\t}\n\tgetSQL() {\n\t\treturn this._getQuery().sql;\n\t}\n\t_toSQL() {\n\t\tconst query = this._getQuery();\n\t\treturn {\n\t\t\tquery,\n\t\t\tbuiltQuery: this.dialect.sqlToQuery(query.sql)\n\t\t};\n\t}\n\ttoSQL() {\n\t\treturn this._toSQL().builtQuery;\n\t}\n};\n\n//#endregion\nexport { PgRelationalQuery, RelationalQueryBuilder };\n//# sourceMappingURL=query.js.map",
28
+ "import { entityKind } from \"../entity.js\";\nimport { TableName } from \"../table.utils.js\";\n\n//#region src/pg-core/foreign-keys.ts\nvar ForeignKeyBuilder = class {\n\tstatic [entityKind] = \"PgForeignKeyBuilder\";\n\t/** @internal */\n\treference;\n\t/** @internal */\n\t_onUpdate = \"no action\";\n\t/** @internal */\n\t_onDelete = \"no action\";\n\tconstructor(config, actions) {\n\t\tthis.reference = () => {\n\t\t\tconst { name, columns, foreignColumns } = config();\n\t\t\treturn {\n\t\t\t\tname,\n\t\t\t\tcolumns,\n\t\t\t\tforeignTable: foreignColumns[0].table,\n\t\t\t\tforeignColumns\n\t\t\t};\n\t\t};\n\t\tif (actions) {\n\t\t\tthis._onUpdate = actions.onUpdate;\n\t\t\tthis._onDelete = actions.onDelete;\n\t\t}\n\t}\n\tonUpdate(action) {\n\t\tthis._onUpdate = action === void 0 ? \"no action\" : action;\n\t\treturn this;\n\t}\n\tonDelete(action) {\n\t\tthis._onDelete = action === void 0 ? \"no action\" : action;\n\t\treturn this;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new ForeignKey(table, this);\n\t}\n};\nvar ForeignKey = class {\n\tstatic [entityKind] = \"PgForeignKey\";\n\treference;\n\tonUpdate;\n\tonDelete;\n\tname;\n\tconstructor(table, builder) {\n\t\tthis.table = table;\n\t\tthis.reference = builder.reference;\n\t\tthis.onUpdate = builder._onUpdate;\n\t\tthis.onDelete = builder._onDelete;\n\t}\n\tgetName() {\n\t\tconst { name, columns, foreignColumns } = this.reference();\n\t\tconst columnNames = columns.map((column) => column.name);\n\t\tconst foreignColumnNames = foreignColumns.map((column) => column.name);\n\t\tconst chunks = [\n\t\t\tthis.table[TableName],\n\t\t\t...columnNames,\n\t\t\tforeignColumns[0].table[TableName],\n\t\t\t...foreignColumnNames\n\t\t];\n\t\treturn name ?? `${chunks.join(\"_\")}_fk`;\n\t}\n\tisNameExplicit() {\n\t\treturn !!this.reference().name;\n\t}\n};\nfunction foreignKey(config) {\n\tfunction mappedConfig() {\n\t\tconst { name, columns, foreignColumns } = config;\n\t\treturn {\n\t\t\tname,\n\t\t\tcolumns,\n\t\t\tforeignColumns\n\t\t};\n\t}\n\treturn new ForeignKeyBuilder(mappedConfig);\n}\n\n//#endregion\nexport { ForeignKey, ForeignKeyBuilder, foreignKey };\n//# sourceMappingURL=foreign-keys.js.map",
29
+ "import { entityKind } from \"../../entity.js\";\nimport { Column } from \"../../column.js\";\nimport { ForeignKeyBuilder } from \"../foreign-keys.js\";\nimport { iife } from \"../../tracing-utils.js\";\n\n//#region src/pg-core/columns/common.ts\nvar PgColumnBuilder = class {\n\tstatic [entityKind] = \"PgColumnBuilder\";\n\tforeignKeyConfigs = [];\n\tconfig;\n\tconstructor(name, dataType, columnType) {\n\t\tthis.config = {\n\t\t\tname,\n\t\t\tkeyAsName: name === \"\",\n\t\t\tnotNull: false,\n\t\t\tdefault: void 0,\n\t\t\thasDefault: false,\n\t\t\tprimaryKey: false,\n\t\t\tisUnique: false,\n\t\t\tuniqueName: void 0,\n\t\t\tuniqueType: void 0,\n\t\t\tdataType,\n\t\t\tcolumnType,\n\t\t\tgenerated: void 0,\n\t\t\tdefaultFn: void 0,\n\t\t\tonUpdateFn: void 0,\n\t\t\tgeneratedIdentity: void 0\n\t\t};\n\t}\n\t/**\n\t* Changes the data type of the column. Commonly used with `json` columns. Also, useful for branded types.\n\t*\n\t* @example\n\t* ```ts\n\t* const users = pgTable('users', {\n\t* \tid: integer('id').$type<UserId>().primaryKey(),\n\t* \tdetails: json('details').$type<UserDetails>().notNull(),\n\t* });\n\t* ```\n\t*/\n\t$type() {\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `not null` clause to the column definition.\n\t*\n\t* Affects the `select` model of the table - columns *without* `not null` will be nullable on select.\n\t*/\n\tnotNull() {\n\t\tthis.config.notNull = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `default <value>` clause to the column definition.\n\t*\n\t* Affects the `insert` model of the table - columns *with* `default` are optional on insert.\n\t*\n\t* If you need to set a dynamic default value, use {@link $defaultFn} instead.\n\t*/\n\tdefault(value) {\n\t\tthis.config.default = value;\n\t\tthis.config.hasDefault = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a dynamic default value to the column.\n\t* The function will be called when the row is inserted, and the returned value will be used as the column value.\n\t*\n\t* **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t*/\n\t$defaultFn(fn) {\n\t\tthis.config.defaultFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Alias for {@link $defaultFn}.\n\t*/\n\t$default = this.$defaultFn;\n\t/**\n\t* Adds a dynamic update value to the column.\n\t* The function will be called when the row is updated, and the returned value will be used as the column value if none is provided.\n\t* If no `default` (or `$defaultFn`) value is provided, the function will be called when the row is inserted as well, and the returned value will be used as the column value.\n\t*\n\t* **Note:** This value does not affect the `drizzle-kit` behavior, it is only used at runtime in `drizzle-orm`.\n\t*/\n\t$onUpdateFn(fn) {\n\t\tthis.config.onUpdateFn = fn;\n\t\tthis.config.hasDefault = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Alias for {@link $onUpdateFn}.\n\t*/\n\t$onUpdate = this.$onUpdateFn;\n\t/**\n\t* Adds a `primary key` clause to the column definition. This implicitly makes the column `not null`.\n\t*\n\t* In SQLite, `integer primary key` implicitly makes the column auto-incrementing.\n\t*/\n\tprimaryKey() {\n\t\tthis.config.primaryKey = true;\n\t\tthis.config.notNull = true;\n\t\treturn this;\n\t}\n\t/** @internal Sets the name of the column to the key within the table definition if a name was not given. */\n\tsetName(name, casingFn) {\n\t\tif (this.config.name !== \"\") return;\n\t\tthis.config.name = casingFn(name);\n\t}\n\tarray(dimensions) {\n\t\tconst dim = dimensions ?? \"[]\";\n\t\tthis.config.dimensions = dim.length / 2;\n\t\treturn this;\n\t}\n\treferences(ref, config = {}) {\n\t\tthis.foreignKeyConfigs.push({\n\t\t\tref,\n\t\t\tconfig\n\t\t});\n\t\treturn this;\n\t}\n\tunique(name, config) {\n\t\tthis.config.isUnique = true;\n\t\tthis.config.uniqueName = name;\n\t\tthis.config.uniqueType = config?.nulls;\n\t\treturn this;\n\t}\n\tgeneratedAlwaysAs(as) {\n\t\tthis.config.generated = {\n\t\t\tas,\n\t\t\ttype: \"always\",\n\t\t\tmode: \"stored\"\n\t\t};\n\t\treturn this;\n\t}\n\t/** @internal */\n\tbuildForeignKeys(column, table) {\n\t\treturn this.foreignKeyConfigs.map(({ ref, config }) => {\n\t\t\treturn iife((ref, config) => {\n\t\t\t\tconst builder = new ForeignKeyBuilder(() => {\n\t\t\t\t\tconst foreignColumn = ref();\n\t\t\t\t\treturn {\n\t\t\t\t\t\tname: config.name,\n\t\t\t\t\t\tcolumns: [column],\n\t\t\t\t\t\tforeignColumns: [foreignColumn]\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t\tif (config.onUpdate) builder.onUpdate(config.onUpdate);\n\t\t\t\tif (config.onDelete) builder.onDelete(config.onDelete);\n\t\t\t\treturn builder.build(table);\n\t\t\t}, ref, config);\n\t\t});\n\t}\n\t/** @internal */\n\tbuildExtraConfigColumn(table) {\n\t\treturn new ExtraConfigColumn(table, {\n\t\t\t...this.config,\n\t\t\tdimensions: this.config.dimensions ?? 0\n\t\t});\n\t}\n};\nvar PgColumn = class extends Column {\n\tstatic [entityKind] = \"PgColumn\";\n\t/** @internal */\n\ttable;\n\tdimensions;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.table = table;\n\t\tthis.dimensions = config.dimensions ?? 0;\n\t}\n\t/** @internal */\n\tpostBuild() {\n\t\tif (this.dimensions) {\n\t\t\tconst originalFromDriver = this.mapFromDriverValue.bind(this);\n\t\t\tconst originalToDriver = this.mapToDriverValue.bind(this);\n\t\t\tthis.mapFromDriverValue = this.mapFromDriverValue.isNoop ? this.mapFromDriverValue : (value) => {\n\t\t\t\treturn this.mapArrayElements(value, originalFromDriver, this.dimensions);\n\t\t\t};\n\t\t\tthis.mapToDriverValue = this.mapToDriverValue.isNoop ? this.mapToDriverValue : (value) => {\n\t\t\t\treturn this.mapArrayElements(value, originalToDriver, this.dimensions);\n\t\t\t};\n\t\t}\n\t\treturn this;\n\t}\n\t/** @internal */\n\tshouldDisableInsert() {\n\t\treturn this.config.generatedIdentity !== void 0 && this.config.generatedIdentity.type !== \"byDefault\" || this.config.generated !== void 0 && this.config.generated.type !== \"byDefault\";\n\t}\n\t/** @internal */\n\tmapArrayElements(value, mapper, depth) {\n\t\tif (depth > 0 && Array.isArray(value)) return value.map((v) => v === null ? null : this.mapArrayElements(v, mapper, depth - 1));\n\t\treturn mapper(value);\n\t}\n};\nvar ExtraConfigColumn = class extends PgColumn {\n\tstatic [entityKind] = \"ExtraConfigColumn\";\n\t/** @itnernal */\n\tcodec = void 0;\n\tgetSQLType() {\n\t\treturn this.getSQLType();\n\t}\n\tindexConfig = {\n\t\torder: this.config.order ?? \"asc\",\n\t\tnulls: this.config.nulls ?? \"last\",\n\t\topClass: this.config.opClass\n\t};\n\tdefaultConfig = {\n\t\torder: \"asc\",\n\t\tnulls: \"last\",\n\t\topClass: void 0\n\t};\n\tasc() {\n\t\tthis.indexConfig.order = \"asc\";\n\t\treturn this;\n\t}\n\tdesc() {\n\t\tthis.indexConfig.order = \"desc\";\n\t\treturn this;\n\t}\n\tnullsFirst() {\n\t\tthis.indexConfig.nulls = \"first\";\n\t\treturn this;\n\t}\n\tnullsLast() {\n\t\tthis.indexConfig.nulls = \"last\";\n\t\treturn this;\n\t}\n\t/**\n\t* ### PostgreSQL documentation quote\n\t*\n\t* > An operator class with optional parameters can be specified for each column of an index.\n\t* The operator class identifies the operators to be used by the index for that column.\n\t* For example, a B-tree index on four-byte integers would use the int4_ops class;\n\t* this operator class includes comparison functions for four-byte integers.\n\t* In practice the default operator class for the column's data type is usually sufficient.\n\t* The main point of having operator classes is that for some data types, there could be more than one meaningful ordering.\n\t* For example, we might want to sort a complex-number data type either by absolute value or by real part.\n\t* We could do this by defining two operator classes for the data type and then selecting the proper class when creating an index.\n\t* More information about operator classes check:\n\t*\n\t* ### Useful links\n\t* https://www.postgresql.org/docs/current/sql-createindex.html\n\t*\n\t* https://www.postgresql.org/docs/current/indexes-opclass.html\n\t*\n\t* https://www.postgresql.org/docs/current/xindex.html\n\t*\n\t* ### Additional types\n\t* If you have the `pg_vector` extension installed in your database, you can use the\n\t* `vector_l2_ops`, `vector_ip_ops`, `vector_cosine_ops`, `vector_l1_ops`, `bit_hamming_ops`, `bit_jaccard_ops`, `halfvec_l2_ops`, `sparsevec_l2_ops` options, which are predefined types.\n\t*\n\t* **You can always specify any string you want in the operator class, in case Drizzle doesn't have it natively in its types**\n\t*\n\t* @param opClass\n\t* @returns\n\t*/\n\top(opClass) {\n\t\tthis.indexConfig.opClass = opClass;\n\t\treturn this;\n\t}\n};\nvar IndexedColumn = class {\n\tstatic [entityKind] = \"IndexedColumn\";\n\tconstructor(name, keyAsName, type, indexConfig) {\n\t\tthis.name = name;\n\t\tthis.keyAsName = keyAsName;\n\t\tthis.type = type;\n\t\tthis.indexConfig = indexConfig;\n\t}\n\tname;\n\tkeyAsName;\n\ttype;\n\tindexConfig;\n};\n\n//#endregion\nexport { ExtraConfigColumn, IndexedColumn, PgColumn, PgColumnBuilder };\n//# sourceMappingURL=common.js.map",
30
+ "import { PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/int.common.ts\nvar PgIntColumnBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgIntColumnBaseBuilder\";\n\t/**\n\t* Adds an `ALWAYS AS IDENTITY` clause to the column definition.\n\t* Available for integer column types.\n\t*/\n\tgeneratedAlwaysAsIdentity(sequence) {\n\t\tif (sequence) {\n\t\t\tconst { name, ...options } = sequence;\n\t\t\tthis.config.generatedIdentity = {\n\t\t\t\ttype: \"always\",\n\t\t\t\tsequenceName: name,\n\t\t\t\tsequenceOptions: options\n\t\t\t};\n\t\t} else this.config.generatedIdentity = { type: \"always\" };\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `BY DEFAULT AS IDENTITY` clause to the column definition.\n\t* Available for integer column types.\n\t*/\n\tgeneratedByDefaultAsIdentity(sequence) {\n\t\tif (sequence) {\n\t\t\tconst { name, ...options } = sequence;\n\t\t\tthis.config.generatedIdentity = {\n\t\t\t\ttype: \"byDefault\",\n\t\t\t\tsequenceName: name,\n\t\t\t\tsequenceOptions: options\n\t\t\t};\n\t\t} else this.config.generatedIdentity = { type: \"byDefault\" };\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t\treturn this;\n\t}\n};\n\n//#endregion\nexport { PgIntColumnBuilder };\n//# sourceMappingURL=int.common.js.map",
31
+ "import { PgColumn } from \"./common.js\";\nimport { PgIntColumnBuilder } from \"./int.common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/bigint.ts\nvar PgBigInt53Builder = class extends PgIntColumnBuilder {\n\tstatic [entityKind] = \"PgBigInt53Builder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number int53\", \"PgBigInt53\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBigInt53(table, this.config);\n\t}\n};\nvar PgBigInt53 = class extends PgColumn {\n\tstatic [entityKind] = \"PgBigInt53\";\n\t/** @internal */\n\tcodec = \"bigint:number\";\n\tgetSQLType() {\n\t\treturn \"bigint\";\n\t}\n};\nvar PgBigInt64Builder = class extends PgIntColumnBuilder {\n\tstatic [entityKind] = \"PgBigInt64Builder\";\n\tconstructor(name) {\n\t\tsuper(name, \"bigint int64\", \"PgBigInt64\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBigInt64(table, this.config);\n\t}\n};\nvar PgBigInt64 = class extends PgColumn {\n\tstatic [entityKind] = \"PgBigInt64\";\n\t/** @internal */\n\tcodec = \"bigint\";\n\tgetSQLType() {\n\t\treturn \"bigint\";\n\t}\n};\nvar PgBigIntStringBuilder = class extends PgIntColumnBuilder {\n\tstatic [entityKind] = \"PgBigIntStringBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string int64\", \"PgBigIntString\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBigIntString(table, this.config);\n\t}\n};\nvar PgBigIntString = class extends PgColumn {\n\tstatic [entityKind] = \"PgBigIntString\";\n\t/** @internal */\n\tcodec = \"bigint:string\";\n\tgetSQLType() {\n\t\treturn \"bigint\";\n\t}\n};\nfunction bigint(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config.mode === \"number\") return new PgBigInt53Builder(name);\n\tif (config.mode === \"string\") return new PgBigIntStringBuilder(name);\n\treturn new PgBigInt64Builder(name);\n}\n\n//#endregion\nexport { PgBigInt53, PgBigInt53Builder, PgBigInt64, PgBigInt64Builder, PgBigIntString, PgBigIntStringBuilder, bigint };\n//# sourceMappingURL=bigint.js.map",
32
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/bigserial.ts\nvar PgBigSerial53Builder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgBigSerial53Builder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number int53\", \"PgBigSerial53\");\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBigSerial53(table, this.config);\n\t}\n};\nvar PgBigSerial53 = class extends PgColumn {\n\tstatic [entityKind] = \"PgBigSerial53\";\n\t/** @internal */\n\tcodec = \"bigserial:number\";\n\tgetSQLType() {\n\t\treturn \"bigserial\";\n\t}\n};\nvar PgBigSerial64Builder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgBigSerial64Builder\";\n\tconstructor(name) {\n\t\tsuper(name, \"bigint int64\", \"PgBigSerial64\");\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBigSerial64(table, this.config);\n\t}\n};\nvar PgBigSerial64 = class extends PgColumn {\n\tstatic [entityKind] = \"PgBigSerial64\";\n\t/** @internal */\n\tcodec = \"bigserial\";\n\tgetSQLType() {\n\t\treturn \"bigserial\";\n\t}\n};\nfunction bigserial(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config.mode === \"number\") return new PgBigSerial53Builder(name);\n\treturn new PgBigSerial64Builder(name);\n}\n\n//#endregion\nexport { PgBigSerial53, PgBigSerial53Builder, PgBigSerial64, PgBigSerial64Builder, bigserial };\n//# sourceMappingURL=bigserial.js.map",
33
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/boolean.ts\nvar PgBooleanBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgBooleanBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"boolean\", \"PgBoolean\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBoolean(table, this.config);\n\t}\n};\nvar PgBoolean = class extends PgColumn {\n\tstatic [entityKind] = \"PgBoolean\";\n\t/** @internal */\n\tcodec = \"bool\";\n\tgetSQLType() {\n\t\treturn \"boolean\";\n\t}\n};\nfunction boolean(name) {\n\treturn new PgBooleanBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgBoolean, PgBooleanBuilder, boolean };\n//# sourceMappingURL=boolean.js.map",
34
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/char.ts\nvar PgCharBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgCharBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, config.enum?.length ? \"string enum\" : \"string\", \"PgChar\");\n\t\tthis.config.length = config.length ?? 1;\n\t\tthis.config.setLength = config.length !== void 0;\n\t\tthis.config.enumValues = config.enum;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgChar(table, this.config);\n\t}\n};\nvar PgChar = class extends PgColumn {\n\tstatic [entityKind] = \"PgChar\";\n\t/** @internal */\n\tcodec = \"char\";\n\tenumValues;\n\tsetLength;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.enumValues = config.enumValues;\n\t\tthis.setLength = config.setLength;\n\t}\n\tgetSQLType() {\n\t\treturn this.setLength ? `char(${this.length})` : `char`;\n\t}\n};\nfunction char(a, b = {}) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgCharBuilder(name, config);\n}\n\n//#endregion\nexport { PgChar, PgCharBuilder, char };\n//# sourceMappingURL=char.js.map",
35
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/cidr.ts\nvar PgCidrBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgCidrBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string cidr\", \"PgCidr\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgCidr(table, this.config);\n\t}\n};\nvar PgCidr = class extends PgColumn {\n\tstatic [entityKind] = \"PgCidr\";\n\t/** @internal */\n\tcodec = \"cidr\";\n\tgetSQLType() {\n\t\treturn \"cidr\";\n\t}\n};\nfunction cidr(name) {\n\treturn new PgCidrBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgCidr, PgCidrBuilder, cidr };\n//# sourceMappingURL=cidr.js.map",
36
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { parsePgArray } from \"../array.js\";\nimport { resolvePgTypeAlias } from \"../codecs.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/custom.ts\nvar PgCustomColumnBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgCustomColumnBuilder\";\n\tconstructor(name, fieldConfig, customTypeParams) {\n\t\tsuper(name, \"custom\", \"PgCustomColumn\");\n\t\tthis.config.fieldConfig = fieldConfig;\n\t\tthis.config.customTypeParams = customTypeParams;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgCustomColumn(table, this.config);\n\t}\n};\nvar PgCustomColumn = class extends PgColumn {\n\tstatic [entityKind] = \"PgCustomColumn\";\n\t/** @internal */\n\tcodec;\n\tsqlName;\n\tmapFromJsonValue;\n\tjsonSelectIdentifier;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.sqlName = config.customTypeParams.dataType(config.fieldConfig);\n\t\tthis.mapToDriverValue = config.customTypeParams.toDriver ?? this.mapToDriverValue;\n\t\tthis.mapFromDriverValue = config.customTypeParams.fromDriver ?? this.mapFromDriverValue;\n\t\tthis.mapFromJsonValue = config.customTypeParams.fromJson;\n\t\tthis.jsonSelectIdentifier = config.customTypeParams.forJsonSelect;\n\t\tconst cfgCodec = typeof config.customTypeParams.codec === \"string\" || typeof config.customTypeParams.codec === \"undefined\" ? config.customTypeParams.codec : config.customTypeParams.codec(config.fieldConfig);\n\t\tthis.codec = typeof cfgCodec === \"string\" ? resolvePgTypeAlias(cfgCodec) : void 0;\n\t\tif (this.dimensions && config.customTypeParams.fromJson) this.mapFromJsonValue = (value) => {\n\t\t\tif (value === null) return value;\n\t\t\tconst arr = typeof value === \"string\" ? parsePgArray(value) : value;\n\t\t\treturn this.mapJsonArrayElements(arr, config.customTypeParams.fromJson, this.dimensions);\n\t\t};\n\t}\n\t/** @internal */\n\tmapJsonArrayElements(value, mapper, depth) {\n\t\tif (depth > 0 && Array.isArray(value)) return value.map((v) => v === null ? null : this.mapJsonArrayElements(v, mapper, depth - 1));\n\t\treturn mapper(value);\n\t}\n\tgetSQLType() {\n\t\treturn this.sqlName;\n\t}\n};\n/**\n* Custom pg database data type generator\n*/\nfunction customType(customTypeParams) {\n\treturn (a, b) => {\n\t\tconst { name, config } = getColumnNameAndConfig(a, b);\n\t\treturn new PgCustomColumnBuilder(name, config, customTypeParams);\n\t};\n}\n\n//#endregion\nexport { PgCustomColumn, PgCustomColumnBuilder, customType };\n//# sourceMappingURL=custom.js.map",
37
+ "import { PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\n\n//#region src/pg-core/columns/date.common.ts\nvar PgDateColumnBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgDateColumnBaseBuilder\";\n\t/**\n\t* Adds a `default now()` clause to the column definition.\n\t* Available for date/time column types.\n\t*/\n\tdefaultNow() {\n\t\treturn this.default(sql`now()`);\n\t}\n};\n\n//#endregion\nexport { PgDateColumnBuilder };\n//# sourceMappingURL=date.common.js.map",
38
+ "import { PgColumn } from \"./common.js\";\nimport { PgDateColumnBuilder } from \"./date.common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/date.ts\nvar PgDateBuilder = class extends PgDateColumnBuilder {\n\tstatic [entityKind] = \"PgDateBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"object date\", \"PgDate\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgDate(table, this.config);\n\t}\n};\nvar PgDate = class extends PgColumn {\n\tstatic [entityKind] = \"PgDate\";\n\t/** @internal */\n\tcodec = \"date\";\n\tgetSQLType() {\n\t\treturn \"date\";\n\t}\n\tmapToDriverValue = function(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\treturn value.toISOString();\n\t};\n};\nvar PgDateStringBuilder = class extends PgDateColumnBuilder {\n\tstatic [entityKind] = \"PgDateStringBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string date\", \"PgDateString\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgDateString(table, this.config);\n\t}\n};\nvar PgDateString = class extends PgColumn {\n\tstatic [entityKind] = \"PgDateString\";\n\t/** @internal */\n\tcodec = \"date:string\";\n\tgetSQLType() {\n\t\treturn \"date\";\n\t}\n\tmapToDriverValue = (value) => {\n\t\tif (typeof value === \"string\") return value;\n\t\treturn value.toISOString();\n\t};\n};\nfunction date(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config?.mode === \"date\") return new PgDateBuilder(name);\n\treturn new PgDateStringBuilder(name);\n}\n\n//#endregion\nexport { PgDate, PgDateBuilder, PgDateString, PgDateStringBuilder, date };\n//# sourceMappingURL=date.js.map",
39
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/double-precision.ts\nvar PgDoublePrecisionBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgDoublePrecisionBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number double\", \"PgDoublePrecision\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgDoublePrecision(table, this.config);\n\t}\n};\nvar PgDoublePrecision = class extends PgColumn {\n\tstatic [entityKind] = \"PgDoublePrecision\";\n\t/** @internal */\n\tcodec = \"float8\";\n\tgetSQLType() {\n\t\treturn \"double precision\";\n\t}\n};\nfunction doublePrecision(name) {\n\treturn new PgDoublePrecisionBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgDoublePrecision, PgDoublePrecisionBuilder, doublePrecision };\n//# sourceMappingURL=double-precision.js.map",
40
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/inet.ts\nvar PgInetBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgInetBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string inet\", \"PgInet\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgInet(table, this.config);\n\t}\n};\nvar PgInet = class extends PgColumn {\n\tstatic [entityKind] = \"PgInet\";\n\t/** @internal */\n\tcodec = \"inet\";\n\tgetSQLType() {\n\t\treturn \"inet\";\n\t}\n};\nfunction inet(name) {\n\treturn new PgInetBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgInet, PgInetBuilder, inet };\n//# sourceMappingURL=inet.js.map",
41
+ "import { PgColumn } from \"./common.js\";\nimport { PgIntColumnBuilder } from \"./int.common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/integer.ts\nvar PgIntegerBuilder = class extends PgIntColumnBuilder {\n\tstatic [entityKind] = \"PgIntegerBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number int32\", \"PgInteger\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgInteger(table, this.config);\n\t}\n};\nvar PgInteger = class extends PgColumn {\n\tstatic [entityKind] = \"PgInteger\";\n\t/** @internal */\n\tcodec = \"int\";\n\tgetSQLType() {\n\t\treturn \"integer\";\n\t}\n};\nfunction integer(name) {\n\treturn new PgIntegerBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgInteger, PgIntegerBuilder, integer };\n//# sourceMappingURL=integer.js.map",
42
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/interval.ts\nvar PgIntervalBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgIntervalBuilder\";\n\tconstructor(name, intervalConfig) {\n\t\tsuper(name, \"string interval\", \"PgInterval\");\n\t\tthis.config.intervalConfig = intervalConfig;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgInterval(table, this.config);\n\t}\n};\nvar PgInterval = class extends PgColumn {\n\tstatic [entityKind] = \"PgInterval\";\n\t/** @internal */\n\tcodec = \"interval\";\n\tfields;\n\tprecision;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.fields = config.intervalConfig.fields;\n\t\tthis.precision = config.intervalConfig.precision;\n\t}\n\tgetSQLType() {\n\t\treturn `interval${this.fields ? ` ${this.fields}` : \"\"}${this.precision ? `(${this.precision})` : \"\"}`;\n\t}\n};\nfunction interval(a, b = {}) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgIntervalBuilder(name, config);\n}\n\n//#endregion\nexport { PgInterval, PgIntervalBuilder, interval };\n//# sourceMappingURL=interval.js.map",
43
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/json.ts\nvar PgJsonBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgJsonBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"object json\", \"PgJson\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgJson(table, this.config);\n\t}\n};\nvar PgJson = class extends PgColumn {\n\tstatic [entityKind] = \"PgJson\";\n\t/** @internal */\n\tcodec = \"json\";\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t}\n\tgetSQLType() {\n\t\treturn \"json\";\n\t}\n};\nfunction json(name) {\n\treturn new PgJsonBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgJson, PgJsonBuilder, json };\n//# sourceMappingURL=json.js.map",
44
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/jsonb.ts\nvar PgJsonbBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgJsonbBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"object json\", \"PgJsonb\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgJsonb(table, this.config);\n\t}\n};\nvar PgJsonb = class extends PgColumn {\n\tstatic [entityKind] = \"PgJsonb\";\n\t/** @internal */\n\tcodec = \"jsonb\";\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t}\n\tgetSQLType() {\n\t\treturn \"jsonb\";\n\t}\n};\nfunction jsonb(name) {\n\treturn new PgJsonbBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgJsonb, PgJsonbBuilder, jsonb };\n//# sourceMappingURL=jsonb.js.map",
45
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/line.ts\nvar PgLineBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgLineBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"array line\", \"PgLine\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgLineTuple(table, this.config);\n\t}\n};\nvar PgLineTuple = class extends PgColumn {\n\tstatic [entityKind] = \"PgLine\";\n\t/** @internal */\n\tcodec = \"line:tuple\";\n\tmode = \"tuple\";\n\tgetSQLType() {\n\t\treturn \"line\";\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn `{${value[0]},${value[1]},${value[2]}}`;\n\t};\n};\nvar PgLineABCBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgLineABCBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"object line\", \"PgLineABC\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgLineABC(table, this.config);\n\t}\n};\nvar PgLineABC = class extends PgColumn {\n\tstatic [entityKind] = \"PgLineABC\";\n\t/** @internal */\n\tcodec = \"line\";\n\tmode = \"abc\";\n\tgetSQLType() {\n\t\treturn \"line\";\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn `{${value.a},${value.b},${value.c}}`;\n\t};\n};\nfunction line(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (!config?.mode || config.mode === \"tuple\") return new PgLineBuilder(name);\n\treturn new PgLineABCBuilder(name);\n}\n\n//#endregion\nexport { PgLineABC, PgLineABCBuilder, PgLineBuilder, PgLineTuple, line };\n//# sourceMappingURL=line.js.map",
46
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/macaddr.ts\nvar PgMacaddrBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgMacaddrBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string macaddr\", \"PgMacaddr\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgMacaddr(table, this.config);\n\t}\n};\nvar PgMacaddr = class extends PgColumn {\n\tstatic [entityKind] = \"PgMacaddr\";\n\t/** @internal */\n\tcodec = \"macaddr\";\n\tgetSQLType() {\n\t\treturn \"macaddr\";\n\t}\n};\nfunction macaddr(name) {\n\treturn new PgMacaddrBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgMacaddr, PgMacaddrBuilder, macaddr };\n//# sourceMappingURL=macaddr.js.map",
47
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/macaddr8.ts\nvar PgMacaddr8Builder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgMacaddr8Builder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string macaddr8\", \"PgMacaddr8\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgMacaddr8(table, this.config);\n\t}\n};\nvar PgMacaddr8 = class extends PgColumn {\n\tstatic [entityKind] = \"PgMacaddr8\";\n\t/** @internal */\n\tcodec = \"macaddr8\";\n\tgetSQLType() {\n\t\treturn \"macaddr8\";\n\t}\n};\nfunction macaddr8(name) {\n\treturn new PgMacaddr8Builder(name ?? \"\");\n}\n\n//#endregion\nexport { PgMacaddr8, PgMacaddr8Builder, macaddr8 };\n//# sourceMappingURL=macaddr8.js.map",
48
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/numeric.ts\nvar PgNumericBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgNumericBuilder\";\n\tconstructor(name, precision, scale) {\n\t\tsuper(name, \"string numeric\", \"PgNumeric\");\n\t\tthis.config.precision = precision;\n\t\tthis.config.scale = scale;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgNumeric(table, this.config);\n\t}\n};\nvar PgNumeric = class extends PgColumn {\n\tstatic [entityKind] = \"PgNumeric\";\n\t/** @internal */\n\tcodec = \"numeric\";\n\tprecision;\n\tscale;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.precision = config.precision;\n\t\tthis.scale = config.scale;\n\t}\n\tgetSQLType() {\n\t\tif (this.precision !== void 0 && this.scale !== void 0) return `numeric(${this.precision}, ${this.scale})`;\n\t\telse if (this.precision === void 0) return \"numeric\";\n\t\telse return `numeric(${this.precision})`;\n\t}\n};\nvar PgNumericNumberBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgNumericNumberBuilder\";\n\tconstructor(name, precision, scale) {\n\t\tsuper(name, \"number\", \"PgNumericNumber\");\n\t\tthis.config.precision = precision;\n\t\tthis.config.scale = scale;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgNumericNumber(table, this.config);\n\t}\n};\nvar PgNumericNumber = class extends PgColumn {\n\tstatic [entityKind] = \"PgNumericNumber\";\n\t/** @internal */\n\tcodec = \"numeric:number\";\n\tprecision;\n\tscale;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.precision = config.precision;\n\t\tthis.scale = config.scale;\n\t}\n\tmapToDriverValue = String;\n\tgetSQLType() {\n\t\tif (this.precision !== void 0 && this.scale !== void 0) return `numeric(${this.precision}, ${this.scale})`;\n\t\telse if (this.precision === void 0) return \"numeric\";\n\t\telse return `numeric(${this.precision})`;\n\t}\n};\nvar PgNumericBigIntBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgNumericBigIntBuilder\";\n\tconstructor(name, precision, scale) {\n\t\tsuper(name, \"bigint int64\", \"PgNumericBigInt\");\n\t\tthis.config.precision = precision;\n\t\tthis.config.scale = scale;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgNumericBigInt(table, this.config);\n\t}\n};\nvar PgNumericBigInt = class extends PgColumn {\n\tstatic [entityKind] = \"PgNumericBigInt\";\n\t/** @internal */\n\tcodec = \"numeric:bigint\";\n\tprecision;\n\tscale;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.precision = config.precision;\n\t\tthis.scale = config.scale;\n\t}\n\tmapToDriverValue = String;\n\tgetSQLType() {\n\t\tif (this.precision !== void 0 && this.scale !== void 0) return `numeric(${this.precision}, ${this.scale})`;\n\t\telse if (this.precision === void 0) return \"numeric\";\n\t\telse return `numeric(${this.precision})`;\n\t}\n};\nfunction numeric(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tconst mode = config?.mode;\n\treturn mode === \"number\" ? new PgNumericNumberBuilder(name, config?.precision, config?.scale) : mode === \"bigint\" ? new PgNumericBigIntBuilder(name, config?.precision, config?.scale) : new PgNumericBuilder(name, config?.precision, config?.scale);\n}\nconst decimal = numeric;\n\n//#endregion\nexport { PgNumeric, PgNumericBigInt, PgNumericBigIntBuilder, PgNumericBuilder, PgNumericNumber, PgNumericNumberBuilder, decimal, numeric };\n//# sourceMappingURL=numeric.js.map",
49
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/point.ts\nvar PgPointTupleBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgPointTupleBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"array point\", \"PgPointTuple\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgPointTuple(table, this.config);\n\t}\n};\nvar PgPointTuple = class extends PgColumn {\n\tstatic [entityKind] = \"PgPointTuple\";\n\t/** @internal */\n\tcodec = \"point:tuple\";\n\tmode = \"tuple\";\n\tgetSQLType() {\n\t\treturn \"point\";\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn `(${value[0]},${value[1]})`;\n\t};\n};\nvar PgPointObjectBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgPointObjectBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"object point\", \"PgPointObject\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgPointObject(table, this.config);\n\t}\n};\nvar PgPointObject = class extends PgColumn {\n\tstatic [entityKind] = \"PgPointObject\";\n\t/** @internal */\n\tcodec = \"point\";\n\tmode = \"xy\";\n\tgetSQLType() {\n\t\treturn \"point\";\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn `(${value.x},${value.y})`;\n\t};\n};\nfunction point(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (!config?.mode || config.mode === \"tuple\") return new PgPointTupleBuilder(name);\n\treturn new PgPointObjectBuilder(name);\n}\n\n//#endregion\nexport { PgPointObject, PgPointObjectBuilder, PgPointTuple, PgPointTupleBuilder, point };\n//# sourceMappingURL=point.js.map",
50
+ "import { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\n\n//#region src/pg-core/columns/postgis_extension/geometry.ts\nvar PgGeometryBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgGeometryBuilder\";\n\tconstructor(name, srid) {\n\t\tsuper(name, \"array geometry\", \"PgGeometry\");\n\t\tthis.config.srid = srid;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgGeometry(table, this.config);\n\t}\n};\nvar PgGeometry = class extends PgColumn {\n\tstatic [entityKind] = \"PgGeometry\";\n\t/** @internal */\n\tcodec = \"geometry(point):tuple\";\n\tsrid = this.config.srid;\n\tmode = \"tuple\";\n\tgetSQLType() {\n\t\treturn `geometry(point${this.srid === void 0 ? \"\" : `,${this.srid}`})`;\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn `point(${value[0]} ${value[1]})`;\n\t};\n};\nvar PgGeometryObjectBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgGeometryObjectBuilder\";\n\tconstructor(name, srid) {\n\t\tsuper(name, \"object geometry\", \"PgGeometryObject\");\n\t\tthis.config.srid = srid;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgGeometryObject(table, this.config);\n\t}\n};\nvar PgGeometryObject = class extends PgColumn {\n\tstatic [entityKind] = \"PgGeometryObject\";\n\t/** @internal */\n\tcodec = \"geometry(point)\";\n\tsrid = this.config.srid;\n\tmode = \"object\";\n\tgetSQLType() {\n\t\treturn `geometry(point${this.srid === void 0 ? \"\" : `,${this.srid}`})`;\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn `point(${value.x} ${value.y})`;\n\t};\n};\nfunction geometry(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (!config?.mode || config.mode === \"tuple\") return new PgGeometryBuilder(name, config?.srid);\n\treturn new PgGeometryObjectBuilder(name, config?.srid);\n}\n\n//#endregion\nexport { PgGeometry, PgGeometryBuilder, PgGeometryObject, PgGeometryObjectBuilder, geometry };\n//# sourceMappingURL=geometry.js.map",
51
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/real.ts\nvar PgRealBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgRealBuilder\";\n\tconstructor(name, length) {\n\t\tsuper(name, \"number float\", \"PgReal\");\n\t\tthis.config.length = length;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgReal(table, this.config);\n\t}\n};\nvar PgReal = class extends PgColumn {\n\tstatic [entityKind] = \"PgReal\";\n\t/** @internal */\n\tcodec = \"float4\";\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t}\n\tgetSQLType() {\n\t\treturn \"real\";\n\t}\n};\nfunction real(name) {\n\treturn new PgRealBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgReal, PgRealBuilder, real };\n//# sourceMappingURL=real.js.map",
52
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/serial.ts\nvar PgSerialBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgSerialBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number int32\", \"PgSerial\");\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgSerial(table, this.config);\n\t}\n};\nvar PgSerial = class extends PgColumn {\n\tstatic [entityKind] = \"PgSerial\";\n\t/** @internal */\n\tcodec = \"serial\";\n\tgetSQLType() {\n\t\treturn \"serial\";\n\t}\n};\nfunction serial(name) {\n\treturn new PgSerialBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgSerial, PgSerialBuilder, serial };\n//# sourceMappingURL=serial.js.map",
53
+ "import { PgColumn } from \"./common.js\";\nimport { PgIntColumnBuilder } from \"./int.common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/smallint.ts\nvar PgSmallIntBuilder = class extends PgIntColumnBuilder {\n\tstatic [entityKind] = \"PgSmallIntBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number int16\", \"PgSmallInt\");\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgSmallInt(table, this.config);\n\t}\n};\nvar PgSmallInt = class extends PgColumn {\n\tstatic [entityKind] = \"PgSmallInt\";\n\t/** @internal */\n\tcodec = \"smallint\";\n\tgetSQLType() {\n\t\treturn \"smallint\";\n\t}\n};\nfunction smallint(name) {\n\treturn new PgSmallIntBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgSmallInt, PgSmallIntBuilder, smallint };\n//# sourceMappingURL=smallint.js.map",
54
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/columns/smallserial.ts\nvar PgSmallSerialBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgSmallSerialBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"number int16\", \"PgSmallSerial\");\n\t\tthis.config.hasDefault = true;\n\t\tthis.config.notNull = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgSmallSerial(table, this.config);\n\t}\n};\nvar PgSmallSerial = class extends PgColumn {\n\tstatic [entityKind] = \"PgSmallSerial\";\n\t/** @internal */\n\tcodec = \"smallserial\";\n\tgetSQLType() {\n\t\treturn \"smallserial\";\n\t}\n};\nfunction smallserial(name) {\n\treturn new PgSmallSerialBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgSmallSerial, PgSmallSerialBuilder, smallserial };\n//# sourceMappingURL=smallserial.js.map",
55
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/text.ts\nvar PgTextBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgTextBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, config.enum?.length ? \"string enum\" : \"string\", \"PgText\");\n\t\tthis.config.enumValues = config.enum;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgText(table, this.config, this.config.enumValues);\n\t}\n};\nvar PgText = class extends PgColumn {\n\tstatic [entityKind] = \"PgText\";\n\tenumValues;\n\t/** @internal */\n\tcodec = \"text\";\n\tconstructor(table, config, enumValues) {\n\t\tsuper(table, config);\n\t\tthis.enumValues = enumValues;\n\t}\n\tgetSQLType() {\n\t\treturn \"text\";\n\t}\n};\nfunction text(a, b = {}) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgTextBuilder(name, config);\n}\n\n//#endregion\nexport { PgText, PgTextBuilder, text };\n//# sourceMappingURL=text.js.map",
56
+ "import { PgColumn } from \"./common.js\";\nimport { PgDateColumnBuilder } from \"./date.common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/time.ts\nvar PgTimeBuilder = class extends PgDateColumnBuilder {\n\tstatic [entityKind] = \"PgTimeBuilder\";\n\tconstructor(name, withTimezone, precision) {\n\t\tsuper(name, \"string time\", \"PgTime\");\n\t\tthis.withTimezone = withTimezone;\n\t\tthis.precision = precision;\n\t\tthis.config.withTimezone = withTimezone;\n\t\tthis.config.precision = precision;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgTime(table, this.config);\n\t}\n};\nvar PgTime = class extends PgColumn {\n\tstatic [entityKind] = \"PgTime\";\n\t/** @internal */\n\tcodec = \"time\";\n\twithTimezone;\n\tprecision;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.withTimezone = config.withTimezone;\n\t\tthis.precision = config.precision;\n\t}\n\tgetSQLType() {\n\t\treturn `time${this.precision === void 0 ? \"\" : `(${this.precision})`}${this.withTimezone ? \" with time zone\" : \"\"}`;\n\t}\n};\nfunction time(a, b = {}) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgTimeBuilder(name, config.withTimezone ?? false, config.precision);\n}\n\n//#endregion\nexport { PgTime, PgTimeBuilder, time };\n//# sourceMappingURL=time.js.map",
57
+ "import { PgColumn } from \"./common.js\";\nimport { PgDateColumnBuilder } from \"./date.common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/timestamp.ts\nvar PgTimestampBuilder = class extends PgDateColumnBuilder {\n\tstatic [entityKind] = \"PgTimestampBuilder\";\n\tconstructor(name, withTimezone, precision) {\n\t\tsuper(name, \"object date\", \"PgTimestamp\");\n\t\tthis.config.withTimezone = withTimezone;\n\t\tthis.config.precision = precision;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgTimestamp(table, this.config);\n\t}\n};\nvar PgTimestamp = class extends PgColumn {\n\tstatic [entityKind] = \"PgTimestamp\";\n\t/** @internal */\n\tcodec;\n\twithTimezone;\n\tprecision;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.withTimezone = config.withTimezone;\n\t\tthis.precision = config.precision;\n\t\tthis.codec = this.withTimezone ? \"timestamptz\" : \"timestamp\";\n\t}\n\tgetSQLType() {\n\t\treturn `timestamp${this.precision === void 0 ? \"\" : ` (${this.precision})`}${this.withTimezone ? \" with time zone\" : \"\"}`;\n\t}\n\tmapToDriverValue = (value) => {\n\t\tif (typeof value === \"string\") return value;\n\t\treturn value.toISOString();\n\t};\n};\nvar PgTimestampStringBuilder = class extends PgDateColumnBuilder {\n\tstatic [entityKind] = \"PgTimestampStringBuilder\";\n\tconstructor(name, withTimezone, precision) {\n\t\tsuper(name, \"string timestamp\", \"PgTimestampString\");\n\t\tthis.config.withTimezone = withTimezone;\n\t\tthis.config.precision = precision;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgTimestampString(table, this.config);\n\t}\n};\nvar PgTimestampString = class extends PgColumn {\n\tstatic [entityKind] = \"PgTimestampString\";\n\t/** @internal */\n\tcodec;\n\twithTimezone;\n\tprecision;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.withTimezone = config.withTimezone;\n\t\tthis.precision = config.precision;\n\t\tthis.codec = this.withTimezone ? \"timestamptz:string\" : \"timestamp:string\";\n\t}\n\tgetSQLType() {\n\t\treturn `timestamp${this.precision === void 0 ? \"\" : `(${this.precision})`}${this.withTimezone ? \" with time zone\" : \"\"}`;\n\t}\n\tmapToDriverValue = (value) => {\n\t\tif (typeof value === \"string\") return value;\n\t\treturn value.toISOString();\n\t};\n};\nfunction timestamp(a, b = {}) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\tif (config?.mode === \"string\") return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision);\n\treturn new PgTimestampBuilder(name, config?.withTimezone ?? false, config?.precision);\n}\n\n//#endregion\nexport { PgTimestamp, PgTimestampBuilder, PgTimestampString, PgTimestampStringBuilder, timestamp };\n//# sourceMappingURL=timestamp.js.map",
58
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { sql } from \"../../sql/sql.js\";\n\n//#region src/pg-core/columns/uuid.ts\nvar PgUUIDBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgUUIDBuilder\";\n\tconstructor(name) {\n\t\tsuper(name, \"string uuid\", \"PgUUID\");\n\t}\n\t/**\n\t* Adds `default gen_random_uuid()` to the column definition.\n\t*/\n\tdefaultRandom() {\n\t\treturn this.default(sql`gen_random_uuid()`);\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgUUID(table, this.config);\n\t}\n};\nvar PgUUID = class extends PgColumn {\n\tstatic [entityKind] = \"PgUUID\";\n\t/** @internal */\n\tcodec = \"uuid\";\n\tgetSQLType() {\n\t\treturn \"uuid\";\n\t}\n};\nfunction uuid(name) {\n\treturn new PgUUIDBuilder(name ?? \"\");\n}\n\n//#endregion\nexport { PgUUID, PgUUIDBuilder, uuid };\n//# sourceMappingURL=uuid.js.map",
59
+ "import { PgColumn, PgColumnBuilder } from \"./common.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../utils.js\";\n\n//#region src/pg-core/columns/varchar.ts\nvar PgVarcharBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgVarcharBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, config.enum?.length ? \"string enum\" : \"string\", \"PgVarchar\");\n\t\tthis.config.length = config.length;\n\t\tthis.config.enumValues = config.enum;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgVarchar(table, this.config);\n\t}\n};\nvar PgVarchar = class extends PgColumn {\n\tstatic [entityKind] = \"PgVarchar\";\n\t/** @internal */\n\tcodec = \"varchar\";\n\tenumValues;\n\tconstructor(table, config) {\n\t\tsuper(table, config);\n\t\tthis.enumValues = config.enumValues;\n\t}\n\tgetSQLType() {\n\t\treturn this.length === void 0 ? `varchar` : `varchar(${this.length})`;\n\t}\n};\nfunction varchar(a, b = {}) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgVarcharBuilder(name, config);\n}\n\n//#endregion\nexport { PgVarchar, PgVarcharBuilder, varchar };\n//# sourceMappingURL=varchar.js.map",
60
+ "import { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\n\n//#region src/pg-core/columns/vector_extension/bit.ts\nvar PgBinaryVectorBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgBinaryVectorBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, \"string binary\", \"PgBinaryVector\");\n\t\tthis.config.length = config.dimensions;\n\t\tthis.config.isLengthExact = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgBinaryVector(table, this.config);\n\t}\n};\nvar PgBinaryVector = class extends PgColumn {\n\tstatic [entityKind] = \"PgBinaryVector\";\n\t/** @internal */\n\tcodec = \"bit\";\n\tgetSQLType() {\n\t\treturn `bit(${this.length})`;\n\t}\n};\nfunction bit(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgBinaryVectorBuilder(name, config);\n}\n\n//#endregion\nexport { PgBinaryVector, PgBinaryVectorBuilder, bit };\n//# sourceMappingURL=bit.js.map",
61
+ "import { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\n\n//#region src/pg-core/columns/vector_extension/halfvec.ts\nvar PgHalfVectorBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgHalfVectorBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, \"array halfvector\", \"PgHalfVector\");\n\t\tthis.config.length = config.dimensions;\n\t\tthis.config.isLengthExact = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgHalfVector(table, this.config);\n\t}\n};\nvar PgHalfVector = class extends PgColumn {\n\tstatic [entityKind] = \"PgHalfVector\";\n\t/** @internal */\n\tcodec = \"halfvec\";\n\tgetSQLType() {\n\t\treturn `halfvec(${this.length})`;\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn JSON.stringify(value);\n\t};\n};\nfunction halfvec(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgHalfVectorBuilder(name, config);\n}\n\n//#endregion\nexport { PgHalfVector, PgHalfVectorBuilder, halfvec };\n//# sourceMappingURL=halfvec.js.map",
62
+ "import { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\n\n//#region src/pg-core/columns/vector_extension/sparsevec.ts\nvar PgSparseVectorBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgSparseVectorBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, \"string sparsevec\", \"PgSparseVector\");\n\t\tthis.config.vectorDimensions = config.dimensions;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgSparseVector(table, this.config);\n\t}\n};\nvar PgSparseVector = class extends PgColumn {\n\tstatic [entityKind] = \"PgSparseVector\";\n\t/** @internal */\n\tcodec = \"sparsevec\";\n\tvectorDimensions = this.config.vectorDimensions;\n\tgetSQLType() {\n\t\treturn `sparsevec(${this.vectorDimensions})`;\n\t}\n};\nfunction sparsevec(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgSparseVectorBuilder(name, config);\n}\n\n//#endregion\nexport { PgSparseVector, PgSparseVectorBuilder, sparsevec };\n//# sourceMappingURL=sparsevec.js.map",
63
+ "import { PgColumn, PgColumnBuilder } from \"../common.js\";\nimport { entityKind } from \"../../../entity.js\";\nimport { getColumnNameAndConfig } from \"../../../utils.js\";\n\n//#region src/pg-core/columns/vector_extension/vector.ts\nvar PgVectorBuilder = class extends PgColumnBuilder {\n\tstatic [entityKind] = \"PgVectorBuilder\";\n\tconstructor(name, config) {\n\t\tsuper(name, \"array vector\", \"PgVector\");\n\t\tthis.config.length = config.dimensions;\n\t\tthis.config.isLengthExact = true;\n\t}\n\t/** @internal */\n\tbuild(table) {\n\t\treturn new PgVector(table, this.config);\n\t}\n};\nvar PgVector = class extends PgColumn {\n\tstatic [entityKind] = \"PgVector\";\n\t/** @internal */\n\tcodec = \"vector\";\n\tgetSQLType() {\n\t\treturn `vector(${this.length})`;\n\t}\n\tmapToDriverValue = (value) => {\n\t\treturn JSON.stringify(value);\n\t};\n};\nfunction vector(a, b) {\n\tconst { name, config } = getColumnNameAndConfig(a, b);\n\treturn new PgVectorBuilder(name, config);\n}\n\n//#endregion\nexport { PgVector, PgVectorBuilder, vector };\n//# sourceMappingURL=vector.js.map",
64
+ "import { bigint } from \"./bigint.js\";\nimport { bigserial } from \"./bigserial.js\";\nimport { boolean } from \"./boolean.js\";\nimport { char } from \"./char.js\";\nimport { cidr } from \"./cidr.js\";\nimport { customType } from \"./custom.js\";\nimport { date } from \"./date.js\";\nimport { doublePrecision } from \"./double-precision.js\";\nimport { inet } from \"./inet.js\";\nimport { integer } from \"./integer.js\";\nimport { interval } from \"./interval.js\";\nimport { json } from \"./json.js\";\nimport { jsonb } from \"./jsonb.js\";\nimport { line } from \"./line.js\";\nimport { macaddr } from \"./macaddr.js\";\nimport { macaddr8 } from \"./macaddr8.js\";\nimport { numeric } from \"./numeric.js\";\nimport { point } from \"./point.js\";\nimport { geometry } from \"./postgis_extension/geometry.js\";\nimport { real } from \"./real.js\";\nimport { serial } from \"./serial.js\";\nimport { smallint } from \"./smallint.js\";\nimport { smallserial } from \"./smallserial.js\";\nimport { text } from \"./text.js\";\nimport { time } from \"./time.js\";\nimport { timestamp } from \"./timestamp.js\";\nimport { uuid } from \"./uuid.js\";\nimport { varchar } from \"./varchar.js\";\nimport { bit } from \"./vector_extension/bit.js\";\nimport { halfvec } from \"./vector_extension/halfvec.js\";\nimport { sparsevec } from \"./vector_extension/sparsevec.js\";\nimport { vector } from \"./vector_extension/vector.js\";\n\n//#region src/pg-core/columns/all.ts\nfunction getPgColumnBuilders() {\n\treturn {\n\t\tbigint,\n\t\tbigserial,\n\t\tboolean,\n\t\tchar,\n\t\tcidr,\n\t\tcustomType,\n\t\tdate,\n\t\tdoublePrecision,\n\t\tinet,\n\t\tinteger,\n\t\tinterval,\n\t\tjson,\n\t\tjsonb,\n\t\tline,\n\t\tmacaddr,\n\t\tmacaddr8,\n\t\tnumeric,\n\t\tpoint,\n\t\tgeometry,\n\t\treal,\n\t\tserial,\n\t\tsmallint,\n\t\tsmallserial,\n\t\ttext,\n\t\ttime,\n\t\ttimestamp,\n\t\tuuid,\n\t\tvarchar,\n\t\tbit,\n\t\thalfvec,\n\t\tsparsevec,\n\t\tvector\n\t};\n}\n\n//#endregion\nexport { getPgColumnBuilders };\n//# sourceMappingURL=all.js.map",
65
+ "//#region src/casing.ts\nfunction toSnakeCase(input) {\n\treturn (input.replace(/['\\u2019]/g, \"\").match(/[\\da-z]+|[A-Z]+(?![a-z])|[A-Z][\\da-z]+/g) ?? []).map((word) => word.toLowerCase()).join(\"_\");\n}\nfunction toCamelCase(input) {\n\treturn (input.replace(/['\\u2019]/g, \"\").match(/[\\da-z]+|[A-Z]+(?![a-z])|[A-Z][\\da-z]+/g) ?? []).reduce((acc, word, i) => {\n\t\treturn acc + (i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`);\n\t}, \"\");\n}\nfunction getCasingFn(casing) {\n\tif (casing === \"snake_case\") return toSnakeCase;\n\tif (casing === \"camelCase\") return toCamelCase;\n\treturn (name) => name;\n}\n\n//#endregion\nexport { getCasingFn, toCamelCase, toSnakeCase };\n//# sourceMappingURL=casing.js.map",
66
+ "import { getPgColumnBuilders } from \"./columns/all.js\";\nimport { entityKind } from \"../entity.js\";\nimport { Table } from \"../table.js\";\nimport { getCasingFn } from \"../casing.js\";\n\n//#region src/pg-core/table.ts\n/** @internal */\nconst InlineForeignKeys = Symbol.for(\"drizzle:PgInlineForeignKeys\");\n/** @internal */\nconst EnableRLS = Symbol.for(\"drizzle:EnableRLS\");\nvar PgTable = class extends Table {\n\tstatic [entityKind] = \"PgTable\";\n\t/** @internal */\n\tstatic Symbol = Object.assign({}, Table.Symbol, {\n\t\tInlineForeignKeys,\n\t\tEnableRLS\n\t});\n\t/**@internal */\n\t[InlineForeignKeys] = [];\n\t/** @internal */\n\t[EnableRLS] = false;\n\t/** @internal */\n\t[Table.Symbol.ExtraConfigBuilder] = void 0;\n\t/** @internal */\n\t[Table.Symbol.ExtraConfigColumns] = {};\n};\n/** @internal */\nfunction pgTableWithSchema(name, columns, extraConfig, schema, casing, baseName = name) {\n\tconst casingFn = getCasingFn(casing);\n\tconst rawTable = new PgTable(name, schema, baseName);\n\tconst parsedColumns = typeof columns === \"function\" ? columns(getPgColumnBuilders()) : columns;\n\tconst builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\tconst colBuilder = colBuilderBase;\n\t\tcolBuilder.setName(name, casingFn);\n\t\tconst column = colBuilder.build(rawTable).postBuild();\n\t\trawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable));\n\t\treturn [name, column];\n\t}));\n\tconst builtColumnsForExtraConfig = Object.fromEntries(Object.entries(parsedColumns).map(([name, colBuilderBase]) => {\n\t\tconst colBuilder = colBuilderBase;\n\t\tcolBuilder.setName(name, casingFn);\n\t\treturn [name, colBuilder.buildExtraConfigColumn(rawTable)];\n\t}));\n\tconst table = Object.assign(rawTable, builtColumns);\n\ttable[Table.Symbol.Columns] = builtColumns;\n\ttable[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig;\n\tif (extraConfig) table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig;\n\treturn Object.assign(table, { enableRLS: () => {\n\t\ttable[PgTable.Symbol.EnableRLS] = true;\n\t\treturn table;\n\t} });\n}\n/** @internal */\nfunction pgTableWithCasing(casing) {\n\tconst pgTableInternal = (name, columns, extraConfig) => {\n\t\treturn pgTableWithSchema(name, columns, extraConfig, void 0, casing);\n\t};\n\tconst pgTableWithRLS = (name, columns, extraConfig) => {\n\t\tconst table = pgTableWithSchema(name, columns, extraConfig, void 0, casing);\n\t\ttable[EnableRLS] = true;\n\t\treturn table;\n\t};\n\treturn Object.assign(pgTableInternal, { withRLS: pgTableWithRLS });\n}\nconst pgTable = pgTableWithCasing(void 0);\nfunction pgTableCreator(customizeTableName, casing) {\n\tconst fn = (name, columns, extraConfig) => {\n\t\treturn pgTableWithSchema(customizeTableName(name), columns, extraConfig, void 0, casing, name);\n\t};\n\treturn Object.assign(fn, { withRLS: ((name, columns, extraConfig) => {\n\t\tconst table = pgTableWithSchema(customizeTableName(name), columns, extraConfig, void 0, casing, name);\n\t\ttable[EnableRLS] = true;\n\t\treturn table;\n\t}) });\n}\n\n//#endregion\nexport { EnableRLS, InlineForeignKeys, PgTable, pgTable, pgTableCreator, pgTableWithCasing, pgTableWithSchema };\n//# sourceMappingURL=table.js.map",
67
+ "//#region src/pg-core/view-common.ts\nconst PgViewConfig = Symbol.for(\"drizzle:PgViewConfig\");\nconst PgMaterializedViewConfig = Symbol.for(\"drizzle:PgMaterializedViewConfig\");\n\n//#endregion\nexport { PgMaterializedViewConfig, PgViewConfig };\n//# sourceMappingURL=view-common.js.map",
68
+ "import { PrimaryKeyBuilder } from \"./primary-keys.js\";\nimport { CheckBuilder } from \"./checks.js\";\nimport { ForeignKeyBuilder } from \"./foreign-keys.js\";\nimport { IndexBuilder } from \"./indexes.js\";\nimport { PgPolicy } from \"./policies.js\";\nimport { UniqueConstraintBuilder } from \"./unique-constraint.js\";\nimport { PgMaterializedViewConfig, PgViewConfig } from \"./view-common.js\";\nimport { is } from \"../entity.js\";\nimport { Subquery } from \"../subquery.js\";\nimport { ViewBaseConfig } from \"../view-common.js\";\nimport { Table, TableSchema } from \"../table.js\";\nimport { SQL } from \"../sql/sql.js\";\nimport { PgTable } from \"./table.js\";\n\n//#region src/pg-core/utils.ts\nfunction getTableConfig(table) {\n\tconst columns = Object.values(table[Table.Symbol.Columns]);\n\tconst indexes = [];\n\tconst checks = [];\n\tconst primaryKeys = [];\n\tconst foreignKeys = Object.values(table[PgTable.Symbol.InlineForeignKeys]);\n\tconst uniqueConstraints = [];\n\tconst name = table[Table.Symbol.Name];\n\tconst schema = table[Table.Symbol.Schema];\n\tconst policies = [];\n\tconst enableRLS = table[PgTable.Symbol.EnableRLS];\n\tconst extraConfigBuilder = table[PgTable.Symbol.ExtraConfigBuilder];\n\tif (extraConfigBuilder !== void 0) {\n\t\tconst extraConfig = extraConfigBuilder(table[Table.Symbol.ExtraConfigColumns]);\n\t\tconst extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);\n\t\tfor (const builder of extraValues) if (is(builder, IndexBuilder)) indexes.push(builder.build(table));\n\t\telse if (is(builder, CheckBuilder)) checks.push(builder.build(table));\n\t\telse if (is(builder, UniqueConstraintBuilder)) uniqueConstraints.push(builder.build(table));\n\t\telse if (is(builder, PrimaryKeyBuilder)) primaryKeys.push(builder.build(table));\n\t\telse if (is(builder, ForeignKeyBuilder)) foreignKeys.push(builder.build(table));\n\t\telse if (is(builder, PgPolicy)) policies.push(builder);\n\t}\n\treturn {\n\t\tcolumns,\n\t\tindexes,\n\t\tforeignKeys,\n\t\tchecks,\n\t\tprimaryKeys,\n\t\tuniqueConstraints,\n\t\tname,\n\t\tschema,\n\t\tpolicies,\n\t\tenableRLS\n\t};\n}\nfunction extractUsedTable(table) {\n\tif (is(table, PgTable)) return [table[TableSchema] ? `${table[TableSchema]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]];\n\tif (is(table, Subquery)) return table._.usedTables ?? [];\n\tif (is(table, SQL)) return table.usedTables ?? [];\n\treturn [];\n}\nfunction getViewConfig(view) {\n\treturn {\n\t\t...view[ViewBaseConfig],\n\t\t...view[PgViewConfig]\n\t};\n}\nfunction getMaterializedViewConfig(view) {\n\treturn {\n\t\t...view[ViewBaseConfig],\n\t\t...view[PgMaterializedViewConfig]\n\t};\n}\n\n//#endregion\nexport { extractUsedTable, getMaterializedViewConfig, getTableConfig, getViewConfig };\n//# sourceMappingURL=utils.js.map",
69
+ "import { entityKind, is } from \"./entity.js\";\nimport { OriginalColumn } from \"./column-common.js\";\nimport { Column } from \"./column.js\";\nimport { Table } from \"./table.js\";\nimport { SQL, View, isSQLWrapper, sql } from \"./sql/sql.js\";\nimport { Subquery } from \"./subquery.js\";\nimport { ViewBaseConfig } from \"./view-common.js\";\n\n//#region src/alias.ts\nvar ColumnTableAliasProxyHandler = class {\n\tstatic [entityKind] = \"ColumnTableAliasProxyHandler\";\n\tconstructor(table, ignoreColumnAlias) {\n\t\tthis.table = table;\n\t\tthis.ignoreColumnAlias = ignoreColumnAlias;\n\t}\n\tget(columnObj, prop) {\n\t\tif (prop === \"table\") return this.table;\n\t\tif (prop === \"isAlias\" && this.ignoreColumnAlias) return false;\n\t\treturn columnObj[prop];\n\t}\n};\nvar ViewSelectionAliasProxyHandler = class {\n\tstatic [entityKind] = \"ViewSelectionAliasProxyHandler\";\n\tconstructor(view, selection, ignoreColumnAlias) {\n\t\tthis.view = view;\n\t\tthis.selection = selection;\n\t\tthis.ignoreColumnAlias = ignoreColumnAlias;\n\t}\n\tget(selection, prop) {\n\t\tconst value = selection[prop];\n\t\tif (is(value, Column)) return new Proxy(value, new ColumnTableAliasProxyHandler(this.view, this.ignoreColumnAlias));\n\t\tif (is(value, Subquery) || is(value, SQL) || is(value, SQL.Aliased) || isSQLWrapper(value) || typeof value !== \"object\" || value === null) return value;\n\t\treturn new Proxy(value, this);\n\t}\n};\nvar TableAliasProxyHandler = class {\n\tstatic [entityKind] = \"TableAliasProxyHandler\";\n\tconstructor(alias, replaceOriginalName, ignoreColumnAlias) {\n\t\tthis.alias = alias;\n\t\tthis.replaceOriginalName = replaceOriginalName;\n\t\tthis.ignoreColumnAlias = ignoreColumnAlias;\n\t}\n\tget(target, prop) {\n\t\tif (prop === Table.Symbol.IsAlias) return true;\n\t\tif (prop === Table.Symbol.Name) return this.alias;\n\t\tif (this.replaceOriginalName && prop === Table.Symbol.OriginalName) return this.alias;\n\t\tif (prop === ViewBaseConfig) return {\n\t\t\t...target[ViewBaseConfig],\n\t\t\tname: this.alias,\n\t\t\tisAlias: true,\n\t\t\tselectedFields: new Proxy(target[ViewBaseConfig].selectedFields, new ViewSelectionAliasProxyHandler(new Proxy(target, this), target[ViewBaseConfig].selectedFields, this.ignoreColumnAlias))\n\t\t};\n\t\tif (prop === Table.Symbol.Columns) {\n\t\t\tconst columns = target[Table.Symbol.Columns];\n\t\t\tif (!columns) return columns;\n\t\t\tif (is(target, View)) return new Proxy(target[Table.Symbol.Columns], new ViewSelectionAliasProxyHandler(new Proxy(target, this), target[Table.Symbol.Columns], this.ignoreColumnAlias));\n\t\t\tconst proxiedColumns = {};\n\t\t\tObject.keys(columns).map((key) => {\n\t\t\t\tproxiedColumns[key] = new Proxy(columns[key], new ColumnTableAliasProxyHandler(new Proxy(target, this), this.ignoreColumnAlias));\n\t\t\t});\n\t\t\treturn proxiedColumns;\n\t\t}\n\t\tconst value = target[prop];\n\t\tif (is(value, Column)) return new Proxy(value, new ColumnTableAliasProxyHandler(new Proxy(target, this), this.ignoreColumnAlias));\n\t\treturn value;\n\t}\n};\nvar ColumnAliasProxyHandler = class {\n\tstatic [entityKind] = \"ColumnAliasProxyHandler\";\n\tconstructor(alias) {\n\t\tthis.alias = alias;\n\t}\n\tget(target, prop) {\n\t\tif (prop === \"isAlias\") return true;\n\t\tif (prop === \"name\") return this.alias;\n\t\tif (prop === \"keyAsName\") return false;\n\t\tif (prop === OriginalColumn) return () => target;\n\t\treturn target[prop];\n\t}\n};\nvar RelationTableAliasProxyHandler = class {\n\tstatic [entityKind] = \"RelationTableAliasProxyHandler\";\n\tconstructor(alias) {\n\t\tthis.alias = alias;\n\t}\n\tget(target, prop) {\n\t\tif (prop === \"sourceTable\") return aliasedTable(target.sourceTable, this.alias);\n\t\treturn target[prop];\n\t}\n};\nfunction aliasedTable(table, tableAlias) {\n\treturn new Proxy(table, new TableAliasProxyHandler(tableAlias, false, false));\n}\nfunction aliasedColumn(column, alias) {\n\treturn new Proxy(column, new ColumnAliasProxyHandler(alias));\n}\nfunction aliasedRelation(relation, tableAlias) {\n\treturn new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias));\n}\nfunction aliasedTableColumn(column, tableAlias) {\n\treturn new Proxy(column, new ColumnTableAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false, false)), false));\n}\nfunction mapColumnsInAliasedSQLToAlias(query, alias) {\n\treturn new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias);\n}\nfunction mapColumnsInSQLToAlias(query, alias) {\n\treturn sql.join(query.queryChunks.map((c) => {\n\t\tif (is(c, Column)) return aliasedTableColumn(c, alias);\n\t\tif (is(c, SQL)) return mapColumnsInSQLToAlias(c, alias);\n\t\tif (is(c, SQL.Aliased)) return mapColumnsInAliasedSQLToAlias(c, alias);\n\t\treturn c;\n\t}));\n}\nColumn.prototype.as = function(alias) {\n\treturn aliasedColumn(this, alias);\n};\nfunction getOriginalColumnFromAlias(column) {\n\treturn column[OriginalColumn]();\n}\n\n//#endregion\nexport { ColumnAliasProxyHandler, ColumnTableAliasProxyHandler, RelationTableAliasProxyHandler, TableAliasProxyHandler, ViewSelectionAliasProxyHandler, aliasedColumn, aliasedRelation, aliasedTable, aliasedTableColumn, getOriginalColumnFromAlias, mapColumnsInAliasedSQLToAlias, mapColumnsInSQLToAlias };\n//# sourceMappingURL=alias.js.map",
70
+ "import { entityKind, is } from \"./entity.js\";\nimport { Column } from \"./column.js\";\nimport { SQL, View } from \"./sql/sql.js\";\nimport { Subquery } from \"./subquery.js\";\nimport { ViewBaseConfig } from \"./view-common.js\";\nimport { ColumnTableAliasProxyHandler, TableAliasProxyHandler } from \"./alias.js\";\n\n//#region src/selection-proxy.ts\nvar SelectionProxyHandler = class SelectionProxyHandler {\n\tstatic [entityKind] = \"SelectionProxyHandler\";\n\tconfig;\n\tconstructor(config) {\n\t\tthis.config = { ...config };\n\t}\n\tget(subquery, prop) {\n\t\tif (prop === \"_\") return {\n\t\t\t...subquery[\"_\"],\n\t\t\tselectedFields: new Proxy(subquery._.selectedFields, this)\n\t\t};\n\t\tif (prop === ViewBaseConfig) return {\n\t\t\t...subquery[ViewBaseConfig],\n\t\t\tselectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this)\n\t\t};\n\t\tif (typeof prop === \"symbol\") return subquery[prop];\n\t\tconst value = (is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery)[prop];\n\t\tif (is(value, SQL.Aliased)) {\n\t\t\tif (this.config.sqlAliasedBehavior === \"sql\" && !value.isSelectionField) return value.sql;\n\t\t\tconst newValue = value.clone();\n\t\t\tnewValue.isSelectionField = true;\n\t\t\tnewValue.origin = this.config.alias;\n\t\t\treturn newValue;\n\t\t}\n\t\tif (is(value, SQL)) {\n\t\t\tif (this.config.sqlBehavior === \"sql\") return value;\n\t\t\tthrow new Error(`You tried to reference \"${prop}\" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using \".as('alias')\" method.`);\n\t\t}\n\t\tif (is(value, Column)) {\n\t\t\tif (this.config.alias) return new Proxy(value, new ColumnTableAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false, true)), true));\n\t\t\treturn value;\n\t\t}\n\t\tif (typeof value !== \"object\" || value === null) return value;\n\t\treturn new Proxy(value, new SelectionProxyHandler(this.config));\n\t}\n};\n\n//#endregion\nexport { SelectionProxyHandler };\n//# sourceMappingURL=selection-proxy.js.map",
71
+ "import { entityKind } from \"../../entity.js\";\nimport { Table, getTableName } from \"../../table.js\";\nimport { orderSelectedFields } from \"../../utils.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { SelectionProxyHandler } from \"../../selection-proxy.js\";\n\n//#region src/pg-core/query-builders/delete.ts\nvar PgDeleteBase = class {\n\tstatic [entityKind] = \"PgDelete\";\n\tconfig;\n\tconstructor(table, session, dialect, withList) {\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis.config = {\n\t\t\ttable,\n\t\t\twithList\n\t\t};\n\t}\n\t/**\n\t* Adds a `where` clause to the query.\n\t*\n\t* Calling this method will delete only those rows that fulfill a specified condition.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/delete}\n\t*\n\t* @param where the `where` clause.\n\t*\n\t* @example\n\t* You can use conditional operators and `sql function` to filter the rows to be deleted.\n\t*\n\t* ```ts\n\t* // Delete all cars with green color\n\t* await db.delete(cars).where(eq(cars.color, 'green'));\n\t* // or\n\t* await db.delete(cars).where(sql`${cars.color} = 'green'`)\n\t* ```\n\t*\n\t* You can logically combine conditional operators with `and()` and `or()` operators:\n\t*\n\t* ```ts\n\t* // Delete all BMW cars with a green color\n\t* await db.delete(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t*\n\t* // Delete all cars with the green or blue color\n\t* await db.delete(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t* ```\n\t*/\n\twhere(where) {\n\t\tthis.config.where = where;\n\t\treturn this;\n\t}\n\treturning(fields = this.config.table[Table.Symbol.Columns]) {\n\t\tthis.config.returningFields = fields;\n\t\tthis.config.returning = orderSelectedFields(fields, void 0, this.dialect.codecs);\n\t\treturn this;\n\t}\n\t/**\n\t* Attach [sqlcommenter](https://google.github.io/sqlcommenter) comment to a query\n\t*/\n\tcomment(comment) {\n\t\tthis.config.comment = sql.comment(comment);\n\t\treturn this;\n\t}\n\tgetSQL() {\n\t\treturn this.dialect.buildDeleteQuery(this.config);\n\t}\n\ttoSQL() {\n\t\treturn this.dialect.sqlToQuery(this.getSQL());\n\t}\n\t/** @internal */\n\tgetSelectedFields() {\n\t\treturn this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({\n\t\t\talias: getTableName(this.config.table),\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\tsqlBehavior: \"error\"\n\t\t})) : void 0;\n\t}\n\t/** @internal */\n\twithoutSelectionCastCodecs() {\n\t\tthis.config.ignoreSelectionCastCodecs = true;\n\t\treturn this;\n\t}\n\t$dynamic() {\n\t\treturn this;\n\t}\n};\n\n//#endregion\nexport { PgDeleteBase };\n//# sourceMappingURL=delete.js.map",
72
+ "import { extractUsedTable } from \"../utils.js\";\nimport { PgDeleteBase } from \"../query-builders/delete.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { tracer } from \"../../tracing.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/delete.ts\nvar PgAsyncDeleteBase = class extends PgDeleteBase {\n\tstatic [entityKind] = \"PgAsyncDelete\";\n\t/** @internal */\n\t_prepare(name, generateName = false) {\n\t\tconst { session, config, dialect } = this;\n\t\tconst { returning: fields } = config;\n\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\tconst query = dialect.sqlToQuery(this.getSQL());\n\t\t\tconst mapper = fields ? this.dialect.mapperGenerators.rows(fields, void 0) : void 0;\n\t\t\treturn session.prepareQuery(query, fields ? \"arrays\" : \"raw\", name ?? generateName, mapper, {\n\t\t\t\ttype: \"delete\",\n\t\t\t\ttables: [...extractUsedTable(this.config.table)]\n\t\t\t});\n\t\t});\n\t}\n\tprepare(name) {\n\t\treturn this._prepare(name, true);\n\t}\n\texecute = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n};\napplyMixins(PgAsyncDeleteBase, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncDeleteBase };\n//# sourceMappingURL=delete.js.map",
73
+ "import { entityKind } from \"../entity.js\";\n\n//#region src/query-builders/query-builder.ts\nvar TypedQueryBuilder = class {\n\tstatic [entityKind] = \"TypedQueryBuilder\";\n\t/** @internal */\n\tgetSelectedFields() {\n\t\treturn this._.selectedFields;\n\t}\n\t/** @internal */\n\twithoutSelectionCastCodecs() {\n\t\treturn this;\n\t}\n};\n\n//#endregion\nexport { TypedQueryBuilder };\n//# sourceMappingURL=query-builder.js.map",
74
+ "import { entityKind } from \"../entity.js\";\nimport { View } from \"../sql/sql.js\";\n\n//#region src/pg-core/view-base.ts\nvar PgViewBase = class extends View {\n\tstatic [entityKind] = \"PgViewBase\";\n};\n\n//#endregion\nexport { PgViewBase };\n//# sourceMappingURL=view-base.js.map",
75
+ "import { extractUsedTable } from \"../utils.js\";\nimport { entityKind, is } from \"../../entity.js\";\nimport { Subquery } from \"../../subquery.js\";\nimport { ViewBaseConfig } from \"../../view-common.js\";\nimport { Table } from \"../../table.js\";\nimport { getTableColumns, getTableLikeName, haveSameKeys, orderSelectedFields } from \"../../utils.js\";\nimport { SQL, View, sql } from \"../../sql/sql.js\";\nimport { SelectionProxyHandler } from \"../../selection-proxy.js\";\nimport { TypedQueryBuilder } from \"../../query-builders/query-builder.js\";\nimport { PgViewBase } from \"../view-base.js\";\n\n//#region src/pg-core/query-builders/select.ts\nvar PgSelectBuilder = class {\n\tstatic [entityKind] = \"PgSelectBuilder\";\n\tfields;\n\tsession;\n\tdialect;\n\twithList = [];\n\tdistinct;\n\ttagged;\n\tconstructor(config, builder = PgSelectBase) {\n\t\tthis.builder = builder;\n\t\tthis.fields = config.fields;\n\t\tthis.session = config.session;\n\t\tthis.dialect = config.dialect;\n\t\tif (config.withList) this.withList = config.withList;\n\t\tthis.distinct = config.distinct;\n\t}\n\t/**\n\t* Specify the table, subquery, or other target that you're\n\t* building a select query against.\n\t*\n\t* {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM | Postgres from documentation}\n\t*/\n\tfrom(source) {\n\t\tconst isPartialSelect = !!this.fields;\n\t\tconst src = source;\n\t\tlet fields;\n\t\tif (this.fields) fields = this.fields;\n\t\telse if (is(src, Subquery)) fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [key, src[key]]));\n\t\telse if (is(src, PgViewBase)) fields = src[ViewBaseConfig].selectedFields;\n\t\telse if (is(src, SQL)) fields = {};\n\t\telse fields = getTableColumns(src);\n\t\treturn new this.builder({\n\t\t\ttable: src,\n\t\t\tfields,\n\t\t\tisPartialSelect,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\twithList: this.withList,\n\t\t\tdistinct: this.distinct\n\t\t});\n\t}\n};\nvar PgSelectBase = class extends TypedQueryBuilder {\n\tstatic [entityKind] = \"PgSelectQueryBuilder\";\n\t_;\n\tconfig;\n\tjoinsNotNullableMap;\n\ttableName;\n\tisPartialSelect;\n\tsession;\n\tdialect;\n\tcacheConfig;\n\tusedTables = /* @__PURE__ */ new Set();\n\tconstructor(config) {\n\t\tsuper();\n\t\tthis.session = config.session;\n\t\tthis.dialect = config.dialect;\n\t\tthis.config = {\n\t\t\twithList: config.withList,\n\t\t\ttable: config.table,\n\t\t\tfields: { ...config.fields },\n\t\t\tdistinct: config.distinct,\n\t\t\tsetOperators: []\n\t\t};\n\t\tthis.isPartialSelect = config.isPartialSelect;\n\t\tthis._ = {\n\t\t\tselectedFields: this.config.fields,\n\t\t\tconfig: this.config\n\t\t};\n\t\tthis.tableName = getTableLikeName(config.table);\n\t\tthis.joinsNotNullableMap = typeof this.tableName === \"string\" ? { [this.tableName]: true } : {};\n\t\tfor (const item of extractUsedTable(config.table)) this.usedTables.add(item);\n\t\tthis.config.withList?.forEach((it) => {\n\t\t\tconst extracted = extractUsedTable(it);\n\t\t\tfor (const el of extracted) this.usedTables.add(el);\n\t\t});\n\t}\n\t/** @internal */\n\tgetUsedTables() {\n\t\treturn [...this.usedTables];\n\t}\n\tcreateJoin(joinType, lateral) {\n\t\treturn ((table, on) => {\n\t\t\tconst baseTableName = this.tableName;\n\t\t\tconst tableName = getTableLikeName(table);\n\t\t\tfor (const item of extractUsedTable(table)) this.usedTables.add(item);\n\t\t\tif (typeof tableName === \"string\" && this.config.joins?.some((join) => join.alias === tableName)) throw new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\tif (!this.isPartialSelect) {\n\t\t\t\tif (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === \"string\") this.config.fields = { [baseTableName]: this.config.fields };\n\t\t\t\tif (typeof tableName === \"string\" && !is(table, SQL)) {\n\t\t\t\t\tconst selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns];\n\t\t\t\t\tthis.config.fields[tableName] = selection;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (typeof on === \"function\") on = on(new Proxy(this.config.fields, new SelectionProxyHandler({\n\t\t\t\tsqlAliasedBehavior: \"sql\",\n\t\t\t\tsqlBehavior: \"sql\"\n\t\t\t})));\n\t\t\tif (!this.config.joins) this.config.joins = [];\n\t\t\tthis.config.joins.push({\n\t\t\t\ton,\n\t\t\t\ttable,\n\t\t\t\tjoinType,\n\t\t\t\talias: tableName,\n\t\t\t\tlateral\n\t\t\t});\n\t\t\tif (typeof tableName === \"string\") switch (joinType) {\n\t\t\t\tcase \"left\":\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"right\":\n\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"cross\":\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"full\":\n\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn this;\n\t\t});\n\t}\n\t/**\n\t* Executes a `left join` operation by adding another table to the current query.\n\t*\n\t* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#left-join}\n\t*\n\t* @param table the table to join.\n\t* @param on the `on` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all users and their pets\n\t* const usersWithPets: { user: User; pets: Pet | null; }[] = await db.select()\n\t* .from(users)\n\t* .leftJoin(pets, eq(users.id, pets.ownerId))\n\t*\n\t* // Select userId and petId\n\t* const usersIdsAndPetIds: { userId: number; petId: number | null; }[] = await db.select({\n\t* userId: users.id,\n\t* petId: pets.id,\n\t* })\n\t* .from(users)\n\t* .leftJoin(pets, eq(users.id, pets.ownerId))\n\t* ```\n\t*/\n\tleftJoin = this.createJoin(\"left\", false);\n\t/**\n\t* Executes a `left join lateral` operation by adding subquery to the current query.\n\t*\n\t* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.\n\t*\n\t* Calling this method associates each row of the table with the corresponding row from the joined table, if a match is found. If no matching row exists, it sets all columns of the joined table to null.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#left-join-lateral}\n\t*\n\t* @param table the subquery to join.\n\t* @param on the `on` clause.\n\t*/\n\tleftJoinLateral = this.createJoin(\"left\", true);\n\t/**\n\t* Executes a `right join` operation by adding another table to the current query.\n\t*\n\t* Calling this method associates each row of the joined table with the corresponding row from the main table, if a match is found. If no matching row exists, it sets all columns of the main table to null.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#right-join}\n\t*\n\t* @param table the table to join.\n\t* @param on the `on` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all users and their pets\n\t* const usersWithPets: { user: User | null; pets: Pet; }[] = await db.select()\n\t* .from(users)\n\t* .rightJoin(pets, eq(users.id, pets.ownerId))\n\t*\n\t* // Select userId and petId\n\t* const usersIdsAndPetIds: { userId: number | null; petId: number; }[] = await db.select({\n\t* userId: users.id,\n\t* petId: pets.id,\n\t* })\n\t* .from(users)\n\t* .rightJoin(pets, eq(users.id, pets.ownerId))\n\t* ```\n\t*/\n\trightJoin = this.createJoin(\"right\", false);\n\t/**\n\t* Executes an `inner join` operation, creating a new table by combining rows from two tables that have matching values.\n\t*\n\t* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join}\n\t*\n\t* @param table the table to join.\n\t* @param on the `on` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all users and their pets\n\t* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()\n\t* .from(users)\n\t* .innerJoin(pets, eq(users.id, pets.ownerId))\n\t*\n\t* // Select userId and petId\n\t* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({\n\t* userId: users.id,\n\t* petId: pets.id,\n\t* })\n\t* .from(users)\n\t* .innerJoin(pets, eq(users.id, pets.ownerId))\n\t* ```\n\t*/\n\tinnerJoin = this.createJoin(\"inner\", false);\n\t/**\n\t* Executes an `inner join lateral` operation, creating a new table by combining rows from two queries that have matching values.\n\t*\n\t* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.\n\t*\n\t* Calling this method retrieves rows that have corresponding entries in both joined tables. Rows without matching entries in either table are excluded, resulting in a table that includes only matching pairs.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#inner-join-lateral}\n\t*\n\t* @param table the subquery to join.\n\t* @param on the `on` clause.\n\t*/\n\tinnerJoinLateral = this.createJoin(\"inner\", true);\n\t/**\n\t* Executes a `full join` operation by combining rows from two tables into a new table.\n\t*\n\t* Calling this method retrieves all rows from both main and joined tables, merging rows with matching values and filling in `null` for non-matching columns.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#full-join}\n\t*\n\t* @param table the table to join.\n\t* @param on the `on` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all users and their pets\n\t* const usersWithPets: { user: User | null; pets: Pet | null; }[] = await db.select()\n\t* .from(users)\n\t* .fullJoin(pets, eq(users.id, pets.ownerId))\n\t*\n\t* // Select userId and petId\n\t* const usersIdsAndPetIds: { userId: number | null; petId: number | null; }[] = await db.select({\n\t* userId: users.id,\n\t* petId: pets.id,\n\t* })\n\t* .from(users)\n\t* .fullJoin(pets, eq(users.id, pets.ownerId))\n\t* ```\n\t*/\n\tfullJoin = this.createJoin(\"full\", false);\n\t/**\n\t* Executes a `cross join` operation by combining rows from two tables into a new table.\n\t*\n\t* Calling this method retrieves all rows from both main and joined tables, merging all rows from each table.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join}\n\t*\n\t* @param table the table to join.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all users, each user with every pet\n\t* const usersWithPets: { user: User; pets: Pet; }[] = await db.select()\n\t* .from(users)\n\t* .crossJoin(pets)\n\t*\n\t* // Select userId and petId\n\t* const usersIdsAndPetIds: { userId: number; petId: number; }[] = await db.select({\n\t* userId: users.id,\n\t* petId: pets.id,\n\t* })\n\t* .from(users)\n\t* .crossJoin(pets)\n\t* ```\n\t*/\n\tcrossJoin = this.createJoin(\"cross\", false);\n\t/**\n\t* Executes a `cross join lateral` operation by combining rows from two queries into a new table.\n\t*\n\t* A `lateral` join allows the right-hand expression to refer to columns from the left-hand side.\n\t*\n\t* Calling this method retrieves all rows from both main and joined queries, merging all rows from each query.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/joins#cross-join-lateral}\n\t*\n\t* @param table the query to join.\n\t*/\n\tcrossJoinLateral = this.createJoin(\"cross\", true);\n\tcreateSetOperator(type, isAll) {\n\t\treturn (rightSelection) => {\n\t\t\tconst rightSelect = typeof rightSelection === \"function\" ? rightSelection(getPgSetOperators()) : rightSelection;\n\t\t\tif (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) throw new Error(\"Set operator error (union / intersect / except): selected fields are not the same or are in a different order\");\n\t\t\tthis.config.setOperators.push({\n\t\t\t\ttype,\n\t\t\t\tisAll,\n\t\t\t\trightSelect\n\t\t\t});\n\t\t\treturn this;\n\t\t};\n\t}\n\t/**\n\t* Adds `union` set operator to the query.\n\t*\n\t* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all unique names from customers and users tables\n\t* await db.select({ name: users.name })\n\t* .from(users)\n\t* .union(\n\t* db.select({ name: customers.name }).from(customers)\n\t* );\n\t* // or\n\t* import { union } from 'drizzle-orm/pg-core'\n\t*\n\t* await union(\n\t* db.select({ name: users.name }).from(users),\n\t* db.select({ name: customers.name }).from(customers)\n\t* );\n\t* ```\n\t*/\n\tunion = this.createSetOperator(\"union\", false);\n\t/**\n\t* Adds `union all` set operator to the query.\n\t*\n\t* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all transaction ids from both online and in-store sales\n\t* await db.select({ transaction: onlineSales.transactionId })\n\t* .from(onlineSales)\n\t* .unionAll(\n\t* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t* );\n\t* // or\n\t* import { unionAll } from 'drizzle-orm/pg-core'\n\t*\n\t* await unionAll(\n\t* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n\t* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n\t* );\n\t* ```\n\t*/\n\tunionAll = this.createSetOperator(\"union\", true);\n\t/**\n\t* Adds `intersect` set operator to the query.\n\t*\n\t* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select course names that are offered in both departments A and B\n\t* await db.select({ courseName: depA.courseName })\n\t* .from(depA)\n\t* .intersect(\n\t* db.select({ courseName: depB.courseName }).from(depB)\n\t* );\n\t* // or\n\t* import { intersect } from 'drizzle-orm/pg-core'\n\t*\n\t* await intersect(\n\t* db.select({ courseName: depA.courseName }).from(depA),\n\t* db.select({ courseName: depB.courseName }).from(depB)\n\t* );\n\t* ```\n\t*/\n\tintersect = this.createSetOperator(\"intersect\", false);\n\t/**\n\t* Adds `intersect all` set operator to the query.\n\t*\n\t* Calling this method will retain only the rows that are present in both result sets including all duplicates.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all products and quantities that are ordered by both regular and VIP customers\n\t* await db.select({\n\t* productId: regularCustomerOrders.productId,\n\t* quantityOrdered: regularCustomerOrders.quantityOrdered\n\t* })\n\t* .from(regularCustomerOrders)\n\t* .intersectAll(\n\t* db.select({\n\t* productId: vipCustomerOrders.productId,\n\t* quantityOrdered: vipCustomerOrders.quantityOrdered\n\t* })\n\t* .from(vipCustomerOrders)\n\t* );\n\t* // or\n\t* import { intersectAll } from 'drizzle-orm/pg-core'\n\t*\n\t* await intersectAll(\n\t* db.select({\n\t* productId: regularCustomerOrders.productId,\n\t* quantityOrdered: regularCustomerOrders.quantityOrdered\n\t* })\n\t* .from(regularCustomerOrders),\n\t* db.select({\n\t* productId: vipCustomerOrders.productId,\n\t* quantityOrdered: vipCustomerOrders.quantityOrdered\n\t* })\n\t* .from(vipCustomerOrders)\n\t* );\n\t* ```\n\t*/\n\tintersectAll = this.createSetOperator(\"intersect\", true);\n\t/**\n\t* Adds `except` set operator to the query.\n\t*\n\t* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all courses offered in department A but not in department B\n\t* await db.select({ courseName: depA.courseName })\n\t* .from(depA)\n\t* .except(\n\t* db.select({ courseName: depB.courseName }).from(depB)\n\t* );\n\t* // or\n\t* import { except } from 'drizzle-orm/pg-core'\n\t*\n\t* await except(\n\t* db.select({ courseName: depA.courseName }).from(depA),\n\t* db.select({ courseName: depB.courseName }).from(depB)\n\t* );\n\t* ```\n\t*/\n\texcept = this.createSetOperator(\"except\", false);\n\t/**\n\t* Adds `except all` set operator to the query.\n\t*\n\t* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all products that are ordered by regular customers but not by VIP customers\n\t* await db.select({\n\t* productId: regularCustomerOrders.productId,\n\t* quantityOrdered: regularCustomerOrders.quantityOrdered,\n\t* })\n\t* .from(regularCustomerOrders)\n\t* .exceptAll(\n\t* db.select({\n\t* productId: vipCustomerOrders.productId,\n\t* quantityOrdered: vipCustomerOrders.quantityOrdered,\n\t* })\n\t* .from(vipCustomerOrders)\n\t* );\n\t* // or\n\t* import { exceptAll } from 'drizzle-orm/pg-core'\n\t*\n\t* await exceptAll(\n\t* db.select({\n\t* productId: regularCustomerOrders.productId,\n\t* quantityOrdered: regularCustomerOrders.quantityOrdered\n\t* })\n\t* .from(regularCustomerOrders),\n\t* db.select({\n\t* productId: vipCustomerOrders.productId,\n\t* quantityOrdered: vipCustomerOrders.quantityOrdered\n\t* })\n\t* .from(vipCustomerOrders)\n\t* );\n\t* ```\n\t*/\n\texceptAll = this.createSetOperator(\"except\", true);\n\t/** @internal */\n\taddSetOperators(setOperators) {\n\t\tthis.config.setOperators.push(...setOperators);\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `where` clause to the query.\n\t*\n\t* Calling this method will select only those rows that fulfill a specified condition.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/select#filtering}\n\t*\n\t* @param where the `where` clause.\n\t*\n\t* @example\n\t* You can use conditional operators and `sql function` to filter the rows to be selected.\n\t*\n\t* ```ts\n\t* // Select all cars with green color\n\t* await db.select().from(cars).where(eq(cars.color, 'green'));\n\t* // or\n\t* await db.select().from(cars).where(sql`${cars.color} = 'green'`)\n\t* ```\n\t*\n\t* You can logically combine conditional operators with `and()` and `or()` operators:\n\t*\n\t* ```ts\n\t* // Select all BMW cars with a green color\n\t* await db.select().from(cars).where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t*\n\t* // Select all cars with the green or blue color\n\t* await db.select().from(cars).where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t* ```\n\t*/\n\twhere(where) {\n\t\tif (typeof where === \"function\") where = where(new Proxy(this.config.fields, new SelectionProxyHandler({\n\t\t\tsqlAliasedBehavior: \"sql\",\n\t\t\tsqlBehavior: \"sql\"\n\t\t})));\n\t\tthis.config.where = where;\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `having` clause to the query.\n\t*\n\t* Calling this method will select only those rows that fulfill a specified condition. It is typically used with aggregate functions to filter the aggregated data based on a specified condition.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/select#aggregations}\n\t*\n\t* @param having the `having` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Select all brands with more than one car\n\t* await db.select({\n\t* \tbrand: cars.brand,\n\t* \tcount: sql<number>`cast(count(${cars.id}) as int)`,\n\t* })\n\t* .from(cars)\n\t* .groupBy(cars.brand)\n\t* .having(({ count }) => gt(count, 1));\n\t* ```\n\t*/\n\thaving(having) {\n\t\tif (typeof having === \"function\") having = having(new Proxy(this.config.fields, new SelectionProxyHandler({\n\t\t\tsqlAliasedBehavior: \"sql\",\n\t\t\tsqlBehavior: \"sql\"\n\t\t})));\n\t\tthis.config.having = having;\n\t\treturn this;\n\t}\n\tgroupBy(...columns) {\n\t\tif (typeof columns[0] === \"function\") {\n\t\t\tconst groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({\n\t\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\t\tsqlBehavior: \"sql\"\n\t\t\t})));\n\t\t\tthis.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy];\n\t\t} else this.config.groupBy = columns;\n\t\treturn this;\n\t}\n\torderBy(...columns) {\n\t\tif (typeof columns[0] === \"function\") {\n\t\t\tconst orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({\n\t\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\t\tsqlBehavior: \"sql\"\n\t\t\t})));\n\t\t\tconst orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy];\n\t\t\tif (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;\n\t\t\telse this.config.orderBy = orderByArray;\n\t\t} else {\n\t\t\tconst orderByArray = columns;\n\t\t\tif (this.config.setOperators.length > 0) this.config.setOperators.at(-1).orderBy = orderByArray;\n\t\t\telse this.config.orderBy = orderByArray;\n\t\t}\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `limit` clause to the query.\n\t*\n\t* Calling this method will set the maximum number of rows that will be returned by this query.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t*\n\t* @param limit the `limit` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Get the first 10 people from this query.\n\t* await db.select().from(people).limit(10);\n\t* ```\n\t*/\n\tlimit(limit) {\n\t\tif (this.config.setOperators.length > 0) this.config.setOperators.at(-1).limit = limit;\n\t\telse this.config.limit = limit;\n\t\treturn this;\n\t}\n\t/**\n\t* Adds an `offset` clause to the query.\n\t*\n\t* Calling this method will skip a number of rows when returning results from this query.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/select#limit--offset}\n\t*\n\t* @param offset the `offset` clause.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Get the 10th-20th people from this query.\n\t* await db.select().from(people).offset(10).limit(10);\n\t* ```\n\t*/\n\toffset(offset) {\n\t\tif (this.config.setOperators.length > 0) this.config.setOperators.at(-1).offset = offset;\n\t\telse this.config.offset = offset;\n\t\treturn this;\n\t}\n\t/**\n\t* Adds a `for` clause to the query.\n\t*\n\t* Calling this method will specify a lock strength for this query that controls how strictly it acquires exclusive access to the rows being queried.\n\t*\n\t* See docs: {@link https://www.postgresql.org/docs/current/sql-select.html#SQL-FOR-UPDATE-SHARE}\n\t*\n\t* @param strength the lock strength.\n\t* @param config the lock configuration.\n\t*/\n\tfor(strength, config = {}) {\n\t\tthis.config.lockingClause = {\n\t\t\tstrength,\n\t\t\tconfig\n\t\t};\n\t\treturn this;\n\t}\n\t/**\n\t* Attach [sqlcommenter](https://google.github.io/sqlcommenter) comment to a query\n\t*/\n\tcomment(comment) {\n\t\tthis.config.comment = sql.comment(comment);\n\t\treturn this;\n\t}\n\tgetSQL() {\n\t\tthis.config.fieldsFlat = orderSelectedFields(this.config.fields, void 0, this.dialect.codecs);\n\t\treturn this.dialect.buildSelectQuery(this.config);\n\t}\n\ttoSQL() {\n\t\treturn this.dialect.sqlToQuery(this.getSQL());\n\t}\n\tas(alias) {\n\t\tconst usedTables = [];\n\t\tusedTables.push(...extractUsedTable(this.config.table));\n\t\tif (this.config.joins) for (const it of this.config.joins) usedTables.push(...extractUsedTable(it.table));\n\t\treturn new Proxy(new Subquery(this.withoutSelectionCastCodecs().getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({\n\t\t\talias,\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\tsqlBehavior: \"error\"\n\t\t}));\n\t}\n\t/** @internal */\n\tgetSelectedFields() {\n\t\treturn new Proxy(this.config.fields, new SelectionProxyHandler({\n\t\t\talias: this.tableName,\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\tsqlBehavior: \"error\"\n\t\t}));\n\t}\n\t/** @internal */\n\twithoutSelectionCastCodecs() {\n\t\tthis.config.ignoreSelectionCastCodecs = true;\n\t\treturn this;\n\t}\n\t$dynamic() {\n\t\treturn this;\n\t}\n\t$withCache(config) {\n\t\tthis.cacheConfig = config === void 0 ? {\n\t\t\tconfig: {},\n\t\t\tenabled: true,\n\t\t\tautoInvalidate: true\n\t\t} : config === false ? { enabled: false } : {\n\t\t\tenabled: true,\n\t\t\tautoInvalidate: true,\n\t\t\t...config\n\t\t};\n\t\treturn this;\n\t}\n};\nfunction createSetOperator(type, isAll) {\n\treturn (leftSelect, rightSelect, ...restSelects) => {\n\t\tconst setOperators = [rightSelect, ...restSelects].map((select) => ({\n\t\t\ttype,\n\t\t\tisAll,\n\t\t\trightSelect: select\n\t\t}));\n\t\tfor (const setOperator of setOperators) if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) throw new Error(\"Set operator error (union / intersect / except): selected fields are not the same or are in a different order\");\n\t\treturn leftSelect.addSetOperators(setOperators);\n\t};\n}\nconst getPgSetOperators = () => ({\n\tunion,\n\tunionAll,\n\tintersect,\n\tintersectAll,\n\texcept,\n\texceptAll\n});\n/**\n* Adds `union` set operator to the query.\n*\n* Calling this method will combine the result sets of the `select` statements and remove any duplicate rows that appear across them.\n*\n* See docs: {@link https://orm.drizzle.team/docs/set-operations#union}\n*\n* @example\n*\n* ```ts\n* // Select all unique names from customers and users tables\n* import { union } from 'drizzle-orm/pg-core'\n*\n* await union(\n* db.select({ name: users.name }).from(users),\n* db.select({ name: customers.name }).from(customers)\n* );\n* // or\n* await db.select({ name: users.name })\n* .from(users)\n* .union(\n* db.select({ name: customers.name }).from(customers)\n* );\n* ```\n*/\nconst union = createSetOperator(\"union\", false);\n/**\n* Adds `union all` set operator to the query.\n*\n* Calling this method will combine the result-set of the `select` statements and keep all duplicate rows that appear across them.\n*\n* See docs: {@link https://orm.drizzle.team/docs/set-operations#union-all}\n*\n* @example\n*\n* ```ts\n* // Select all transaction ids from both online and in-store sales\n* import { unionAll } from 'drizzle-orm/pg-core'\n*\n* await unionAll(\n* db.select({ transaction: onlineSales.transactionId }).from(onlineSales),\n* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n* );\n* // or\n* await db.select({ transaction: onlineSales.transactionId })\n* .from(onlineSales)\n* .unionAll(\n* db.select({ transaction: inStoreSales.transactionId }).from(inStoreSales)\n* );\n* ```\n*/\nconst unionAll = createSetOperator(\"union\", true);\n/**\n* Adds `intersect` set operator to the query.\n*\n* Calling this method will retain only the rows that are present in both result sets and eliminate duplicates.\n*\n* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect}\n*\n* @example\n*\n* ```ts\n* // Select course names that are offered in both departments A and B\n* import { intersect } from 'drizzle-orm/pg-core'\n*\n* await intersect(\n* db.select({ courseName: depA.courseName }).from(depA),\n* db.select({ courseName: depB.courseName }).from(depB)\n* );\n* // or\n* await db.select({ courseName: depA.courseName })\n* .from(depA)\n* .intersect(\n* db.select({ courseName: depB.courseName }).from(depB)\n* );\n* ```\n*/\nconst intersect = createSetOperator(\"intersect\", false);\n/**\n* Adds `intersect all` set operator to the query.\n*\n* Calling this method will retain only the rows that are present in both result sets including all duplicates.\n*\n* See docs: {@link https://orm.drizzle.team/docs/set-operations#intersect-all}\n*\n* @example\n*\n* ```ts\n* // Select all products and quantities that are ordered by both regular and VIP customers\n* import { intersectAll } from 'drizzle-orm/pg-core'\n*\n* await intersectAll(\n* db.select({\n* productId: regularCustomerOrders.productId,\n* quantityOrdered: regularCustomerOrders.quantityOrdered\n* })\n* .from(regularCustomerOrders),\n* db.select({\n* productId: vipCustomerOrders.productId,\n* quantityOrdered: vipCustomerOrders.quantityOrdered\n* })\n* .from(vipCustomerOrders)\n* );\n* // or\n* await db.select({\n* productId: regularCustomerOrders.productId,\n* quantityOrdered: regularCustomerOrders.quantityOrdered\n* })\n* .from(regularCustomerOrders)\n* .intersectAll(\n* db.select({\n* productId: vipCustomerOrders.productId,\n* quantityOrdered: vipCustomerOrders.quantityOrdered\n* })\n* .from(vipCustomerOrders)\n* );\n* ```\n*/\nconst intersectAll = createSetOperator(\"intersect\", true);\n/**\n* Adds `except` set operator to the query.\n*\n* Calling this method will retrieve all unique rows from the left query, except for the rows that are present in the result set of the right query.\n*\n* See docs: {@link https://orm.drizzle.team/docs/set-operations#except}\n*\n* @example\n*\n* ```ts\n* // Select all courses offered in department A but not in department B\n* import { except } from 'drizzle-orm/pg-core'\n*\n* await except(\n* db.select({ courseName: depA.courseName }).from(depA),\n* db.select({ courseName: depB.courseName }).from(depB)\n* );\n* // or\n* await db.select({ courseName: depA.courseName })\n* .from(depA)\n* .except(\n* db.select({ courseName: depB.courseName }).from(depB)\n* );\n* ```\n*/\nconst except = createSetOperator(\"except\", false);\n/**\n* Adds `except all` set operator to the query.\n*\n* Calling this method will retrieve all rows from the left query, except for the rows that are present in the result set of the right query.\n*\n* See docs: {@link https://orm.drizzle.team/docs/set-operations#except-all}\n*\n* @example\n*\n* ```ts\n* // Select all products that are ordered by regular customers but not by VIP customers\n* import { exceptAll } from 'drizzle-orm/pg-core'\n*\n* await exceptAll(\n* db.select({\n* productId: regularCustomerOrders.productId,\n* quantityOrdered: regularCustomerOrders.quantityOrdered\n* })\n* .from(regularCustomerOrders),\n* db.select({\n* productId: vipCustomerOrders.productId,\n* quantityOrdered: vipCustomerOrders.quantityOrdered\n* })\n* .from(vipCustomerOrders)\n* );\n* // or\n* await db.select({\n* productId: regularCustomerOrders.productId,\n* quantityOrdered: regularCustomerOrders.quantityOrdered,\n* })\n* .from(regularCustomerOrders)\n* .exceptAll(\n* db.select({\n* productId: vipCustomerOrders.productId,\n* quantityOrdered: vipCustomerOrders.quantityOrdered,\n* })\n* .from(vipCustomerOrders)\n* );\n* ```\n*/\nconst exceptAll = createSetOperator(\"except\", true);\n\n//#endregion\nexport { PgSelectBase, PgSelectBuilder, except, exceptAll, intersect, intersectAll, union, unionAll };\n//# sourceMappingURL=select.js.map",
76
+ "import { entityKind } from \"./entity.js\";\n\n//#region src/errors.ts\nvar DrizzleError = class extends Error {\n\tstatic [entityKind] = \"DrizzleError\";\n\tconstructor({ message, cause }) {\n\t\tsuper(message);\n\t\tthis.name = \"DrizzleError\";\n\t\tthis.cause = cause;\n\t}\n};\nvar DrizzleQueryError = class DrizzleQueryError extends Error {\n\tstatic [entityKind] = \"DrizzleQueryError\";\n\tconstructor(query, params, cause) {\n\t\tsuper(`Failed query: ${query}\\nparams: ${params}`);\n\t\tthis.query = query;\n\t\tthis.params = params;\n\t\tthis.cause = cause;\n\t\tthis.name = \"DrizzleQueryError\";\n\t\tError.captureStackTrace(this, DrizzleQueryError);\n\t\tif (cause) this.cause = cause;\n\t}\n};\nvar TransactionRollbackError = class extends DrizzleError {\n\tstatic [entityKind] = \"TransactionRollbackError\";\n\tconstructor() {\n\t\tsuper({ message: \"Rollback\" });\n\t\tthis.name = \"TransactionRollbackError\";\n\t}\n};\n\n//#endregion\nexport { DrizzleError, DrizzleQueryError, TransactionRollbackError };\n//# sourceMappingURL=errors.js.map",
77
+ "import { Param, Placeholder, SQL, StringChunk, View, isDriverValueEncoder, isSQLWrapper, sql } from \"../sql.js\";\nimport { is } from \"../../entity.js\";\nimport { Table } from \"../../table.js\";\nimport { Column } from \"../../column.js\";\n\n//#region src/sql/expressions/conditions.ts\nfunction bindIfParam(value, column) {\n\tif (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) return new Param(value, column);\n\treturn value;\n}\n/**\n* Test that two values are equal.\n*\n* Remember that the SQL standard dictates that\n* two NULL values are not equal, so if you want to test\n* whether a value is null, you may want to use\n* `isNull` instead.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars made by Ford\n* db.select().from(cars)\n* .where(eq(cars.make, 'Ford'))\n* ```\n*\n* @see isNull for a way to test equality to NULL.\n*/\nconst eq = (left, right) => {\n\treturn sql`${left} = ${bindIfParam(right, left)}`;\n};\n/**\n* Test that two values are not equal.\n*\n* Remember that the SQL standard dictates that\n* two NULL values are not equal, so if you want to test\n* whether a value is not null, you may want to use\n* `isNotNull` instead.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars not made by Ford\n* db.select().from(cars)\n* .where(ne(cars.make, 'Ford'))\n* ```\n*\n* @see isNotNull for a way to test whether a value is not null.\n*/\nconst ne = (left, right) => {\n\treturn sql`${left} <> ${bindIfParam(right, left)}`;\n};\nfunction and(...unfilteredConditions) {\n\tconst conditions = unfilteredConditions.filter((c) => c !== void 0);\n\tif (conditions.length === 0) return;\n\tif (conditions.length === 1) return new SQL(conditions);\n\treturn new SQL([\n\t\tnew StringChunk(\"(\"),\n\t\tsql.join(conditions.map((c) => sql`(${c})`), new StringChunk(\" and \")),\n\t\tnew StringChunk(\")\")\n\t]);\n}\nfunction or(...unfilteredConditions) {\n\tconst conditions = unfilteredConditions.filter((c) => c !== void 0);\n\tif (conditions.length === 0) return;\n\tif (conditions.length === 1) return new SQL(conditions);\n\treturn new SQL([\n\t\tnew StringChunk(\"(\"),\n\t\tsql.join(conditions.map((c) => sql`(${c})`), new StringChunk(\" or \")),\n\t\tnew StringChunk(\")\")\n\t]);\n}\n/**\n* Negate the meaning of an expression using the `not` keyword.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars _not_ made by GM or Ford.\n* db.select().from(cars)\n* .where(not(inArray(cars.make, ['GM', 'Ford'])))\n* ```\n*/\nfunction not(condition) {\n\treturn is(condition, SQL) ? sql`not (${condition})` : sql`not ${condition}`;\n}\n/**\n* Test that the first expression passed is greater than\n* the second expression.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars made after 2000.\n* db.select().from(cars)\n* .where(gt(cars.year, 2000))\n* ```\n*\n* @see gte for greater-than-or-equal\n*/\nconst gt = (left, right) => {\n\treturn sql`${left} > ${bindIfParam(right, left)}`;\n};\n/**\n* Test that the first expression passed is greater than\n* or equal to the second expression. Use `gt` to\n* test whether an expression is strictly greater\n* than another.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars made on or after 2000.\n* db.select().from(cars)\n* .where(gte(cars.year, 2000))\n* ```\n*\n* @see gt for a strictly greater-than condition\n*/\nconst gte = (left, right) => {\n\treturn sql`${left} >= ${bindIfParam(right, left)}`;\n};\n/**\n* Test that the first expression passed is less than\n* the second expression.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars made before 2000.\n* db.select().from(cars)\n* .where(lt(cars.year, 2000))\n* ```\n*\n* @see lte for less-than-or-equal\n*/\nconst lt = (left, right) => {\n\treturn sql`${left} < ${bindIfParam(right, left)}`;\n};\n/**\n* Test that the first expression passed is less than\n* or equal to the second expression.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars made before 2000.\n* db.select().from(cars)\n* .where(lte(cars.year, 2000))\n* ```\n*\n* @see lt for a strictly less-than condition\n*/\nconst lte = (left, right) => {\n\treturn sql`${left} <= ${bindIfParam(right, left)}`;\n};\nfunction inArray(column, values) {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) return sql`false`;\n\t\treturn sql`${column} in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\treturn sql`${column} in ${bindIfParam(values, column)}`;\n}\nfunction notInArray(column, values) {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) return sql`true`;\n\t\treturn sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`;\n\t}\n\treturn sql`${column} not in ${bindIfParam(values, column)}`;\n}\n/**\n* Test whether an expression is NULL. By the SQL standard,\n* NULL is neither equal nor not equal to itself, so\n* it's recommended to use `isNull` and `notIsNull` for\n* comparisons to NULL.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars that have no discontinuedAt date.\n* db.select().from(cars)\n* .where(isNull(cars.discontinuedAt))\n* ```\n*\n* @see isNotNull for the inverse of this test\n*/\nfunction isNull(value) {\n\treturn sql`(${value} is null)`;\n}\n/**\n* Test whether an expression is not NULL. By the SQL standard,\n* NULL is neither equal nor not equal to itself, so\n* it's recommended to use `isNull` and `notIsNull` for\n* comparisons to NULL.\n*\n* ## Examples\n*\n* ```ts\n* // Select cars that have been discontinued.\n* db.select().from(cars)\n* .where(isNotNull(cars.discontinuedAt))\n* ```\n*\n* @see isNull for the inverse of this test\n*/\nfunction isNotNull(value) {\n\treturn sql`(${value} is not null)`;\n}\n/**\n* Test whether a subquery evaluates to have any rows.\n*\n* ## Examples\n*\n* ```ts\n* // Users whose `homeCity` column has a match in a cities\n* // table.\n* db\n* .select()\n* .from(users)\n* .where(\n* exists(db.select()\n* .from(cities)\n* .where(eq(users.homeCity, cities.id))),\n* );\n* ```\n*\n* @see notExists for the inverse of this test\n*/\nfunction exists(subquery) {\n\treturn sql`exists ${subquery}`;\n}\n/**\n* Test whether a subquery doesn't include any result\n* rows.\n*\n* ## Examples\n*\n* ```ts\n* // Users whose `homeCity` column doesn't match\n* // a row in the cities table.\n* db\n* .select()\n* .from(users)\n* .where(\n* notExists(db.select()\n* .from(cities)\n* .where(eq(users.homeCity, cities.id))),\n* );\n* ```\n*\n* @see exists for the inverse of this test\n*/\nfunction notExists(subquery) {\n\treturn sql`not exists ${subquery}`;\n}\nfunction between(column, min, max) {\n\treturn sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;\n}\nfunction notBetween(column, min, max) {\n\treturn sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`;\n}\n/**\n* Compare a column to a pattern, which can include `%` and `_`\n* characters to match multiple variations. Including `%`\n* in the pattern matches zero or more characters, and including\n* `_` will match a single character.\n*\n* ## Examples\n*\n* ```ts\n* // Select all cars with 'Turbo' in their names.\n* db.select().from(cars)\n* .where(like(cars.name, '%Turbo%'))\n* ```\n*\n* @see ilike for a case-insensitive version of this condition\n*/\nfunction like(column, value) {\n\treturn sql`${column} like ${value}`;\n}\n/**\n* The inverse of like - this tests that a given column\n* does not match a pattern, which can include `%` and `_`\n* characters to match multiple variations. Including `%`\n* in the pattern matches zero or more characters, and including\n* `_` will match a single character.\n*\n* ## Examples\n*\n* ```ts\n* // Select all cars that don't have \"ROver\" in their name.\n* db.select().from(cars)\n* .where(notLike(cars.name, '%Rover%'))\n* ```\n*\n* @see like for the inverse condition\n* @see notIlike for a case-insensitive version of this condition\n*/\nfunction notLike(column, value) {\n\treturn sql`${column} not like ${value}`;\n}\n/**\n* Case-insensitively compare a column to a pattern,\n* which can include `%` and `_`\n* characters to match multiple variations. Including `%`\n* in the pattern matches zero or more characters, and including\n* `_` will match a single character.\n*\n* Unlike like, this performs a case-insensitive comparison.\n*\n* ## Examples\n*\n* ```ts\n* // Select all cars with 'Turbo' in their names.\n* db.select().from(cars)\n* .where(ilike(cars.name, '%Turbo%'))\n* ```\n*\n* @see like for a case-sensitive version of this condition\n*/\nfunction ilike(column, value) {\n\treturn sql`${column} ilike ${value}`;\n}\n/**\n* The inverse of ilike - this case-insensitively tests that a given column\n* does not match a pattern, which can include `%` and `_`\n* characters to match multiple variations. Including `%`\n* in the pattern matches zero or more characters, and including\n* `_` will match a single character.\n*\n* ## Examples\n*\n* ```ts\n* // Select all cars that don't have \"Rover\" in their name.\n* db.select().from(cars)\n* .where(notLike(cars.name, '%Rover%'))\n* ```\n*\n* @see ilike for the inverse condition\n* @see notLike for a case-sensitive version of this condition\n*/\nfunction notIlike(column, value) {\n\treturn sql`${column} not ilike ${value}`;\n}\nfunction arrayContains(column, values) {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) throw new Error(\"arrayContains requires at least one value\");\n\t\tconst par = bindIfParam(values, column);\n\t\treturn sql`${column} @> ${sql`${Array.isArray(par) ? new Param(par) : par}`}`;\n\t}\n\treturn sql`${column} @> ${bindIfParam(values, column)}`;\n}\nfunction arrayContained(column, values) {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) throw new Error(\"arrayContained requires at least one value\");\n\t\tconst par = bindIfParam(values, column);\n\t\treturn sql`${column} <@ ${sql`${Array.isArray(par) ? new Param(par) : par}`}`;\n\t}\n\treturn sql`${column} <@ ${bindIfParam(values, column)}`;\n}\nfunction arrayOverlaps(column, values) {\n\tif (Array.isArray(values)) {\n\t\tif (values.length === 0) throw new Error(\"arrayOverlaps requires at least one value\");\n\t\tconst par = bindIfParam(values, column);\n\t\treturn sql`${column} && ${sql`${Array.isArray(par) ? new Param(par) : par}`}`;\n\t}\n\treturn sql`${column} && ${bindIfParam(values, column)}`;\n}\n\n//#endregion\nexport { and, arrayContained, arrayContains, arrayOverlaps, between, bindIfParam, eq, exists, gt, gte, ilike, inArray, isNotNull, isNull, like, lt, lte, ne, not, notBetween, notExists, notIlike, notInArray, notLike, or };\n//# sourceMappingURL=conditions.js.map",
78
+ "import { sql } from \"../sql.js\";\n\n//#region src/sql/expressions/select.ts\n/**\n* Used in sorting, this specifies that the given\n* column or expression should be sorted in ascending\n* order. By the SQL standard, ascending order is the\n* default, so it is not usually necessary to specify\n* ascending sort order.\n*\n* ## Examples\n*\n* ```ts\n* // Return cars, starting with the oldest models\n* // and going in ascending order to the newest.\n* db.select().from(cars)\n* .orderBy(asc(cars.year));\n* ```\n*\n* @see desc to sort in descending order\n*/\nfunction asc(column) {\n\treturn sql`${column} asc`;\n}\n/**\n* Used in sorting, this specifies that the given\n* column or expression should be sorted in descending\n* order.\n*\n* ## Examples\n*\n* ```ts\n* // Select users, with the most recently created\n* // records coming first.\n* db.select().from(users)\n* .orderBy(desc(users.createdAt));\n* ```\n*\n* @see asc to sort in ascending order\n*/\nfunction desc(column) {\n\treturn sql`${column} desc`;\n}\n\n//#endregion\nexport { asc, desc };\n//# sourceMappingURL=select.js.map",
79
+ "import { entityKind, is } from \"./entity.js\";\nimport { Column } from \"./column.js\";\nimport { Placeholder, SQL, View, noopDecoder, sql } from \"./sql/sql.js\";\nimport { DrizzleError } from \"./errors.js\";\nimport { and, arrayContained, arrayContains, arrayOverlaps, between, eq, exists, gt, gte, ilike, inArray, isNotNull, isNull, like, lt, lte, ne, not, notBetween, notExists, notIlike, notInArray, notLike, or } from \"./sql/expressions/conditions.js\";\nimport { asc, desc } from \"./sql/expressions/select.js\";\nimport { aliasedTable } from \"./alias.js\";\nimport { FnConstructor, getColumnFromDecoder } from \"./utils.js\";\nimport { IsAlias, OriginalName, Table, TableColumns, TableSchema } from \"./table.js\";\n\n//#region src/relations.ts\nfunction processRelations(tablesConfig, tables) {\n\tfor (const tableConfig of Object.values(tablesConfig)) for (const [relationFieldName, relation] of Object.entries(tableConfig.relations)) {\n\t\tif (!is(relation, Relation)) continue;\n\t\trelation.sourceTable = tableConfig.table;\n\t\trelation.fieldName = relationFieldName;\n\t}\n\tfor (const [sourceTableName, tableConfig] of Object.entries(tablesConfig)) for (const [relationFieldName, relation] of Object.entries(tableConfig.relations)) {\n\t\tif (!is(relation, Relation)) continue;\n\t\tlet reverseRelation;\n\t\tconst { targetTableName, alias, sourceColumns, targetColumns, throughTable, sourceTable, through, where, sourceColumnTableNames, targetColumnTableNames } = relation;\n\t\tconst relationPrintName = `relations -> ${tableConfig.name}: { ${relationFieldName}: r.${is(relation, One) ? \"one\" : \"many\"}.${targetTableName}(...) }`;\n\t\tif (relationFieldName in tableConfig.table[TableColumns]) throw new Error(`${relationPrintName}: relation name collides with column \"${relationFieldName}\" of table \"${tableConfig.name}\"`);\n\t\tif (typeof alias === \"string\" && !alias) throw new Error(`${relationPrintName}: \"alias\" cannot be an empty string - omit it if you don't need it`);\n\t\tif (sourceColumns?.length === 0) throw new Error(`${relationPrintName}: \"from\" cannot be empty`);\n\t\tif (targetColumns?.length === 0) throw new Error(`${relationPrintName}: \"to\" cannot be empty`);\n\t\tif (sourceColumns && targetColumns) {\n\t\t\tif (sourceColumns.length !== targetColumns.length && !throughTable) throw new Error(`${relationPrintName}: \"from\" and \"to\" fields without \"through\" must have the same length`);\n\t\t\tfor (const sName of sourceColumnTableNames) if (sName !== sourceTableName) throw new Error(`${relationPrintName}: all \"from\" columns must belong to table \"${sourceTableName}\", found column of table \"${sName}\"`);\n\t\t\tfor (const tName of targetColumnTableNames) if (tName !== targetTableName) throw new Error(`${relationPrintName}: all \"to\" columns must belong to table \"${targetTableName}\", found column of table \"${tName}\"`);\n\t\t\tif (through) {\n\t\t\t\tif (through.source.length !== sourceColumns.length || through.target.length !== targetColumns.length) throw new Error(`${relationPrintName}: \".through(column)\" must be used either on all columns in \"from\" and \"to\" or not defined on any of them`);\n\t\t\t\tfor (const column of through.source) if (tables[column._.tableName] !== throughTable) throw new Error(`${relationPrintName}: \".through(column)\" must be used on the same table by all columns of the relation`);\n\t\t\t\tfor (const column of through.target) if (tables[column._.tableName] !== throughTable) throw new Error(`${relationPrintName}: \".through(column)\" must be used on the same table by all columns of the relation`);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (sourceColumns || targetColumns) throw new Error(`${relationPrintName}: relation must have either both \"from\" and \"to\" defined, or none of them`);\n\t\tconst reverseTableConfig = tablesConfig[targetTableName];\n\t\tif (!reverseTableConfig) throw new Error(`${relationPrintName}: not enough data provided to build the relation - \"from\"/\"to\" are not defined, and no reverse relations of table \"${targetTableName}\" were found\"`);\n\t\tif (alias) {\n\t\t\tconst reverseRelations = Object.values(reverseTableConfig.relations).filter((it) => is(it, Relation) && it.alias === alias && it !== relation);\n\t\t\tif (reverseRelations.length > 1) throw new Error(`${relationPrintName}: not enough data provided to build the relation - \"from\"/\"to\" are not defined, and multiple relations with alias \"${alias}\" found in table \"${targetTableName}\": ${reverseRelations.map((it) => `\"${it.fieldName}\"`).join(\", \")}`);\n\t\t\treverseRelation = reverseRelations[0];\n\t\t\tif (!reverseRelation) throw new Error(`${relationPrintName}: not enough data provided to build the relation - \"from\"/\"to\" are not defined, and there is no reverse relation of table \"${targetTableName}\" with alias \"${alias}\"`);\n\t\t} else {\n\t\t\tconst reverseRelations = Object.values(reverseTableConfig.relations).filter((it) => is(it, Relation) && it.targetTable === sourceTable && !it.alias && it !== relation);\n\t\t\tif (reverseRelations.length > 1) throw new Error(`${relationPrintName}: not enough data provided to build the relation - \"from\"/\"to\" are not defined, and multiple relations between \"${targetTableName}\" and \"${sourceTableName}\" were found.\\nHint: you can specify \"alias\" on both sides of the relation with the same value`);\n\t\t\treverseRelation = reverseRelations[0];\n\t\t\tif (!reverseRelation) throw new Error(`${relationPrintName}: not enough data provided to build the relation - \"from\"/\"to\" are not defined, and no reverse relation of table \"${targetTableName}\" with target table \"${sourceTableName}\" was found`);\n\t\t}\n\t\tif (!reverseRelation.sourceColumns || !reverseRelation.targetColumns) throw new Error(`${relationPrintName}: not enough data provided to build the relation - \"from\"/\"to\" are not defined, and reverse relation \"${targetTableName}.${reverseRelation.fieldName}\" does not have \"from\"/\"to\" defined`);\n\t\trelation.sourceColumns = reverseRelation.targetColumns;\n\t\trelation.targetColumns = reverseRelation.sourceColumns;\n\t\trelation.through = reverseRelation.through ? {\n\t\t\tsource: reverseRelation.through.target,\n\t\t\ttarget: reverseRelation.through.source\n\t\t} : void 0;\n\t\trelation.throughTable = reverseRelation.throughTable;\n\t\trelation.isReversed = !where;\n\t\trelation.where = where ?? reverseRelation.where;\n\t}\n\treturn tablesConfig;\n}\n/** Builds relational config for every table in schema */\nfunction buildRelations(tables, config) {\n\tconst tablesConfig = {};\n\tfor (const [tsName, table] of Object.entries(tables)) tablesConfig[tsName] = {\n\t\ttable,\n\t\tname: tsName,\n\t\trelations: config[tsName] ?? {}\n\t};\n\treturn processRelations(tablesConfig, tables);\n}\n/** Builds relational config only for tables present in relational config */\nfunction buildRelationsParts(tables, config) {\n\tconst tablesConfig = {};\n\tfor (const [tsName, relations] of Object.entries(config)) {\n\t\tif (!relations || !tables[tsName]) continue;\n\t\ttablesConfig[tsName] = {\n\t\t\ttable: tables[tsName],\n\t\t\tname: tsName,\n\t\t\trelations\n\t\t};\n\t}\n\treturn processRelations(tablesConfig, tables);\n}\nvar Relation = class {\n\tstatic [entityKind] = \"RelationV2\";\n\tfieldName;\n\tsourceColumns;\n\ttargetColumns;\n\talias;\n\twhere;\n\tsourceTable;\n\ttargetTable;\n\tthrough;\n\tthroughTable;\n\tisReversed;\n\t/** @internal */\n\tsourceColumnTableNames = [];\n\t/** @internal */\n\ttargetColumnTableNames = [];\n\tconstructor(targetTable, targetTableName) {\n\t\tthis.targetTableName = targetTableName;\n\t\tthis.targetTable = targetTable;\n\t}\n};\nvar One = class extends Relation {\n\tstatic [entityKind] = \"OneV2\";\n\trelationType = \"one\";\n\toptional;\n\tconstructor(tables, targetTable, targetTableName, config) {\n\t\tsuper(targetTable, targetTableName);\n\t\tthis.alias = config?.alias;\n\t\tthis.where = config?.where;\n\t\tif (config?.from) this.sourceColumns = (Array.isArray(config.from) ? config.from : [config.from]).map((it) => {\n\t\t\tthis.throughTable ??= it._.through ? tables[it._.through._.tableName] : void 0;\n\t\t\tthis.sourceColumnTableNames.push(it._.tableName);\n\t\t\treturn it._.column;\n\t\t});\n\t\tif (config?.to) this.targetColumns = (Array.isArray(config.to) ? config.to : [config.to]).map((it) => {\n\t\t\tthis.throughTable ??= it._.through ? tables[it._.through._.tableName] : void 0;\n\t\t\tthis.targetColumnTableNames.push(it._.tableName);\n\t\t\treturn it._.column;\n\t\t});\n\t\tif (this.throughTable) this.through = {\n\t\t\tsource: (Array.isArray(config?.from) ? config.from : config?.from ? [config.from] : []).map((c) => c._.through),\n\t\t\ttarget: (Array.isArray(config?.to) ? config.to : config?.to ? [config.to] : []).map((c) => c._.through)\n\t\t};\n\t\tthis.optional = config?.optional ?? true;\n\t}\n};\nvar Many = class extends Relation {\n\tstatic [entityKind] = \"ManyV2\";\n\trelationType = \"many\";\n\tconstructor(tables, targetTable, targetTableName, config) {\n\t\tsuper(targetTable, targetTableName);\n\t\tthis.config = config;\n\t\tthis.alias = config?.alias;\n\t\tthis.where = config?.where;\n\t\tif (config?.from) this.sourceColumns = (Array.isArray(config.from) ? config.from : [config.from]).map((it) => {\n\t\t\tthis.throughTable ??= it._.through ? tables[it._.through._.tableName] : void 0;\n\t\t\tthis.sourceColumnTableNames.push(it._.tableName);\n\t\t\treturn it._.column;\n\t\t});\n\t\tif (config?.to) this.targetColumns = (Array.isArray(config.to) ? config.to : [config.to]).map((it) => {\n\t\t\tthis.throughTable ??= it._.through ? tables[it._.through._.tableName] : void 0;\n\t\t\tthis.targetColumnTableNames.push(it._.tableName);\n\t\t\treturn it._.column;\n\t\t});\n\t\tif (this.throughTable) this.through = {\n\t\t\tsource: (Array.isArray(config?.from) ? config.from : config?.from ? [config.from] : []).map((c) => c._.through),\n\t\t\ttarget: (Array.isArray(config?.to) ? config.to : config?.to ? [config.to] : []).map((c) => c._.through)\n\t\t};\n\t}\n};\nvar AggregatedField = class {\n\tstatic [entityKind] = \"AggregatedField\";\n\ttable;\n\tonTable(table) {\n\t\tthis.table = table;\n\t\treturn this;\n\t}\n};\nvar Count = class extends AggregatedField {\n\tstatic [entityKind] = \"AggregatedFieldCount\";\n\tquery;\n\tgetSQL() {\n\t\tif (!this.query) {\n\t\t\tif (!this.table) throw new Error(\"Table must be set before building aggregate field\");\n\t\t\tthis.query = sql`select count(*) as ${sql.identifier(\"r\")} from ${getTableAsAliasSQL(this.table)}`.mapWith(Number);\n\t\t}\n\t\treturn this.query;\n\t}\n};\nconst operators = {\n\tand,\n\tbetween,\n\teq,\n\texists,\n\tgt,\n\tgte,\n\tilike,\n\tinArray,\n\tarrayContains,\n\tarrayContained,\n\tarrayOverlaps,\n\tisNull,\n\tisNotNull,\n\tlike,\n\tlt,\n\tlte,\n\tne,\n\tnot,\n\tnotBetween,\n\tnotExists,\n\tnotLike,\n\tnotIlike,\n\tnotInArray,\n\tor,\n\tsql\n};\nconst orderByOperators = {\n\tsql,\n\tasc,\n\tdesc\n};\nfunction getOrderByOperators() {\n\treturn orderByOperators;\n}\nfunction mapRelationalRow(rows, isOne, buildQueryResultSelection, parseJson = false, parseJsonIfString = false, useJsonMappers = true) {\n\tconst maxIdx = isOne ? 1 : rows.length;\n\tconst decoders = buildQueryResultSelection.map(({ field, codec, arrayDimensions }) => {\n\t\tlet decoder;\n\t\tif (is(field, Column)) decoder = field;\n\t\telse if (is(field, SQL)) decoder = field.decoder;\n\t\telse if (is(field, SQL.Aliased)) decoder = field.sql.decoder;\n\t\telse if (is(field, Table) || is(field, View)) decoder = noopDecoder;\n\t\telse decoder = field.getSQL().decoder;\n\t\tif (useJsonMappers && field.mapFromJsonValue) return (v) => field.mapFromJsonValue(v);\n\t\treturn decoder.mapFromDriverValue.isNoop ? codec ? (value) => codec(value, arrayDimensions) : void 0 : codec ? (value) => decoder.mapFromDriverValue(codec(value, arrayDimensions)) : (value) => decoder.mapFromDriverValue(value);\n\t});\n\tfor (let i = 0; i < maxIdx; ++i) {\n\t\tconst row = isOne ? rows : rows[i];\n\t\tfor (let selectionItemIdx = 0; selectionItemIdx < buildQueryResultSelection.length; ++selectionItemIdx) {\n\t\t\tconst selectionItem = buildQueryResultSelection[selectionItemIdx];\n\t\t\tif (selectionItem.selection) {\n\t\t\t\tif (row[selectionItem.key] === null) continue;\n\t\t\t\tif (parseJson) {\n\t\t\t\t\trow[selectionItem.key] = JSON.parse(row[selectionItem.key]);\n\t\t\t\t\tif (row[selectionItem.key] === null) continue;\n\t\t\t\t} else if (parseJsonIfString && typeof row[selectionItem.key] === \"string\") row[selectionItem.key] = JSON.parse(row[selectionItem.key]);\n\t\t\t\tif (selectionItem.isArray) {\n\t\t\t\t\tmapRelationalRow(row[selectionItem.key], false, selectionItem.selection, false, parseJsonIfString);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tmapRelationalRow(row[selectionItem.key], true, selectionItem.selection, false, parseJsonIfString);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (row[selectionItem.key] === null) continue;\n\t\t\tconst decoder = decoders[selectionItemIdx];\n\t\t\tif (!decoder) continue;\n\t\t\trow[selectionItem.key] = decoder(row[selectionItem.key]);\n\t\t}\n\t}\n\treturn rows;\n}\nfunction mapRelationalRowFromArrays(rows, isOne, buildQueryResultSelection, parseJson = false, parseJsonIfString = false) {\n\tconst maxIdx = isOne ? 1 : rows.length;\n\tconst decoders = buildQueryResultSelection.map(({ field, codec, arrayDimensions }) => {\n\t\tlet decoder;\n\t\tif (is(field, Column)) decoder = field;\n\t\telse if (is(field, SQL)) decoder = field.decoder;\n\t\telse if (is(field, SQL.Aliased)) decoder = field.sql.decoder;\n\t\telse if (is(field, Table) || is(field, View)) decoder = noopDecoder;\n\t\telse decoder = field.getSQL().decoder;\n\t\treturn decoder.mapFromDriverValue.isNoop ? codec ? (value) => codec(value, arrayDimensions) : void 0 : codec ? (value) => decoder.mapFromDriverValue(codec(value, arrayDimensions)) : (value) => decoder.mapFromDriverValue(value);\n\t});\n\tconst results = Array.from({ length: maxIdx });\n\tfor (let i = 0; i < maxIdx; ++i) {\n\t\tconst row = isOne ? rows : rows[i];\n\t\tconst result = {};\n\t\tfor (let selectionItemIdx = 0; selectionItemIdx < buildQueryResultSelection.length; ++selectionItemIdx) {\n\t\t\tconst selectionItem = buildQueryResultSelection[selectionItemIdx];\n\t\t\tlet value = row[selectionItemIdx];\n\t\t\tif (selectionItem.selection) {\n\t\t\t\tif (value === null) {\n\t\t\t\t\tresult[selectionItem.key] = null;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (parseJson) {\n\t\t\t\t\tvalue = JSON.parse(value);\n\t\t\t\t\tif (value === null) {\n\t\t\t\t\t\tresult[selectionItem.key] = null;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t} else if (parseJsonIfString && typeof value === \"string\") value = JSON.parse(value);\n\t\t\t\tif (selectionItem.isArray) mapRelationalRow(value, false, selectionItem.selection, false, parseJsonIfString);\n\t\t\t\telse mapRelationalRow(value, true, selectionItem.selection, false, parseJsonIfString);\n\t\t\t\tresult[selectionItem.key] = value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (value === null) {\n\t\t\t\tresult[selectionItem.key] = null;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst decoder = decoders[selectionItemIdx];\n\t\t\tresult[selectionItem.key] = decoder ? decoder(value) : value;\n\t\t}\n\t\tresults[i] = result;\n\t}\n\treturn isOne ? results[0] : results;\n}\nfunction makeDefaultRqbMapper({ selection, isFirst, parseJson, parseJsonIfString, rootJsonMappers, arrayModeRoot }) {\n\treturn ((rows) => {\n\t\tif (isFirst && !rows[0]) return rows[0];\n\t\treturn arrayModeRoot ? mapRelationalRowFromArrays(isFirst ? rows[0] : rows, isFirst, selection, parseJson, parseJsonIfString) : mapRelationalRow(isFirst ? rows[0] : rows, isFirst, selection, parseJson, parseJsonIfString, rootJsonMappers);\n\t});\n}\nfunction makeJitRqbMapperInner(selection, rowExpr, selectionVar, parseJson, parseJsonIfString, useJsonMappers, preFn, counter, accessByIdx) {\n\tconst bodyStmts = [];\n\tconst literalEntries = [];\n\tlet hasWork = false;\n\tconst fieldVars = selection.map(() => `c${counter.n++}`);\n\tconst destructurePieces = selection.map((item, idx) => accessByIdx ? fieldVars[idx] : `${JSON.stringify(item.key)}: ${fieldVars[idx]}`);\n\tbodyStmts.push(accessByIdx ? `let [ ${destructurePieces.join(\", \")} ] = ${rowExpr};` : `let { ${destructurePieces.join(\", \")} } = ${rowExpr};`);\n\tfor (const [idx, { field, key, codec, isArray, selection: innerSelection, arrayDimensions }] of selection.entries()) {\n\t\tconst sel = `${selectionVar}[${idx}]`;\n\t\tconst keyStr = JSON.stringify(key);\n\t\tconst slot = fieldVars[idx];\n\t\tif (innerSelection) {\n\t\t\tif (parseJson) {\n\t\t\t\tbodyStmts.push(`if (${slot} !== null) ${slot} = JSON.parse(${slot});`);\n\t\t\t\thasWork = true;\n\t\t\t} else if (parseJsonIfString) {\n\t\t\t\tbodyStmts.push(`if (typeof ${slot} === 'string') ${slot} = JSON.parse(${slot});`);\n\t\t\t\thasWork = true;\n\t\t\t}\n\t\t\tconst nestedSelVar = `s${counter.n++}`;\n\t\t\tconst savedPreFnLen = preFn.length;\n\t\t\tpreFn.push(`const { selection: ${nestedSelVar} } = ${sel};`);\n\t\t\tif (isArray) {\n\t\t\t\tconst j = `j${counter.n++}`;\n\t\t\t\tconst inner = makeJitRqbMapperInner(innerSelection, `${slot}[${j}]`, nestedSelVar, false, parseJsonIfString, true, preFn, counter, false);\n\t\t\t\tif (inner.hasWork) {\n\t\t\t\t\thasWork = true;\n\t\t\t\t\tbodyStmts.push(`if (${slot} !== null) {`);\n\t\t\t\t\tbodyStmts.push(`\\tfor (let ${j} = 0; ${j} < ${slot}.length; ++${j}) {`);\n\t\t\t\t\tfor (const s of inner.bodyStmts) bodyStmts.push(`\\t\\t${s}`);\n\t\t\t\t\tbodyStmts.push(`\\t\\t${slot}[${j}] = ${inner.literal};`);\n\t\t\t\t\tbodyStmts.push(`\\t}`);\n\t\t\t\t\tbodyStmts.push(`}`);\n\t\t\t\t} else preFn.splice(savedPreFnLen, 1);\n\t\t\t} else {\n\t\t\t\tconst inner = makeJitRqbMapperInner(innerSelection, slot, nestedSelVar, false, parseJsonIfString, true, preFn, counter, false);\n\t\t\t\tif (inner.hasWork) {\n\t\t\t\t\thasWork = true;\n\t\t\t\t\tbodyStmts.push(`if (${slot} !== null) {`);\n\t\t\t\t\tfor (const s of inner.bodyStmts) bodyStmts.push(`\\t${s}`);\n\t\t\t\t\tbodyStmts.push(`\\t${slot} = ${inner.literal};`);\n\t\t\t\t\tbodyStmts.push(`}`);\n\t\t\t\t} else preFn.splice(savedPreFnLen, 1);\n\t\t\t}\n\t\t\tliteralEntries.push(`${keyStr}: ${slot}`);\n\t\t\tcontinue;\n\t\t}\n\t\tlet decoderExpr = \"\";\n\t\tlet destructure = \"\";\n\t\tlet bypassCodecs = false;\n\t\tif (is(field, Column)) {\n\t\t\tif (useJsonMappers && field.mapFromJsonValue) {\n\t\t\t\tbypassCodecs = true;\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tdestructure = `field: dec${id}`;\n\t\t\t\tdecoderExpr = `dec${id}.mapFromJsonValue`;\n\t\t\t} else if (!field.mapFromDriverValue.isNoop) {\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tdestructure = `field: dec${id}`;\n\t\t\t\tdecoderExpr = `dec${id}.mapFromDriverValue`;\n\t\t\t}\n\t\t} else if (is(field, SQL)) {\n\t\t\tif (useJsonMappers && field.decoder.mapFromJsonValue) {\n\t\t\t\tbypassCodecs = true;\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tdestructure = `field: { decoder: dec${id} }`;\n\t\t\t\tdecoderExpr = `dec${id}.mapFromJsonValue`;\n\t\t\t} else if (!field.decoder.mapFromDriverValue.isNoop) {\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tdestructure = `field: { decoder: dec${id} }`;\n\t\t\t\tdecoderExpr = `dec${id}.mapFromDriverValue`;\n\t\t\t}\n\t\t} else if (is(field, SQL.Aliased)) {\n\t\t\tif (useJsonMappers && field.sql.decoder.mapFromJsonValue) {\n\t\t\t\tbypassCodecs = true;\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tdestructure = `field: { sql: { decoder: dec${id} } }`;\n\t\t\t\tdecoderExpr = `dec${id}.mapFromJsonValue`;\n\t\t\t} else if (!field.sql.decoder.mapFromDriverValue.isNoop) {\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tdestructure = `field: { sql: { decoder: dec${id} } }`;\n\t\t\t\tdecoderExpr = `dec${id}.mapFromDriverValue`;\n\t\t\t}\n\t\t} else if (is(field, Table) || is(field, View)) {} else {\n\t\t\tconst sqlExpr = field.getSQL();\n\t\t\tif (useJsonMappers && sqlExpr.decoder.mapFromJsonValue) {\n\t\t\t\tbypassCodecs = true;\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tpreFn.push(`const dec${id} = ${sel}.field.getSQL().decoder;`);\n\t\t\t\tdecoderExpr = `dec${id}.mapFromJsonValue`;\n\t\t\t} else if (!sqlExpr.decoder.mapFromDriverValue.isNoop) {\n\t\t\t\tconst id = counter.n++;\n\t\t\t\tpreFn.push(`const dec${id} = ${sel}.field.getSQL().decoder;`);\n\t\t\t\tdecoderExpr = `dec${id}.mapFromDriverValue`;\n\t\t\t}\n\t\t}\n\t\tlet codecVar = \"\";\n\t\tif (!bypassCodecs && codec) codecVar = `codec${counter.n++}`;\n\t\tif (destructure || codecVar) {\n\t\t\tconst parts = [];\n\t\t\tif (destructure) parts.push(destructure);\n\t\t\tif (codecVar) parts.push(`codec: ${codecVar}`);\n\t\t\tpreFn.push(`const { ${parts.join(\", \")} } = ${sel};`);\n\t\t}\n\t\tif (decoderExpr || codecVar) {\n\t\t\thasWork = true;\n\t\t\tlet decoded = slot;\n\t\t\tif (codecVar) decoded = `${codecVar}(${decoded}, ${arrayDimensions})`;\n\t\t\tif (decoderExpr) decoded = `${decoderExpr}(${decoded})`;\n\t\t\tliteralEntries.push(`${keyStr}: ${slot} === null ? null : ${decoded}`);\n\t\t} else literalEntries.push(`${keyStr}: ${slot}`);\n\t}\n\treturn {\n\t\tbodyStmts,\n\t\tliteral: `{ ${literalEntries.join(\", \")} }`,\n\t\thasWork\n\t};\n}\nfunction makeJitRqbMapper({ selection, isFirst, parseJson, parseJsonIfString, rootJsonMappers, arrayModeRoot }) {\n\tconst preFn = [];\n\tconst inner = makeJitRqbMapperInner(selection, \"row\", \"selection\", parseJson, parseJsonIfString, arrayModeRoot ? false : rootJsonMappers, preFn, { n: 0 }, !!arrayModeRoot);\n\tconst lines = [];\n\tlines.push(`\\t\"use strict\";\n\tconst { selection } = this;`);\n\tfor (const p of preFn) lines.push(`\\t${p}`);\n\tif (arrayModeRoot) if (isFirst) {\n\t\tlines.push(`\\tconst row = rows[0];`);\n\t\tlines.push(`\\tif (!row) return undefined;`);\n\t\tfor (const s of inner.bodyStmts) lines.push(`\\t${s}`);\n\t\tlines.push(`\\treturn ${inner.literal};`);\n\t} else {\n\t\tlines.push(`\\tconst { length } = rows;`);\n\t\tlines.push(`\\tconst mapped = Array.from({ length });`);\n\t\tlines.push(`\\tfor (let i = 0; i < length; ++i) {`);\n\t\tlines.push(`\\t\\tconst row = rows[i];`);\n\t\tfor (const s of inner.bodyStmts) lines.push(`\\t\\t${s}`);\n\t\tlines.push(`\\t\\tmapped[i] = ${inner.literal};`);\n\t\tlines.push(`\\t}`);\n\t\tlines.push(`\\treturn mapped;`);\n\t}\n\telse if (!inner.hasWork) lines.push(isFirst ? `\\treturn rows[0];` : `\\treturn rows;`);\n\telse if (isFirst) {\n\t\tlines.push(`\\tconst row = rows[0];`);\n\t\tlines.push(`\\tif (!row) return undefined;`);\n\t\tfor (const s of inner.bodyStmts) lines.push(`\\t${s}`);\n\t\tlines.push(`\\trows[0] = ${inner.literal};`);\n\t\tlines.push(`\\treturn rows[0];`);\n\t} else {\n\t\tlines.push(`\\tfor (let i = 0; i < rows.length; ++i) {`);\n\t\tlines.push(`\\t\\tconst row = rows[i];`);\n\t\tfor (const s of inner.bodyStmts) lines.push(`\\t\\t${s}`);\n\t\tlines.push(`\\t\\trows[i] = ${inner.literal};`);\n\t\tlines.push(`\\t}`);\n\t\tlines.push(`\\treturn rows;`);\n\t}\n\tlines.push(\"\t//# sourceURL=drizzle:jit-relational-query-mapper\");\n\tconst compiled = lines.join(\"\\n\");\n\treturn Object.assign(new FnConstructor(\"rows\", compiled).bind({ selection }), { body: `function jitRqbMapper (rows) {\\n${compiled}\\n}` });\n}\nvar RelationsBuilderTable = class {\n\tstatic [entityKind] = \"RelationsBuilderTable\";\n\t_;\n\tconstructor(table, name) {\n\t\tthis._ = {\n\t\t\tname,\n\t\t\ttable\n\t\t};\n\t}\n};\nvar RelationsBuilderColumn = class {\n\tstatic [entityKind] = \"RelationsBuilderColumn\";\n\t_;\n\tconstructor(column, tableName, key) {\n\t\tthis._ = {\n\t\t\ttableName,\n\t\t\tcolumn,\n\t\t\tkey\n\t\t};\n\t}\n\tthrough(column) {\n\t\treturn new RelationsBuilderJunctionColumn(this._.column, this._.tableName, this._.key, column);\n\t}\n};\nvar RelationsBuilderJunctionColumn = class {\n\tstatic [entityKind] = \"RelationsBuilderColumn\";\n\t_;\n\tconstructor(column, tableName, key, through) {\n\t\tthis._ = {\n\t\t\ttableName,\n\t\t\tcolumn,\n\t\t\tthrough,\n\t\t\tkey\n\t\t};\n\t}\n};\nvar RelationsHelperStatic = class {\n\tstatic [entityKind] = \"RelationsHelperStatic\";\n\t_;\n\tconstructor(tables) {\n\t\tthis._ = { tables };\n\t\tconst one = {};\n\t\tconst many = {};\n\t\tfor (const [tableName, table] of Object.entries(tables)) {\n\t\t\tone[tableName] = (config) => {\n\t\t\t\treturn new One(tables, table, tableName, config);\n\t\t\t};\n\t\t\tmany[tableName] = (config) => {\n\t\t\t\treturn new Many(tables, table, tableName, config);\n\t\t\t};\n\t\t}\n\t\tthis.one = one;\n\t\tthis.many = many;\n\t}\n\tone;\n\tmany;\n\t/** @internal - to be reworked */\n\taggs = { count() {\n\t\treturn new Count();\n\t} };\n};\nfunction createRelationsHelper(tables) {\n\tconst helperStatic = new RelationsHelperStatic(tables);\n\tconst relationsTables = Object.entries(tables).reduce((acc, [tKey, value]) => {\n\t\tconst rTable = new RelationsBuilderTable(value, tKey);\n\t\tconst columns = Object.entries(value[TableColumns]).reduce((acc, [cKey, column]) => {\n\t\t\tacc[cKey] = new RelationsBuilderColumn(column, tKey, cKey);\n\t\t\treturn acc;\n\t\t}, {});\n\t\tacc[tKey] = Object.assign(rTable, columns);\n\t\treturn acc;\n\t}, {});\n\treturn Object.assign(helperStatic, relationsTables);\n}\nfunction extractTablesFromSchema(schema) {\n\treturn Object.fromEntries(Object.entries(schema).filter(([_, e]) => is(e, Table) || is(e, View)));\n}\nfunction defineRelations(schema, relations) {\n\tconst tables = extractTablesFromSchema(schema);\n\treturn buildRelations(tables, relations ? relations(createRelationsHelper(tables)) : {});\n}\nfunction defineRelationsPart(schema, relations) {\n\tconst tables = extractTablesFromSchema(schema);\n\treturn buildRelationsParts(tables, relations ? relations(createRelationsHelper(tables)) : Object.fromEntries(Object.keys(tables).map((k) => [k, {}])));\n}\n/** @internal */\nfunction fieldSelectionToSQL(table, target) {\n\tconst field = table[TableColumns][target];\n\treturn field ? is(field, Column) ? field : is(field, SQL.Aliased) ? sql`${table}.${sql.identifier(field.fieldAlias)}` : sql`${table}.${sql.identifier(target)}` : sql`${table}.${sql.identifier(target)}`;\n}\nfunction relationsFieldFilterToSQL(column, filter) {\n\tif (typeof filter !== \"object\" || is(filter, Placeholder)) return eq(column, filter);\n\tconst entries = Object.entries(filter);\n\tif (!entries.length) return void 0;\n\tconst parts = [];\n\tfor (const [target, value] of entries) {\n\t\tif (value === void 0) continue;\n\t\tswitch (target) {\n\t\t\tcase \"NOT\": {\n\t\t\t\tconst res = relationsFieldFilterToSQL(column, value);\n\t\t\t\tif (!res) continue;\n\t\t\t\tparts.push(not(res));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcase \"OR\":\n\t\t\t\tif (!value.length) continue;\n\t\t\t\tparts.push(or(...value.map((subFilter) => relationsFieldFilterToSQL(column, subFilter))));\n\t\t\t\tcontinue;\n\t\t\tcase \"AND\":\n\t\t\t\tif (!value.length) continue;\n\t\t\t\tparts.push(and(...value.map((subFilter) => relationsFieldFilterToSQL(column, subFilter))));\n\t\t\t\tcontinue;\n\t\t\tcase \"isNotNull\":\n\t\t\tcase \"isNull\":\n\t\t\t\tif (!value) continue;\n\t\t\t\tparts.push(operators[target](column));\n\t\t\t\tcontinue;\n\t\t\tcase \"in\":\n\t\t\t\tparts.push(operators.inArray(column, value));\n\t\t\t\tcontinue;\n\t\t\tcase \"notIn\":\n\t\t\t\tparts.push(operators.notInArray(column, value));\n\t\t\t\tcontinue;\n\t\t\tdefault:\n\t\t\t\tparts.push(operators[target](column, value));\n\t\t\t\tcontinue;\n\t\t}\n\t}\n\tif (!parts.length) return void 0;\n\treturn and(...parts);\n}\nfunction relationsFilterToSQL(table, filter, tableRelations = {}, tablesRelations = {}, depth = 0) {\n\tconst entries = Object.entries(filter);\n\tif (!entries.length) return void 0;\n\tconst parts = [];\n\tfor (const [target, value] of entries) {\n\t\tif (value === void 0) continue;\n\t\tswitch (target) {\n\t\t\tcase \"RAW\": {\n\t\t\t\tconst processed = typeof value === \"function\" ? value(table, operators) : value.getSQL();\n\t\t\t\tparts.push(processed);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcase \"OR\":\n\t\t\t\tif (!value?.length) continue;\n\t\t\t\tparts.push(or(...value.map((subFilter) => relationsFilterToSQL(table, subFilter, tableRelations, tablesRelations, depth))));\n\t\t\t\tcontinue;\n\t\t\tcase \"AND\":\n\t\t\t\tif (!value?.length) continue;\n\t\t\t\tparts.push(and(...value.map((subFilter) => relationsFilterToSQL(table, subFilter, tableRelations, tablesRelations, depth))));\n\t\t\t\tcontinue;\n\t\t\tcase \"NOT\": {\n\t\t\t\tif (value === void 0) continue;\n\t\t\t\tconst built = relationsFilterToSQL(table, value, tableRelations, tablesRelations, depth);\n\t\t\t\tif (!built) continue;\n\t\t\t\tparts.push(not(built));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tif (table[TableColumns][target]) {\n\t\t\t\t\tconst colFilter = relationsFieldFilterToSQL(fieldSelectionToSQL(table, target), value);\n\t\t\t\t\tif (colFilter) parts.push(colFilter);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst relation = tableRelations[target];\n\t\t\t\tif (!relation) throw new DrizzleError({ message: `Unknown relational filter field: \"${target}\"` });\n\t\t\t\tconst targetTable = aliasedTable(relation.targetTable, `f${depth}`);\n\t\t\t\tconst throughTable = relation.throughTable ? aliasedTable(relation.throughTable, `ft${depth}`) : void 0;\n\t\t\t\tconst targetConfig = tablesRelations[relation.targetTableName];\n\t\t\t\tconst { filter: relationFilter, joinCondition } = relationToSQL(relation, table, targetTable, throughTable);\n\t\t\t\tconst filter = and(relationFilter, typeof value === \"boolean\" ? void 0 : relationsFilterToSQL(targetTable, value, targetConfig.relations, tablesRelations, depth + 1));\n\t\t\t\tconst subquery = throughTable ? sql`(select * from ${getTableAsAliasSQL(targetTable)} inner join ${getTableAsAliasSQL(throughTable)} on ${joinCondition}${sql` where ${filter}`.if(filter)} limit 1)` : sql`(select * from ${getTableAsAliasSQL(targetTable)}${sql` where ${filter}`.if(filter)} limit 1)`;\n\t\t\t\tif (filter) parts.push((value ? exists : notExists)(subquery));\n\t\t\t}\n\t\t}\n\t}\n\treturn and(...parts);\n}\nfunction relationsOrderToSQL(table, orders) {\n\tif (typeof orders === \"function\") {\n\t\tconst data = orders(table, orderByOperators);\n\t\treturn is(data, SQL) ? data : Array.isArray(data) ? data.length ? sql.join(data.map((o) => is(o, SQL) ? o : asc(o)), sql`, `) : void 0 : is(data, Column) ? asc(data) : void 0;\n\t}\n\tconst entries = Object.entries(orders).filter(([_, value]) => value);\n\tif (!entries.length) return void 0;\n\treturn sql.join(entries.map(([target, value]) => (value === \"asc\" ? asc : desc)(fieldSelectionToSQL(table, target))), sql`, `);\n}\nfunction relationExtrasToSQL(table, extras, codecs, inJson) {\n\tconst subqueries = [];\n\tconst selection = [];\n\tfor (const [key, field] of Object.entries(extras)) {\n\t\tif (!field) continue;\n\t\tconst subq = (typeof field === \"function\" ? field(table, { sql: operators.sql }) : field).getSQL();\n\t\tconst column = codecs ? getColumnFromDecoder(subq) : void 0;\n\t\tconst query = column && (!inJson || !column.jsonSelectIdentifier) ? sql`${codecs.apply(column, inJson ? \"castInJson\" : \"cast\", sql`(${subq})`)} as ${sql.identifier(key)}` : sql`(${subq}) as ${sql.identifier(key)}`;\n\t\tquery.decoder = subq.decoder;\n\t\tsubqueries.push(query);\n\t\tselection.push(column && (!inJson || !column.mapFromJsonValue) ? {\n\t\t\tkey,\n\t\t\tfield: query,\n\t\t\tcodec: codecs.get(column, inJson ? \"normalizeInJson\" : \"normalize\"),\n\t\t\tarrayDimensions: column.dimensions\n\t\t} : {\n\t\t\tkey,\n\t\t\tfield: query\n\t\t});\n\t}\n\treturn {\n\t\tsql: subqueries.length ? sql.join(subqueries, sql`, `) : void 0,\n\t\tselection\n\t};\n}\nfunction relationToSQL(relation, sourceTable, targetTable, throughTable) {\n\tif (relation.through) {\n\t\tconst outerColumnWhere = relation.sourceColumns.map((s, i) => {\n\t\t\tconst t = relation.through.source[i];\n\t\t\treturn eq(sql`${sourceTable}.${sql.identifier(s.name)}`, sql`${throughTable}.${sql.identifier(is(t._.column, Column) ? t._.column.name : t._.key)}`);\n\t\t});\n\t\tconst innerColumnWhere = relation.targetColumns.map((s, i) => {\n\t\t\tconst t = relation.through.target[i];\n\t\t\treturn eq(sql`${throughTable}.${sql.identifier(is(t._.column, Column) ? t._.column.name : t._.key)}`, sql`${targetTable}.${sql.identifier(s.name)}`);\n\t\t});\n\t\treturn {\n\t\t\tfilter: and(relation.where ? relationsFilterToSQL(relation.isReversed ? sourceTable : targetTable, relation.where) : void 0, ...outerColumnWhere),\n\t\t\tjoinCondition: and(...innerColumnWhere)\n\t\t};\n\t}\n\treturn { filter: and(...relation.sourceColumns.map((s, i) => {\n\t\tconst t = relation.targetColumns[i];\n\t\treturn eq(sql`${sourceTable}.${sql.identifier(s.name)}`, sql`${targetTable}.${sql.identifier(t.name)}`);\n\t}), relation.where ? relationsFilterToSQL(relation.isReversed ? sourceTable : targetTable, relation.where) : void 0) };\n}\nfunction getTableAsAliasSQL(table) {\n\treturn sql`${table[IsAlias] ? sql`${sql`${sql.identifier(table[TableSchema] ?? \"\")}.`.if(table[TableSchema])}${sql.identifier(table[OriginalName])} as ${table}` : table}`;\n}\n\n//#endregion\nexport { AggregatedField, Count, Many, One, Relation, RelationsBuilderColumn, RelationsBuilderJunctionColumn, RelationsBuilderTable, RelationsHelperStatic, buildRelations, buildRelationsParts, createRelationsHelper, defineRelations, defineRelationsPart, extractTablesFromSchema, fieldSelectionToSQL, getOrderByOperators, getTableAsAliasSQL, makeDefaultRqbMapper, makeJitRqbMapper, mapRelationalRow, mapRelationalRowFromArrays, operators, orderByOperators, processRelations, relationExtrasToSQL, relationToSQL, relationsFilterToSQL, relationsOrderToSQL };\n//# sourceMappingURL=relations.js.map",
80
+ "import { resolvePgTypeAlias, unionsTypeTable } from \"./codecs.js\";\nimport { PgViewBase } from \"./view-base.js\";\nimport { entityKind, is } from \"../entity.js\";\nimport { Subquery } from \"../subquery.js\";\nimport { ViewBaseConfig } from \"../view-common.js\";\nimport { Table, TableColumns, getTableName } from \"../table.js\";\nimport { getColumnFromDecoder, makeDefaultQueryMapper, makeJitQueryMapper, orderSelectedFields } from \"../utils.js\";\nimport { Column } from \"../column.js\";\nimport { CodecsCollection } from \"../codecs.js\";\nimport { Param, SQL, sql } from \"../sql/sql.js\";\nimport { aliasedTable, getOriginalColumnFromAlias } from \"../alias.js\";\nimport { DrizzleError } from \"../errors.js\";\nimport { View as View$1, and, isSQLWrapper as isSQLWrapper$1 } from \"../sql/index.js\";\nimport { One, getTableAsAliasSQL, makeDefaultRqbMapper, makeJitRqbMapper, relationExtrasToSQL, relationToSQL, relationsFilterToSQL, relationsOrderToSQL } from \"../relations.js\";\nimport { PgTable } from \"./table.js\";\nimport { PgColumn } from \"./columns/index.js\";\n\n//#region src/pg-core/dialect.ts\nvar PgDialect = class {\n\tstatic [entityKind] = \"PgDialect\";\n\tcodecs;\n\tmapperGenerators;\n\tconstructor(config) {\n\t\tthis.codecs = new CodecsCollection(resolvePgTypeAlias, config?.codecs);\n\t\tthis.mapperGenerators = config?.useJitMappers ? {\n\t\t\trows: makeJitQueryMapper,\n\t\t\trelationalRows: makeJitRqbMapper\n\t\t} : {\n\t\t\trows: makeDefaultQueryMapper,\n\t\t\trelationalRows: makeDefaultRqbMapper\n\t\t};\n\t}\n\tescapeName(name) {\n\t\treturn `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n\t}\n\tescapeParam(num) {\n\t\treturn `$${num + 1}`;\n\t}\n\tescapeString(str) {\n\t\treturn `'${str.replace(/'/g, \"''\")}'`;\n\t}\n\tbuildWithCTE(queries) {\n\t\tif (!queries?.length) return void 0;\n\t\tconst withSqlChunks = [sql`with `];\n\t\tfor (const [i, w] of queries.entries()) {\n\t\t\twithSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`);\n\t\t\tif (i < queries.length - 1) withSqlChunks.push(sql`, `);\n\t\t}\n\t\twithSqlChunks.push(sql` `);\n\t\treturn sql.join(withSqlChunks);\n\t}\n\tbuildDeleteQuery({ table, where, returning, withList, comment, ignoreSelectionCastCodecs }) {\n\t\tconst withSql = this.buildWithCTE(withList);\n\t\tconst returningSql = returning ? sql` returning ${this.buildSelection(returning, {\n\t\t\tisSingleTable: true,\n\t\t\tignoreCastCodecs: ignoreSelectionCastCodecs\n\t\t})}` : void 0;\n\t\treturn sql`${withSql}delete from ${table}${where ? sql` where ${where}` : void 0}${returningSql}${comment !== void 0 ? sql` ${comment}` : void 0}`;\n\t}\n\tbuildUpdateSet(table, set) {\n\t\tconst tableColumns = table[Table.Symbol.Columns];\n\t\tconst columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== void 0 || tableColumns[colName]?.onUpdateFn !== void 0);\n\t\tconst setLength = columnNames.length;\n\t\treturn sql.join(columnNames.flatMap((colName, i) => {\n\t\t\tconst col = tableColumns[colName];\n\t\t\tconst onUpdateFnResult = col.onUpdateFn?.();\n\t\t\tconst value = set[colName] ?? (is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col));\n\t\t\tconst res = sql`${sql.identifier(col.name)} = ${value}`;\n\t\t\tif (i < setLength - 1) return [res, sql.raw(\", \")];\n\t\t\treturn [res];\n\t\t}));\n\t}\n\tbuildUpdateQuery({ table, set, where, returning, withList, from, joins, comment, ignoreSelectionCastCodecs }) {\n\t\tconst withSql = this.buildWithCTE(withList);\n\t\tconst tableName = table[PgTable.Symbol.Name];\n\t\tconst tableSchema = table[PgTable.Symbol.Schema];\n\t\tconst origTableName = table[PgTable.Symbol.OriginalName];\n\t\tconst alias = tableName === origTableName ? void 0 : tableName;\n\t\tconst tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`;\n\t\tconst setSql = this.buildUpdateSet(table, set);\n\t\tconst fromSql = from && sql.join([sql.raw(\" from \"), this.buildFromTable(from)]);\n\t\tconst joinsSql = this.buildJoins(joins);\n\t\tconst returningSql = returning ? sql` returning ${this.buildSelection(returning, {\n\t\t\tisSingleTable: !from,\n\t\t\tignoreCastCodecs: ignoreSelectionCastCodecs\n\t\t})}` : void 0;\n\t\treturn sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${where ? sql` where ${where}` : void 0}${returningSql}${comment !== void 0 ? sql` ${comment}` : void 0}`;\n\t}\n\t/**\n\t* Builds selection SQL with provided fields/expressions\n\t*\n\t* Examples:\n\t*\n\t* `select <selection> from`\n\t*\n\t* `insert ... returning <selection>`\n\t*\n\t* If `isSingleTable` is true, then columns won't be prefixed with table name\n\t*/\n\tbuildSelection(fields, { isSingleTable = false, ignoreCastCodecs = false } = {}) {\n\t\tconst columnsLen = fields.length;\n\t\tconst chunks = fields.flatMap(({ field, codecOverride, column }, i) => {\n\t\t\tconst chunk = [];\n\t\t\tconst override = codecOverride;\n\t\t\tif (is(field, SQL.Aliased)) if (field.isSelectionField) {\n\t\t\t\tconst query = !isSingleTable && field.origin !== void 0 ? sql`${sql.identifier(field.origin)}.${sql.identifier(field.fieldAlias)}` : sql.identifier(field.fieldAlias);\n\t\t\t\tif (column && !ignoreCastCodecs) chunk.push(this.codecs.apply(column, \"cast\", query, override));\n\t\t\t\telse chunk.push(query);\n\t\t\t} else {\n\t\t\t\tconst query = field.sql;\n\t\t\t\tif (isSingleTable) {\n\t\t\t\t\tconst newSql = new SQL(query.queryChunks.map((c) => {\n\t\t\t\t\t\tif (is(c, PgColumn)) return sql.identifier(c.name);\n\t\t\t\t\t\treturn c;\n\t\t\t\t\t}));\n\t\t\t\t\tif (query.shouldInlineParams) newSql.inlineParams();\n\t\t\t\t\tchunk.push(column && !ignoreCastCodecs ? this.codecs.apply(column, \"cast\", newSql, override) : newSql);\n\t\t\t\t} else chunk.push(column && !ignoreCastCodecs ? this.codecs.apply(column, \"cast\", query, override) : query);\n\t\t\t\tchunk.push(sql` as ${sql.identifier(field.fieldAlias)}`);\n\t\t\t}\n\t\t\telse if (is(field, SQL)) {\n\t\t\t\tconst query = field;\n\t\t\t\tif (isSingleTable) {\n\t\t\t\t\tconst newSql = new SQL(query.queryChunks.map((c) => {\n\t\t\t\t\t\tif (is(c, PgColumn)) return sql.identifier(c.name);\n\t\t\t\t\t\treturn c;\n\t\t\t\t\t}));\n\t\t\t\t\tif (query.shouldInlineParams) newSql.inlineParams();\n\t\t\t\t\tchunk.push(column && !ignoreCastCodecs ? this.codecs.apply(column, \"cast\", newSql, override) : newSql);\n\t\t\t\t} else chunk.push(column && !ignoreCastCodecs ? this.codecs.apply(column, \"cast\", query, override) : query);\n\t\t\t} else if (is(field, Column)) {\n\t\t\t\tlet name;\n\t\t\t\tif (isSingleTable) name = field.isAlias ? sql.identifier(getOriginalColumnFromAlias(field).name) : sql.identifier(field.name);\n\t\t\t\telse name = field.isAlias ? getOriginalColumnFromAlias(field) : field;\n\t\t\t\tconst casted = ignoreCastCodecs ? name : this.codecs.apply(field, \"cast\", name, override);\n\t\t\t\tchunk.push(field.isAlias ? sql`${casted} as ${field}` : casted);\n\t\t\t} else if (is(field, Subquery)) if (column && !ignoreCastCodecs && !field._.isWith) {\n\t\t\t\tconst innerCasted = this.codecs.apply(column, \"cast\", sql`(${field._.sql})`, override);\n\t\t\t\tchunk.push(sql`${innerCasted} ${sql.identifier(field._.alias)}`);\n\t\t\t} else chunk.push(column ? this.codecs.apply(column, \"cast\", field) : field, override);\n\t\t\tif (i < columnsLen - 1) chunk.push(sql`, `);\n\t\t\treturn chunk;\n\t\t});\n\t\treturn sql.join(chunks);\n\t}\n\tbuildJoins(joins) {\n\t\tif (!joins || joins.length === 0) return;\n\t\tconst joinsArray = [];\n\t\tfor (const [index, joinMeta] of joins.entries()) {\n\t\t\tif (index === 0) joinsArray.push(sql` `);\n\t\t\tconst table = joinMeta.table;\n\t\t\tconst lateralSql = joinMeta.lateral ? sql` lateral` : void 0;\n\t\t\tconst onSql = joinMeta.on ? sql` on ${joinMeta.on}` : void 0;\n\t\t\tif (is(table, PgTable)) {\n\t\t\t\tconst tableName = table[PgTable.Symbol.Name];\n\t\t\t\tconst tableSchema = table[PgTable.Symbol.Schema];\n\t\t\t\tconst origTableName = table[PgTable.Symbol.OriginalName];\n\t\t\t\tconst alias = tableName === origTableName ? void 0 : joinMeta.alias;\n\t\t\t\tjoinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : void 0}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);\n\t\t\t} else if (is(table, View$1)) {\n\t\t\t\tconst viewName = table[ViewBaseConfig].name;\n\t\t\t\tconst viewSchema = table[ViewBaseConfig].schema;\n\t\t\t\tconst origViewName = table[ViewBaseConfig].originalName;\n\t\t\t\tconst alias = viewName === origViewName ? void 0 : joinMeta.alias;\n\t\t\t\tjoinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : void 0}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`);\n\t\t\t} else joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`);\n\t\t\tif (index < joins.length - 1) joinsArray.push(sql` `);\n\t\t}\n\t\treturn sql.join(joinsArray);\n\t}\n\tbuildFromTable(table) {\n\t\tif (is(table, Table) && table[Table.Symbol.IsAlias]) {\n\t\t\tlet fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`;\n\t\t\tif (table[Table.Symbol.Schema]) fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`;\n\t\t\treturn sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`;\n\t\t}\n\t\tif (is(table, View$1) && table[ViewBaseConfig].isAlias) {\n\t\t\tlet fullName = sql`${sql.identifier(table[ViewBaseConfig].originalName)}`;\n\t\t\tif (table[ViewBaseConfig].schema) fullName = sql`${sql.identifier(table[ViewBaseConfig].schema)}.${fullName}`;\n\t\t\treturn sql`${fullName} ${sql.identifier(table[ViewBaseConfig].name)}`;\n\t\t}\n\t\treturn table;\n\t}\n\tbuildSelectQuery({ withList, fieldsFlat, where, having, table, joins, orderBy, groupBy, limit, offset, lockingClause, distinct, setOperators, comment, ignoreSelectionCastCodecs }) {\n\t\tif (!fieldsFlat) throw new Error(\"Select query builder must be provided with `fieldsFlat` on `buildSelectQuery` invocation\");\n\t\tconst fieldsList = fieldsFlat;\n\t\tfor (const f of fieldsList) if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : getTableName(table)) && !((table) => joins?.some(({ alias }) => alias === (table[Table.Symbol.IsAlias] ? getTableName(table) : table[Table.Symbol.BaseName])))(f.field.table)) {\n\t\t\tconst tableName = getTableName(f.field.table);\n\t\t\tthrow new Error(`Your \"${f.path.join(\"->\")}\" field references a column \"${tableName}\".\"${f.field.name}\", but the table \"${tableName}\" is not part of the query! Did you forget to join it?`);\n\t\t}\n\t\tconst isSingleTable = !joins || joins.length === 0;\n\t\tconst withSql = this.buildWithCTE(withList);\n\t\tlet distinctSql;\n\t\tif (distinct) distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`;\n\t\tconst selection = this.buildSelection(fieldsList, {\n\t\t\tisSingleTable,\n\t\t\tignoreCastCodecs: ignoreSelectionCastCodecs || setOperators.length > 0\n\t\t});\n\t\tconst tableSql = this.buildFromTable(table);\n\t\tconst joinsSql = this.buildJoins(joins);\n\t\tconst whereSql = where ? sql` where ${where}` : void 0;\n\t\tconst havingSql = having ? sql` having ${having}` : void 0;\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`;\n\t\tlet groupBySql;\n\t\tif (groupBy && groupBy.length > 0) groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`;\n\t\tconst limitSql = typeof limit === \"object\" || typeof limit === \"number\" && limit >= 0 ? sql` limit ${limit}` : void 0;\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : void 0;\n\t\tconst lockingClauseSql = sql.empty();\n\t\tif (lockingClause) {\n\t\t\tconst clauseSql = sql` for ${sql.raw(lockingClause.strength)}`;\n\t\t\tif (lockingClause.config.of) clauseSql.append(sql` of ${sql.join(Array.isArray(lockingClause.config.of) ? lockingClause.config.of.map((it) => sql.identifier(it[PgTable.Symbol.Name])) : [sql.identifier(lockingClause.config.of[PgTable.Symbol.Name])], sql`, `)}`);\n\t\t\tif (lockingClause.config.noWait) clauseSql.append(sql` nowait`);\n\t\t\telse if (lockingClause.config.skipLocked) clauseSql.append(sql` skip locked`);\n\t\t\tlockingClauseSql.append(clauseSql);\n\t\t}\n\t\tconst finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}${comment !== void 0 ? sql` ${comment}` : void 0}`;\n\t\tif (setOperators.length > 0) return this.buildSetOperations(finalQuery, fieldsList, ignoreSelectionCastCodecs, setOperators);\n\t\treturn finalQuery;\n\t}\n\tbuildSetOperations(leftSelect, leftSelection, ignoreSelectionCastCodecs, setOperators) {\n\t\tconst outputSelection = leftSelection;\n\t\tfor (let i = 0; i < setOperators.length; ++i) {\n\t\t\tconst setOperator = setOperators[i];\n\t\t\tif (!setOperator) throw new Error(\"Cannot pass undefined values to any set operator\");\n\t\t\tleftSelect = this.buildSetOperationQuery({\n\t\t\t\tleftSelect,\n\t\t\t\tsetOperator\n\t\t\t});\n\t\t\tconst rightSelection = orderSelectedFields(setOperator.rightSelect.getSelectedFields());\n\t\t\tfor (let j = 0; j < outputSelection.length; ++j) {\n\t\t\t\tconst l = outputSelection[j];\n\t\t\t\tconst lPath = l.path.join(\".\");\n\t\t\t\tconst r = rightSelection.find((e) => e.path.join(\".\") === lPath);\n\t\t\t\tconst lc = l.codecOverride ?? l.column?.codec;\n\t\t\t\tconst rc = r.codecOverride ?? r.column?.codec;\n\t\t\t\toutputSelection[j].codecOverride = lc && rc ? unionsTypeTable[lc]?.[rc] : lc;\n\t\t\t}\n\t\t}\n\t\tfor (let i = 0; i < outputSelection.length; ++i) {\n\t\t\tconst out = outputSelection[i];\n\t\t\tout.codec = out.codecOverride ? this.codecs.get(out.column, \"normalize\", out.codecOverride) : out.codec;\n\t\t}\n\t\treturn ignoreSelectionCastCodecs ? leftSelect : sql`select ${this.buildSelection(outputSelection.map((field) => {\n\t\t\tif (is(field.field, SQL.Aliased)) {\n\t\t\t\tconst ref = field.field.clone();\n\t\t\t\tref.isSelectionField = true;\n\t\t\t\treturn {\n\t\t\t\t\t...field,\n\t\t\t\t\tfield: ref\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (is(field.field, Column) && field.field.isAlias) {\n\t\t\t\tconst ref = new SQL.Aliased(sql`${sql.identifier(field.field.name)}`, field.field.name);\n\t\t\t\tref.isSelectionField = true;\n\t\t\t\treturn {\n\t\t\t\t\t...field,\n\t\t\t\t\tfield: ref\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (is(field.field, Subquery)) {\n\t\t\t\tconst ref = new SQL.Aliased(sql`${field.field.getSQL()}`, field.field._.alias);\n\t\t\t\tref.isSelectionField = true;\n\t\t\t\treturn {\n\t\t\t\t\t...field,\n\t\t\t\t\tfield: ref\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn field;\n\t\t}), {\n\t\t\tisSingleTable: true,\n\t\t\tignoreCastCodecs: ignoreSelectionCastCodecs\n\t\t})} from (${leftSelect}) ${sql.identifier(\"drizzle_union\")}`;\n\t}\n\tbuildSetOperationQuery({ leftSelect, setOperator: { type, isAll, rightSelect, limit, orderBy, offset } }) {\n\t\tconst leftChunk = sql`(${leftSelect.getSQL()}) `;\n\t\tconst rightChunk = sql`(${rightSelect.withoutSelectionCastCodecs().getSQL()})`;\n\t\tlet orderBySql;\n\t\tif (orderBy && orderBy.length > 0) {\n\t\t\tconst orderByValues = [];\n\t\t\tfor (const singleOrderBy of orderBy) if (is(singleOrderBy, PgColumn)) orderByValues.push(sql.identifier(singleOrderBy.name));\n\t\t\telse if (is(singleOrderBy, SQL)) {\n\t\t\t\tfor (let i = 0; i < singleOrderBy.queryChunks.length; i++) {\n\t\t\t\t\tconst chunk = singleOrderBy.queryChunks[i];\n\t\t\t\t\tif (is(chunk, PgColumn)) singleOrderBy.queryChunks[i] = sql.identifier(chunk.name);\n\t\t\t\t}\n\t\t\t\torderByValues.push(sql`${singleOrderBy}`);\n\t\t\t} else orderByValues.push(sql`${singleOrderBy}`);\n\t\t\torderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `;\n\t\t}\n\t\tconst limitSql = typeof limit === \"object\" || typeof limit === \"number\" && limit >= 0 ? sql` limit ${limit}` : void 0;\n\t\tconst operatorChunk = sql.raw(`${type} ${isAll ? \"all \" : \"\"}`);\n\t\tconst offsetSql = offset ? sql` offset ${offset}` : void 0;\n\t\treturn sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`;\n\t}\n\tbuildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_, comment, ignoreSelectionCastCodecs }) {\n\t\tconst valuesSqlList = [];\n\t\tconst columns = table[Table.Symbol.Columns];\n\t\tconst colEntries = Object.entries(columns);\n\t\tconst colFilteredEntries = select && !is(valuesOrSelect, SQL) ? Object.keys(valuesOrSelect.getSelectedFields()).map((key) => [key, columns[key]]) : overridingSystemValue_ ? colEntries : colEntries.filter(([_, col]) => !col.shouldDisableInsert());\n\t\tconst insertOrder = colFilteredEntries.map(([, column]) => sql.identifier(column.name));\n\t\tif (select) {\n\t\t\tconst select = valuesOrSelect;\n\t\t\tif (is(select, SQL)) valuesSqlList.push(select);\n\t\t\telse valuesSqlList.push(select.getSQL());\n\t\t} else {\n\t\t\tconst values = valuesOrSelect;\n\t\t\tvaluesSqlList.push(sql.raw(\"values \"));\n\t\t\tfor (const [valueIndex, value] of values.entries()) {\n\t\t\t\tconst valueList = [];\n\t\t\t\tfor (const [fieldName, col] of colFilteredEntries) {\n\t\t\t\t\tconst colValue = value[fieldName];\n\t\t\t\t\tif (colValue === void 0 || is(colValue, Param) && colValue.value === void 0) if (col.defaultFn !== void 0) {\n\t\t\t\t\t\tconst defaultFnResult = col.defaultFn();\n\t\t\t\t\t\tconst defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col);\n\t\t\t\t\t\tvalueList.push(defaultValue);\n\t\t\t\t\t} else if (!col.default && col.onUpdateFn !== void 0) {\n\t\t\t\t\t\tconst onUpdateFnResult = col.onUpdateFn();\n\t\t\t\t\t\tconst newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col);\n\t\t\t\t\t\tvalueList.push(newValue);\n\t\t\t\t\t} else valueList.push(sql`default`);\n\t\t\t\t\telse valueList.push(colValue);\n\t\t\t\t}\n\t\t\t\tvaluesSqlList.push(valueList);\n\t\t\t\tif (valueIndex < values.length - 1) valuesSqlList.push(sql`, `);\n\t\t\t}\n\t\t}\n\t\tconst withSql = this.buildWithCTE(withList);\n\t\tconst valuesSql = sql.join(valuesSqlList);\n\t\tconst returningSql = returning ? sql` returning ${this.buildSelection(returning, {\n\t\t\tisSingleTable: true,\n\t\t\tignoreCastCodecs: ignoreSelectionCastCodecs\n\t\t})}` : void 0;\n\t\tconst onConflictSql = onConflict ? sql` on conflict ${onConflict}` : void 0;\n\t\treturn sql`${withSql}insert into ${table} ${insertOrder} ${overridingSystemValue_ === true ? sql`overriding system value ` : void 0}${valuesSql}${onConflictSql}${returningSql}${comment !== void 0 ? sql` ${comment}` : void 0}`;\n\t}\n\tbuildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) {\n\t\treturn sql`refresh materialized view${concurrently ? sql` concurrently` : void 0} ${view}${withNoData ? sql` with no data` : void 0}`;\n\t}\n\tsqlToQuery(sql, invokeSource) {\n\t\treturn sql.toQuery({\n\t\t\tescapeName: this.escapeName,\n\t\t\tescapeParam: this.escapeParam,\n\t\t\tescapeString: this.escapeString,\n\t\t\tcodecs: this.codecs,\n\t\t\tinvokeSource\n\t\t});\n\t}\n\t_sqlToQuery(sql) {\n\t\treturn sql.toQuery({\n\t\t\tescapeName: this.escapeName,\n\t\t\tescapeParam: this.escapeParam,\n\t\t\tescapeString: this.escapeString,\n\t\t\tcodecs: this.codecs,\n\t\t\ttagged: true\n\t\t});\n\t}\n\tbuildRqbColumn(table, field, key, inJson) {\n\t\tif (is(field, Column)) {\n\t\t\tconst name = sql`${table}.${sql.identifier(field.name)}`;\n\t\t\treturn sql`${inJson && field.jsonSelectIdentifier ? field.jsonSelectIdentifier(name, sql, field.dimensions) : this.codecs.apply(field, inJson ? \"castInJson\" : \"cast\", name)} as ${sql.identifier(key)}`;\n\t\t}\n\t\tif (is(field, SQL.Aliased)) {\n\t\t\tconst column = getColumnFromDecoder(field);\n\t\t\tconst q = sql`${table}.${sql.identifier(field.fieldAlias)}`;\n\t\t\treturn sql`${column ? this.codecs.apply(column, inJson ? \"castInJson\" : \"cast\", q) : q} as ${sql.identifier(key)}`;\n\t\t}\n\t\tif (isSQLWrapper$1(field)) {\n\t\t\tconst column = getColumnFromDecoder(field);\n\t\t\tconst q = sql`${table}.${sql.identifier(key)}`;\n\t\t\treturn sql`${column ? this.codecs.apply(column, inJson ? \"castInJson\" : \"cast\", q) : q} as ${sql.identifier(key)}`;\n\t\t}\n\t\tthrow new DrizzleError({ message: `Views with nested selections are not supported by the relational query builder` });\n\t}\n\tresolveSelection(field, key, inJson) {\n\t\tif (is(field, Column)) return {\n\t\t\tkey,\n\t\t\tfield,\n\t\t\tcodec: this.codecs.get(field, inJson ? \"normalizeInJson\" : \"normalize\"),\n\t\t\tarrayDimensions: field.dimensions\n\t\t};\n\t\tconst decoderColumn = getColumnFromDecoder(field);\n\t\treturn decoderColumn ? {\n\t\t\tkey,\n\t\t\tfield,\n\t\t\tcodec: decoderColumn && (!inJson || !decoderColumn.mapFromJsonValue) ? this.codecs.get(decoderColumn, inJson ? \"normalizeInJson\" : \"normalize\") : void 0,\n\t\t\tarrayDimensions: decoderColumn.dimensions\n\t\t} : {\n\t\t\tkey,\n\t\t\tfield\n\t\t};\n\t}\n\tbuildColumns = (table, selection, inJson, config) => {\n\t\tif (!config?.columns) return sql.join(Object.entries(table[TableColumns]).map(([k, v]) => {\n\t\t\tselection.push(this.resolveSelection(v, k, inJson));\n\t\t\treturn this.buildRqbColumn(table, v, k, inJson);\n\t\t}), sql`, `);\n\t\tconst entries = Object.entries(config.columns);\n\t\tconst columnContainer = table[TableColumns];\n\t\tconst columnIdentifiers = [];\n\t\tlet colSelectionMode;\n\t\tfor (const [k, v] of entries) {\n\t\t\tif (v === void 0) continue;\n\t\t\tcolSelectionMode = colSelectionMode || v;\n\t\t\tif (v) {\n\t\t\t\tconst column = columnContainer[k];\n\t\t\t\tcolumnIdentifiers.push(this.buildRqbColumn(table, column, k, inJson));\n\t\t\t\tselection.push(this.resolveSelection(column, k, inJson));\n\t\t\t}\n\t\t}\n\t\tif (colSelectionMode === false) for (const [k, v] of Object.entries(columnContainer)) {\n\t\t\tif (config.columns[k] === false) continue;\n\t\t\tcolumnIdentifiers.push(this.buildRqbColumn(table, v, k, inJson));\n\t\t\tselection.push(this.resolveSelection(v, k, inJson));\n\t\t}\n\t\treturn columnIdentifiers.length ? sql.join(columnIdentifiers, sql`, `) : void 0;\n\t};\n\tbuildRelationalQuery({ schema, table, tableConfig, queryConfig: config, relationWhere, mode, errorPath, depth, throughJoin, nested }) {\n\t\tconst selection = [];\n\t\tconst isSingle = mode === \"first\";\n\t\tconst params = config === true ? void 0 : config;\n\t\tconst currentPath = errorPath ?? \"\";\n\t\tconst currentDepth = depth ?? 0;\n\t\tif (!currentDepth) table = aliasedTable(table, `d${currentDepth}`);\n\t\tconst limit = isSingle ? 1 : params?.limit;\n\t\tconst offset = params?.offset;\n\t\tconst where = params?.where && relationWhere ? and(relationsFilterToSQL(table, params.where, tableConfig.relations, schema), relationWhere) : params?.where ? relationsFilterToSQL(table, params.where, tableConfig.relations, schema) : relationWhere;\n\t\tconst order = params?.orderBy ? relationsOrderToSQL(table, params.orderBy) : void 0;\n\t\tconst columns = this.buildColumns(table, selection, !!nested, params);\n\t\tconst extras = params?.extras ? relationExtrasToSQL(table, params.extras, this.codecs, nested) : void 0;\n\t\tif (extras) selection.push(...extras.selection);\n\t\tconst selectionArr = columns ? [columns] : [];\n\t\tif (extras?.sql) selectionArr.push(extras.sql);\n\t\tconst joins = params ? (() => {\n\t\t\tconst { with: joins } = params;\n\t\t\tif (!joins) return;\n\t\t\tconst withEntries = Object.entries(joins).filter(([_, v]) => v);\n\t\t\tif (!withEntries.length) return;\n\t\t\treturn sql.join(withEntries.map(([k, join]) => {\n\t\t\t\tconst relation = tableConfig.relations[k];\n\t\t\t\tconst isSingle = is(relation, One);\n\t\t\t\tconst targetTable = aliasedTable(relation.targetTable, `d${currentDepth + 1}`);\n\t\t\t\tconst throughTable = relation.throughTable ? aliasedTable(relation.throughTable, `tr${currentDepth}`) : void 0;\n\t\t\t\tconst { filter, joinCondition } = relationToSQL(relation, table, targetTable, throughTable);\n\t\t\t\tselectionArr.push(sql`${sql.identifier(k)}.${sql.identifier(\"r\")} as ${sql.identifier(k)}`);\n\t\t\t\tconst throughJoin = throughTable ? sql` inner join ${getTableAsAliasSQL(throughTable)} on ${joinCondition}` : void 0;\n\t\t\t\tconst innerQuery = this.buildRelationalQuery({\n\t\t\t\t\ttable: targetTable,\n\t\t\t\t\tmode: isSingle ? \"first\" : \"many\",\n\t\t\t\t\tschema,\n\t\t\t\t\tqueryConfig: join,\n\t\t\t\t\ttableConfig: schema[relation.targetTableName],\n\t\t\t\t\trelationWhere: filter,\n\t\t\t\t\terrorPath: `${currentPath.length ? `${currentPath}.` : \"\"}${k}`,\n\t\t\t\t\tdepth: currentDepth + 1,\n\t\t\t\t\tthroughJoin,\n\t\t\t\t\tnested: true\n\t\t\t\t});\n\t\t\t\tselection.push({\n\t\t\t\t\tfield: targetTable,\n\t\t\t\t\tkey: k,\n\t\t\t\t\tselection: innerQuery.selection,\n\t\t\t\t\tisArray: !isSingle,\n\t\t\t\t\tisOptional: (relation.optional ?? false) || join !== true && !!join.where\n\t\t\t\t});\n\t\t\t\treturn sql`left join lateral(select ${isSingle ? sql`row_to_json(${sql.identifier(\"t\")}.*) ${sql.identifier(\"r\")}` : sql`coalesce(json_agg(row_to_json(${sql.identifier(\"t\")}.*)), '[]') as ${sql.identifier(\"r\")}`} from (${innerQuery.sql}) as ${sql.identifier(\"t\")}) as ${sql.identifier(k)} on true`;\n\t\t\t}), sql` `);\n\t\t})() : void 0;\n\t\tif (!selectionArr.length) throw new DrizzleError({ message: `No fields selected for table \"${tableConfig.name}\"${currentPath ? ` (\"${currentPath}\")` : \"\"}` });\n\t\tconst selectionSet = sql.join(selectionArr.filter((e) => e !== void 0), sql`, `);\n\t\tconst comment = config !== true && config?.comment ? sql.comment(config.comment) : void 0;\n\t\treturn {\n\t\t\tsql: sql`select ${selectionSet} from ${getTableAsAliasSQL(table)}${throughJoin}${joins ? sql` ${joins}` : void 0}${where ? sql` where ${where}` : void 0}${order ? sql` order by ${order}` : void 0}${limit !== void 0 ? sql` limit ${limit}` : void 0}${offset !== void 0 ? sql` offset ${offset}` : void 0}${comment ? sql` ${comment}` : void 0}`,\n\t\t\tselection\n\t\t};\n\t}\n};\n\n//#endregion\nexport { PgDialect };\n//# sourceMappingURL=dialect.js.map",
81
+ "import { PgSelectBuilder } from \"./select.js\";\nimport { entityKind, is } from \"../../entity.js\";\nimport { WithSubquery } from \"../../subquery.js\";\nimport { SelectionProxyHandler } from \"../../selection-proxy.js\";\nimport { PgDialect } from \"../dialect.js\";\n\n//#region src/pg-core/query-builders/query-builder.ts\nvar QueryBuilder = class {\n\tstatic [entityKind] = \"PgQueryBuilder\";\n\tdialect;\n\tdialectConfig;\n\tconstructor(dialect) {\n\t\tthis.dialect = is(dialect, PgDialect) ? dialect : void 0;\n\t\tthis.dialectConfig = is(dialect, PgDialect) ? void 0 : dialect;\n\t}\n\t$with = (alias, selection) => {\n\t\tconst queryBuilder = this;\n\t\tconst as = (qb) => {\n\t\t\tif (typeof qb === \"function\") qb = qb(queryBuilder);\n\t\t\tconst sql = (\"withoutSelectionCastCodecs\" in qb ? qb.withoutSelectionCastCodecs() : qb).getSQL();\n\t\t\treturn new Proxy(new WithSubquery(sql, selection ?? (\"getSelectedFields\" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true, sql.usedTables ?? []), new SelectionProxyHandler({\n\t\t\t\talias,\n\t\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\t\tsqlBehavior: \"error\"\n\t\t\t}));\n\t\t};\n\t\treturn { as };\n\t};\n\twith(...queries) {\n\t\tconst self = this;\n\t\tfunction select(fields) {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? void 0,\n\t\t\t\tsession: void 0,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\twithList: queries\n\t\t\t});\n\t\t}\n\t\tfunction selectDistinct(fields) {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? void 0,\n\t\t\t\tsession: void 0,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\tdistinct: true\n\t\t\t});\n\t\t}\n\t\tfunction selectDistinctOn(on, fields) {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? void 0,\n\t\t\t\tsession: void 0,\n\t\t\t\tdialect: self.getDialect(),\n\t\t\t\tdistinct: { on }\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tselect,\n\t\t\tselectDistinct,\n\t\t\tselectDistinctOn\n\t\t};\n\t}\n\tselect(fields) {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? void 0,\n\t\t\tsession: void 0,\n\t\t\tdialect: this.getDialect()\n\t\t});\n\t}\n\tselectDistinct(fields) {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? void 0,\n\t\t\tsession: void 0,\n\t\t\tdialect: this.getDialect(),\n\t\t\tdistinct: true\n\t\t});\n\t}\n\tselectDistinctOn(on, fields) {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? void 0,\n\t\t\tsession: void 0,\n\t\t\tdialect: this.getDialect(),\n\t\t\tdistinct: { on }\n\t\t});\n\t}\n\tgetDialect() {\n\t\tif (!this.dialect) this.dialect = new PgDialect(this.dialectConfig);\n\t\treturn this.dialect;\n\t}\n};\n\n//#endregion\nexport { QueryBuilder };\n//# sourceMappingURL=query-builder.js.map",
82
+ "import { QueryBuilder } from \"./query-builder.js\";\nimport { entityKind, is } from \"../../entity.js\";\nimport { Table, getTableName } from \"../../table.js\";\nimport { mapUpdateSet, orderSelectedFields } from \"../../utils.js\";\nimport { Param, SQL, sql } from \"../../sql/sql.js\";\nimport { SelectionProxyHandler } from \"../../selection-proxy.js\";\n\n//#region src/pg-core/query-builders/insert.ts\nvar PgInsertBuilder = class {\n\tstatic [entityKind] = \"PgInsertBuilder\";\n\tconstructor(table, session, dialect, withList, overridingSystemValue_, builder = PgInsertBase) {\n\t\tthis.table = table;\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis.withList = withList;\n\t\tthis.overridingSystemValue_ = overridingSystemValue_;\n\t\tthis.builder = builder;\n\t}\n\toverridingSystemValue() {\n\t\tthis.overridingSystemValue_ = true;\n\t\treturn this;\n\t}\n\tvalues(values) {\n\t\tvalues = Array.isArray(values) ? values : [values];\n\t\tif (values.length === 0) throw new Error(\"values() must be called with at least one value\");\n\t\tconst mappedValues = values.map((entry) => {\n\t\t\tconst result = {};\n\t\t\tconst cols = this.table[Table.Symbol.Columns];\n\t\t\tfor (const colKey of Object.keys(entry)) {\n\t\t\t\tconst colValue = entry[colKey];\n\t\t\t\tresult[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]);\n\t\t\t}\n\t\t\treturn result;\n\t\t});\n\t\treturn new this.builder(this.table, mappedValues, this.session, this.dialect, this.withList, false, this.overridingSystemValue_);\n\t}\n\tselect(selectQuery) {\n\t\tconst select = typeof selectQuery === \"function\" ? selectQuery(new QueryBuilder()) : selectQuery;\n\t\tif (\"withoutSelectionCastCodecs\" in select) select.withoutSelectionCastCodecs();\n\t\tif (!is(select, SQL)) {\n\t\t\tconst insertCols = Object.keys(this.table[Table.Symbol.Columns]);\n\t\t\tconst selected = Object.keys(select._.selectedFields);\n\t\t\tfor (const col of selected) if (!insertCols.includes(col)) throw new Error(`Insert select error: column \"${col}\" does not exist in table \"${this.table[Table.Symbol.Name]}\"`);\n\t\t}\n\t\treturn new this.builder(this.table, select, this.session, this.dialect, this.withList, true, this.overridingSystemValue_);\n\t}\n};\nvar PgInsertBase = class {\n\tstatic [entityKind] = \"PgInsert\";\n\tconfig;\n\tconstructor(table, values, session, dialect, withList, select, overridingSystemValue_) {\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis.config = {\n\t\t\ttable,\n\t\t\tvalues,\n\t\t\twithList,\n\t\t\tselect,\n\t\t\toverridingSystemValue_\n\t\t};\n\t}\n\treturning(fields = this.config.table[Table.Symbol.Columns]) {\n\t\tthis.config.returningFields = fields;\n\t\tthis.config.returning = orderSelectedFields(this.config.returningFields, void 0, this.dialect.codecs);\n\t\treturn this;\n\t}\n\t/**\n\t* Adds an `on conflict do nothing` clause to the query.\n\t*\n\t* Calling this method simply avoids inserting a row as its alternative action.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/insert#on-conflict-do-nothing}\n\t*\n\t* @param config The `target` and `where` clauses.\n\t*\n\t* @example\n\t* ```ts\n\t* // Insert one row and cancel the insert if there's a conflict\n\t* await db.insert(cars)\n\t* .values({ id: 1, brand: 'BMW' })\n\t* .onConflictDoNothing();\n\t*\n\t* // Explicitly specify conflict target\n\t* await db.insert(cars)\n\t* .values({ id: 1, brand: 'BMW' })\n\t* .onConflictDoNothing({ target: cars.id });\n\t* ```\n\t*/\n\tonConflictDoNothing(config = {}) {\n\t\tif (config.target === void 0) this.config.onConflict = sql`do nothing`;\n\t\telse {\n\t\t\tlet targetColumn = \"\";\n\t\t\ttargetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(it.name)).join(\",\") : this.dialect.escapeName(config.target.name);\n\t\t\tconst whereSql = config.where ? sql` where ${config.where}` : void 0;\n\t\t\tthis.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`;\n\t\t}\n\t\treturn this;\n\t}\n\t/**\n\t* Adds an `on conflict do update` clause to the query.\n\t*\n\t* Calling this method will update the existing row that conflicts with the row proposed for insertion as its alternative action.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/insert#upserts-and-conflicts}\n\t*\n\t* @param config The `target`, `set` and `where` clauses.\n\t*\n\t* @example\n\t* ```ts\n\t* // Update the row if there's a conflict\n\t* await db.insert(cars)\n\t* .values({ id: 1, brand: 'BMW' })\n\t* .onConflictDoUpdate({\n\t* target: cars.id,\n\t* set: { brand: 'Porsche' }\n\t* });\n\t*\n\t* // Upsert with 'where' clause\n\t* await db.insert(cars)\n\t* .values({ id: 1, brand: 'BMW' })\n\t* .onConflictDoUpdate({\n\t* target: cars.id,\n\t* set: { brand: 'newBMW' },\n\t* targetWhere: sql`${cars.createdAt} > '2023-01-01'::date`,\n\t* });\n\t* ```\n\t*/\n\tonConflictDoUpdate(config) {\n\t\tif (config.where && (config.targetWhere || config.setWhere)) throw new Error(\"You cannot use both \\\"where\\\" and \\\"targetWhere\\\"/\\\"setWhere\\\" at the same time - \\\"where\\\" is deprecated, use \\\"targetWhere\\\" or \\\"setWhere\\\" instead.\");\n\t\tconst whereSql = config.where ? sql` where ${config.where}` : void 0;\n\t\tconst targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : void 0;\n\t\tconst setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : void 0;\n\t\tconst setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set));\n\t\tlet targetColumn = \"\";\n\t\ttargetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(it.name)).join(\",\") : this.dialect.escapeName(config.target.name);\n\t\tthis.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`;\n\t\treturn this;\n\t}\n\t/**\n\t* Attach [sqlcommenter](https://google.github.io/sqlcommenter) comment to a query\n\t*/\n\tcomment(comment) {\n\t\tthis.config.comment = sql.comment(comment);\n\t\treturn this;\n\t}\n\tgetSQL() {\n\t\treturn this.dialect.buildInsertQuery(this.config);\n\t}\n\ttoSQL() {\n\t\treturn this.dialect.sqlToQuery(this.getSQL());\n\t}\n\t/** @internal */\n\tgetSelectedFields() {\n\t\treturn this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({\n\t\t\talias: getTableName(this.config.table),\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\tsqlBehavior: \"error\"\n\t\t})) : void 0;\n\t}\n\t/** @internal */\n\twithoutSelectionCastCodecs() {\n\t\tthis.config.ignoreSelectionCastCodecs = true;\n\t\treturn this;\n\t}\n\t$dynamic() {\n\t\treturn this;\n\t}\n};\n\n//#endregion\nexport { PgInsertBase, PgInsertBuilder };\n//# sourceMappingURL=insert.js.map",
83
+ "import { extractUsedTable } from \"../utils.js\";\nimport { PgInsertBase } from \"../query-builders/insert.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { tracer } from \"../../tracing.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/insert.ts\nvar PgAsyncInsertBase = class extends PgInsertBase {\n\tstatic [entityKind] = \"PgAsyncInsert\";\n\t/** @internal */\n\t_prepare(name, generateName = false) {\n\t\tconst { session, config, dialect } = this;\n\t\tconst { returning: fields } = config;\n\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\tconst query = dialect.sqlToQuery(this.getSQL());\n\t\t\tconst mapper = fields ? this.dialect.mapperGenerators.rows(fields, void 0) : void 0;\n\t\t\treturn session.prepareQuery(query, fields ? \"arrays\" : \"raw\", name ?? generateName, mapper, {\n\t\t\t\ttype: \"insert\",\n\t\t\t\ttables: [...extractUsedTable(this.config.table)]\n\t\t\t});\n\t\t});\n\t}\n\tprepare(name) {\n\t\treturn this._prepare(name, true);\n\t}\n\texecute = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n};\napplyMixins(PgAsyncInsertBase, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncInsertBase };\n//# sourceMappingURL=insert.js.map",
84
+ "import { PgRelationalQuery } from \"../query-builders/query.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { tracer } from \"../../tracing.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/query.ts\nvar PgAsyncRelationalQuery = class extends PgRelationalQuery {\n\tstatic [entityKind] = \"PgAsyncRelationalQueryV2\";\n\t/** @internal */\n\t_prepare(name, generateName = false) {\n\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\tconst { query, builtQuery } = this._toSQL();\n\t\t\tconst mapper = this.dialect.mapperGenerators.relationalRows({\n\t\t\t\tisFirst: this.mode === \"first\",\n\t\t\t\tparseJson: this.parseJson,\n\t\t\t\tparseJsonIfString: false,\n\t\t\t\trootJsonMappers: false,\n\t\t\t\tselection: query.selection,\n\t\t\t\tarrayModeRoot: true\n\t\t\t});\n\t\t\treturn this.session.prepareQuery(builtQuery, \"arrays\", name ?? generateName, mapper);\n\t\t});\n\t}\n\tprepare(name) {\n\t\treturn this._prepare(name, true);\n\t}\n\texecute(placeholderValues) {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t}\n};\napplyMixins(PgAsyncRelationalQuery, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncRelationalQuery };\n//# sourceMappingURL=query.js.map",
85
+ "import { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/query-builders/raw.ts\nvar PgRaw = class {\n\tstatic [entityKind] = \"PgRaw\";\n\tconstructor(prepared, sql, query) {\n\t\tthis.prepared = prepared;\n\t\tthis.sql = sql;\n\t\tthis.query = query;\n\t}\n\tgetSQL() {\n\t\treturn this.sql;\n\t}\n\tgetQuery() {\n\t\treturn this.query;\n\t}\n\t_prepare() {\n\t\treturn this.prepared;\n\t}\n};\n\n//#endregion\nexport { PgRaw };\n//# sourceMappingURL=raw.js.map",
86
+ "import { PgRaw } from \"../query-builders/raw.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/raw.ts\nvar PgAsyncRaw = class extends PgRaw {\n\tstatic [entityKind] = \"PgAsyncRaw\";\n\tconstructor(prepared, sql, query) {\n\t\tsuper(prepared, sql, query);\n\t}\n\texecute(placeholderValues) {\n\t\treturn this.prepared.execute(placeholderValues);\n\t}\n\t_prepare() {\n\t\treturn this.prepared;\n\t}\n};\napplyMixins(PgAsyncRaw, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncRaw };\n//# sourceMappingURL=raw.js.map",
87
+ "import { entityKind } from \"../../entity.js\";\n\n//#region src/pg-core/query-builders/refresh-materialized-view.ts\nvar PgRefreshMaterializedView = class {\n\tstatic [entityKind] = \"PgRefreshMaterializedView\";\n\tconfig;\n\tconstructor(view, session, dialect) {\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis.config = { view };\n\t}\n\tconcurrently() {\n\t\tif (this.config.withNoData !== void 0) throw new Error(\"Cannot use concurrently and withNoData together\");\n\t\tthis.config.concurrently = true;\n\t\treturn this;\n\t}\n\twithNoData() {\n\t\tif (this.config.concurrently !== void 0) throw new Error(\"Cannot use concurrently and withNoData together\");\n\t\tthis.config.withNoData = true;\n\t\treturn this;\n\t}\n\t/** @internal */\n\tgetSQL() {\n\t\treturn this.dialect.buildRefreshMaterializedViewQuery(this.config);\n\t}\n\ttoSQL() {\n\t\treturn this.dialect.sqlToQuery(this.getSQL());\n\t}\n};\n\n//#endregion\nexport { PgRefreshMaterializedView };\n//# sourceMappingURL=refresh-materialized-view.js.map",
88
+ "import { PgRefreshMaterializedView } from \"../query-builders/refresh-materialized-view.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { tracer } from \"../../tracing.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/refresh-materialized-view.ts\nvar PgAsyncRefreshMaterializedView = class extends PgRefreshMaterializedView {\n\tstatic [entityKind] = \"PgAsyncRefreshMaterializedView\";\n\t/** @internal */\n\t_prepare(name, generateName = false) {\n\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\tconst query = this.dialect.sqlToQuery(this.getSQL());\n\t\t\treturn this.session.prepareQuery(query, \"raw\", name ?? generateName);\n\t\t});\n\t}\n\tprepare(name) {\n\t\treturn this._prepare(name, true);\n\t}\n\texecute = (placeholderValues) => {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t};\n};\napplyMixins(PgAsyncRefreshMaterializedView, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncRefreshMaterializedView };\n//# sourceMappingURL=refresh-materialized-view.js.map",
89
+ "import { PgSelectBase } from \"../query-builders/select.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { tracer } from \"../../tracing.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/select.ts\nvar PgAsyncSelectBase = class extends PgSelectBase {\n\tstatic [entityKind] = \"PgAsyncSelectQueryBuilder\";\n\t/** @internal */\n\t_prepare(name, generateName = false) {\n\t\tconst { session, dialect, cacheConfig, usedTables } = this;\n\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\tconst query = this.config.tagged ? dialect._sqlToQuery(this.getSQL()) : dialect.sqlToQuery(this.getSQL());\n\t\t\tconst fieldsList = this.config.fieldsFlat;\n\t\t\tconst mapper = this.dialect.mapperGenerators.rows(fieldsList, this.joinsNotNullableMap);\n\t\t\treturn session.prepareQuery(query, \"arrays\", name ?? generateName, mapper, {\n\t\t\t\ttype: \"select\",\n\t\t\t\ttables: [...usedTables]\n\t\t\t}, cacheConfig);\n\t\t});\n\t}\n\t/**\n\t* Create a prepared statement for this query. This allows\n\t* the database to remember this query for the given session\n\t* and call it by name, rather than specifying the full query.\n\t*\n\t* {@link https://www.postgresql.org/docs/current/sql-prepare.html | Postgres prepare documentation}\n\t*/\n\tprepare(name) {\n\t\treturn this._prepare(name, true);\n\t}\n\texecute(placeholderValues) {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn this._prepare().execute(placeholderValues);\n\t\t});\n\t}\n};\napplyMixins(PgAsyncSelectBase, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncSelectBase };\n//# sourceMappingURL=select.js.map",
90
+ "import { entityKind, is } from \"../../entity.js\";\nimport { Subquery } from \"../../subquery.js\";\nimport { ViewBaseConfig } from \"../../view-common.js\";\nimport { Table, getTableName } from \"../../table.js\";\nimport { getTableLikeName, mapUpdateSet, orderSelectedFields } from \"../../utils.js\";\nimport { SQL, sql } from \"../../sql/sql.js\";\nimport { SelectionProxyHandler } from \"../../selection-proxy.js\";\nimport { PgTable } from \"../table.js\";\n\n//#region src/pg-core/query-builders/update.ts\nvar PgUpdateBuilder = class {\n\tstatic [entityKind] = \"PgUpdateBuilder\";\n\tconstructor(table, session, dialect, withList, builder = PgUpdateBase) {\n\t\tthis.table = table;\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis.withList = withList;\n\t\tthis.builder = builder;\n\t}\n\tset(values) {\n\t\treturn new this.builder(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList);\n\t}\n};\nvar PgUpdateBase = class {\n\tstatic [entityKind] = \"PgUpdate\";\n\tconfig;\n\ttableName;\n\tjoinsNotNullableMap;\n\tconstructor(table, set, session, dialect, withList) {\n\t\tthis.session = session;\n\t\tthis.dialect = dialect;\n\t\tthis.config = {\n\t\t\tset,\n\t\t\ttable,\n\t\t\twithList,\n\t\t\tjoins: []\n\t\t};\n\t\tthis.tableName = getTableLikeName(table);\n\t\tthis.joinsNotNullableMap = typeof this.tableName === \"string\" ? { [this.tableName]: true } : {};\n\t}\n\tfrom(source) {\n\t\tconst src = source;\n\t\tconst tableName = getTableLikeName(src);\n\t\tif (typeof tableName === \"string\") this.joinsNotNullableMap[tableName] = true;\n\t\tthis.config.from = src;\n\t\treturn this;\n\t}\n\tgetTableLikeFields(table) {\n\t\tif (is(table, PgTable)) return table[Table.Symbol.Columns];\n\t\telse if (is(table, Subquery)) return table._.selectedFields;\n\t\treturn table[ViewBaseConfig].selectedFields;\n\t}\n\tcreateJoin(joinType) {\n\t\treturn ((table, on) => {\n\t\t\tconst tableName = getTableLikeName(table);\n\t\t\tif (typeof tableName === \"string\" && this.config.joins.some((join) => join.alias === tableName)) throw new Error(`Alias \"${tableName}\" is already used in this query`);\n\t\t\tif (typeof on === \"function\") {\n\t\t\t\tconst from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : void 0;\n\t\t\t\ton = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({\n\t\t\t\t\tsqlAliasedBehavior: \"sql\",\n\t\t\t\t\tsqlBehavior: \"sql\"\n\t\t\t\t})), from && new Proxy(from, new SelectionProxyHandler({\n\t\t\t\t\tsqlAliasedBehavior: \"sql\",\n\t\t\t\t\tsqlBehavior: \"sql\"\n\t\t\t\t})));\n\t\t\t}\n\t\t\tthis.config.joins.push({\n\t\t\t\ton,\n\t\t\t\ttable,\n\t\t\t\tjoinType,\n\t\t\t\talias: tableName\n\t\t\t});\n\t\t\tif (typeof tableName === \"string\") switch (joinType) {\n\t\t\t\tcase \"left\":\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"right\":\n\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"inner\":\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = true;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"full\":\n\t\t\t\t\tthis.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false]));\n\t\t\t\t\tthis.joinsNotNullableMap[tableName] = false;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn this;\n\t\t});\n\t}\n\tleftJoin = this.createJoin(\"left\");\n\trightJoin = this.createJoin(\"right\");\n\tinnerJoin = this.createJoin(\"inner\");\n\tfullJoin = this.createJoin(\"full\");\n\t/**\n\t* Adds a 'where' clause to the query.\n\t*\n\t* Calling this method will update only those rows that fulfill a specified condition.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/update}\n\t*\n\t* @param where the 'where' clause.\n\t*\n\t* @example\n\t* You can use conditional operators and `sql function` to filter the rows to be updated.\n\t*\n\t* ```ts\n\t* // Update all cars with green color\n\t* await db.update(cars).set({ color: 'red' })\n\t* .where(eq(cars.color, 'green'));\n\t* // or\n\t* await db.update(cars).set({ color: 'red' })\n\t* .where(sql`${cars.color} = 'green'`)\n\t* ```\n\t*\n\t* You can logically combine conditional operators with `and()` and `or()` operators:\n\t*\n\t* ```ts\n\t* // Update all BMW cars with a green color\n\t* await db.update(cars).set({ color: 'red' })\n\t* .where(and(eq(cars.color, 'green'), eq(cars.brand, 'BMW')));\n\t*\n\t* // Update all cars with the green or blue color\n\t* await db.update(cars).set({ color: 'red' })\n\t* .where(or(eq(cars.color, 'green'), eq(cars.color, 'blue')));\n\t* ```\n\t*/\n\twhere(where) {\n\t\tthis.config.where = where;\n\t\treturn this;\n\t}\n\treturning(fields) {\n\t\tif (!fields) {\n\t\t\tfields = Object.assign({}, this.config.table[Table.Symbol.Columns]);\n\t\t\tif (this.config.from) {\n\t\t\t\tconst tableName = getTableLikeName(this.config.from);\n\t\t\t\tif (typeof tableName === \"string\" && this.config.from && !is(this.config.from, SQL)) {\n\t\t\t\t\tconst fromFields = this.getTableLikeFields(this.config.from);\n\t\t\t\t\tfields[tableName] = fromFields;\n\t\t\t\t}\n\t\t\t\tfor (const join of this.config.joins) {\n\t\t\t\t\tconst tableName = getTableLikeName(join.table);\n\t\t\t\t\tif (typeof tableName === \"string\" && !is(join.table, SQL)) {\n\t\t\t\t\t\tconst fromFields = this.getTableLikeFields(join.table);\n\t\t\t\t\t\tfields[tableName] = fromFields;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.config.returningFields = fields;\n\t\tthis.config.returning = orderSelectedFields(fields, void 0, this.dialect.codecs);\n\t\treturn this;\n\t}\n\t/**\n\t* Attach [sqlcommenter](https://google.github.io/sqlcommenter) comment to a query\n\t*/\n\tcomment(comment) {\n\t\tthis.config.comment = sql.comment(comment);\n\t\treturn this;\n\t}\n\tgetSQL() {\n\t\treturn this.dialect.buildUpdateQuery(this.config);\n\t}\n\ttoSQL() {\n\t\treturn this.dialect.sqlToQuery(this.getSQL());\n\t}\n\t/** @internal */\n\tgetSelectedFields() {\n\t\treturn this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({\n\t\t\talias: getTableName(this.config.table),\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\tsqlBehavior: \"error\"\n\t\t})) : void 0;\n\t}\n\t/** @internal */\n\twithoutSelectionCastCodecs() {\n\t\tthis.config.ignoreSelectionCastCodecs = true;\n\t\treturn this;\n\t}\n\t$dynamic() {\n\t\treturn this;\n\t}\n};\n\n//#endregion\nexport { PgUpdateBase, PgUpdateBuilder };\n//# sourceMappingURL=update.js.map",
91
+ "import { extractUsedTable } from \"../utils.js\";\nimport { PgUpdateBase } from \"../query-builders/update.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { tracer } from \"../../tracing.js\";\nimport { applyMixins } from \"../../utils.js\";\nimport { QueryPromise } from \"../../query-promise.js\";\n\n//#region src/pg-core/async/update.ts\nvar PgAsyncUpdateBase = class extends PgUpdateBase {\n\tstatic [entityKind] = \"PgAsyncUpdate\";\n\t/** @internal */\n\t_prepare(name, generateName = false) {\n\t\tconst { session, config, dialect, joinsNotNullableMap } = this;\n\t\tconst { returning: fields } = config;\n\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\tconst query = dialect.sqlToQuery(this.getSQL());\n\t\t\tconst mapper = fields ? this.dialect.mapperGenerators.rows(fields, joinsNotNullableMap) : void 0;\n\t\t\treturn session.prepareQuery(query, fields ? \"arrays\" : \"raw\", name ?? generateName, mapper, {\n\t\t\t\ttype: \"update\",\n\t\t\t\ttables: [...extractUsedTable(this.config.table)]\n\t\t\t});\n\t\t});\n\t}\n\tprepare(name) {\n\t\treturn this._prepare(name, true);\n\t}\n\texecute = (placeholderValues = {}) => {\n\t\treturn this._prepare().execute(placeholderValues);\n\t};\n};\napplyMixins(PgAsyncUpdateBase, [QueryPromise]);\n\n//#endregion\nexport { PgAsyncUpdateBase };\n//# sourceMappingURL=update.js.map",
92
+ "import { PgAsyncCountBuilder } from \"./count.js\";\nimport { RelationalQueryBuilder } from \"../query-builders/query.js\";\nimport { PgAsyncDeleteBase } from \"./delete.js\";\nimport { PgAsyncInsertBase } from \"./insert.js\";\nimport { PgAsyncRelationalQuery } from \"./query.js\";\nimport { PgAsyncRaw } from \"./raw.js\";\nimport { PgAsyncRefreshMaterializedView } from \"./refresh-materialized-view.js\";\nimport { PgAsyncSelectBase } from \"./select.js\";\nimport { PgAsyncUpdateBase } from \"./update.js\";\nimport { entityKind } from \"../../entity.js\";\nimport { WithSubquery } from \"../../subquery.js\";\nimport { sql } from \"../../sql/sql.js\";\nimport { SelectionProxyHandler } from \"../../selection-proxy.js\";\nimport { PgInsertBuilder, PgSelectBuilder, PgUpdateBuilder, QueryBuilder } from \"../query-builders/index.js\";\n\n//#region src/pg-core/async/db.ts\nvar PgAsyncDatabase = class {\n\tstatic [entityKind] = \"PgAsyncDatabase\";\n\tquery;\n\tconstructor(dialect, session, relations, parseRqbJson = false, tagged = false) {\n\t\tthis.dialect = dialect;\n\t\tthis.session = session;\n\t\tthis.tagged = tagged;\n\t\tthis._ = {\n\t\t\trelations,\n\t\t\tsession\n\t\t};\n\t\tthis.query = {};\n\t\tfor (const [tableName, relation] of Object.entries(relations)) this.query[tableName] = new RelationalQueryBuilder(relations, relations[relation.name].table, relation, dialect, session, parseRqbJson, PgAsyncRelationalQuery);\n\t\tthis.$cache = { invalidate: async (_params) => {} };\n\t}\n\t/**\n\t* Creates a subquery that defines a temporary named result set as a CTE.\n\t*\n\t* It is useful for breaking down complex queries into simpler parts and for reusing the result set in subsequent parts of the query.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t*\n\t* @param alias The alias for the subquery.\n\t*\n\t* Failure to provide an alias will result in a DrizzleTypeError, preventing the subquery from being referenced in other queries.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Create a subquery with alias 'sq' and use it in the select query\n\t* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t*\n\t* const result = await db.with(sq).select().from(sq);\n\t* ```\n\t*\n\t* To select arbitrary SQL values as fields in a CTE and reference them in other CTEs or in the main query, you need to add aliases to them:\n\t*\n\t* ```ts\n\t* // Select an arbitrary SQL value as a field in a CTE and reference it in the main query\n\t* const sq = db.$with('sq').as(db.select({\n\t* name: sql<string>`upper(${users.name})`.as('name'),\n\t* })\n\t* .from(users));\n\t*\n\t* const result = await db.with(sq).select({ name: sq.name }).from(sq);\n\t* ```\n\t*/\n\t$with = (alias, selection) => {\n\t\tconst as = (qb) => {\n\t\t\tif (typeof qb === \"function\") qb = qb(new QueryBuilder(this.dialect));\n\t\t\tconst sql = (\"withoutSelectionCastCodecs\" in qb ? qb.withoutSelectionCastCodecs() : qb).getSQL();\n\t\t\treturn new Proxy(new WithSubquery(sql, selection ?? (\"getSelectedFields\" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true, sql.usedTables ?? []), new SelectionProxyHandler({\n\t\t\t\talias,\n\t\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\t\tsqlBehavior: \"error\"\n\t\t\t}));\n\t\t};\n\t\treturn { as };\n\t};\n\t$count(source, filters) {\n\t\treturn new PgAsyncCountBuilder({\n\t\t\tsource,\n\t\t\tfilters,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect\n\t\t});\n\t}\n\t$cache;\n\t/**\n\t* Incorporates a previously defined CTE (using `$with`) into the main query.\n\t*\n\t* This method allows the main query to reference a temporary named result set.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/select#with-clause}\n\t*\n\t* @param queries The CTEs to incorporate into the main query.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Define a subquery 'sq' as a CTE using $with\n\t* const sq = db.$with('sq').as(db.select().from(users).where(eq(users.id, 42)));\n\t*\n\t* // Incorporate the CTE 'sq' into the main query and select from it\n\t* const result = await db.with(sq).select().from(sq);\n\t* ```\n\t*/\n\twith(...queries) {\n\t\tconst self = this;\n\t\tfunction select(fields) {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? void 0,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\ttagged: self.tagged\n\t\t\t}, PgAsyncSelectBase);\n\t\t}\n\t\tfunction selectDistinct(fields) {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? void 0,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: true,\n\t\t\t\ttagged: self.tagged\n\t\t\t}, PgAsyncSelectBase);\n\t\t}\n\t\tfunction selectDistinctOn(on, fields) {\n\t\t\treturn new PgSelectBuilder({\n\t\t\t\tfields: fields ?? void 0,\n\t\t\t\tsession: self.session,\n\t\t\t\tdialect: self.dialect,\n\t\t\t\twithList: queries,\n\t\t\t\tdistinct: { on },\n\t\t\t\ttagged: self.tagged\n\t\t\t}, PgAsyncSelectBase);\n\t\t}\n\t\t/**\n\t\t* Creates an update query.\n\t\t*\n\t\t* Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t\t*\n\t\t* Use `.set()` method to specify which values to update.\n\t\t*\n\t\t* See docs: {@link https://orm.drizzle.team/docs/update}\n\t\t*\n\t\t* @param table The table to update.\n\t\t*\n\t\t* @example\n\t\t*\n\t\t* ```ts\n\t\t* // Update all rows in the 'cars' table\n\t\t* await db.update(cars).set({ color: 'red' });\n\t\t*\n\t\t* // Update rows with filters and conditions\n\t\t* await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t\t*\n\t\t* // Update with returning clause\n\t\t* const updatedCar: Car[] = await db.update(cars)\n\t\t* .set({ color: 'red' })\n\t\t* .where(eq(cars.id, 1))\n\t\t* .returning();\n\t\t* ```\n\t\t*/\n\t\tfunction update(table) {\n\t\t\treturn new PgUpdateBuilder(table, self.session, self.dialect, queries, PgAsyncUpdateBase);\n\t\t}\n\t\t/**\n\t\t* Creates an insert query.\n\t\t*\n\t\t* Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t\t*\n\t\t* See docs: {@link https://orm.drizzle.team/docs/insert}\n\t\t*\n\t\t* @param table The table to insert into.\n\t\t*\n\t\t* @example\n\t\t*\n\t\t* ```ts\n\t\t* // Insert one row\n\t\t* await db.insert(cars).values({ brand: 'BMW' });\n\t\t*\n\t\t* // Insert multiple rows\n\t\t* await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t\t*\n\t\t* // Insert with returning clause\n\t\t* const insertedCar: Car[] = await db.insert(cars)\n\t\t* .values({ brand: 'BMW' })\n\t\t* .returning();\n\t\t* ```\n\t\t*/\n\t\tfunction insert(table) {\n\t\t\treturn new PgInsertBuilder(table, self.session, self.dialect, queries, void 0, PgAsyncInsertBase);\n\t\t}\n\t\t/**\n\t\t* Creates a delete query.\n\t\t*\n\t\t* Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t\t*\n\t\t* See docs: {@link https://orm.drizzle.team/docs/delete}\n\t\t*\n\t\t* @param table The table to delete from.\n\t\t*\n\t\t* @example\n\t\t*\n\t\t* ```ts\n\t\t* // Delete all rows in the 'cars' table\n\t\t* await db.delete(cars);\n\t\t*\n\t\t* // Delete rows with filters and conditions\n\t\t* await db.delete(cars).where(eq(cars.color, 'green'));\n\t\t*\n\t\t* // Delete with returning clause\n\t\t* const deletedCar: Car[] = await db.delete(cars)\n\t\t* .where(eq(cars.id, 1))\n\t\t* .returning();\n\t\t* ```\n\t\t*/\n\t\tfunction delete_(table) {\n\t\t\treturn new PgAsyncDeleteBase(table, self.session, self.dialect, queries);\n\t\t}\n\t\treturn {\n\t\t\tselect,\n\t\t\tselectDistinct,\n\t\t\tselectDistinctOn,\n\t\t\tupdate,\n\t\t\tinsert,\n\t\t\tdelete: delete_\n\t\t};\n\t}\n\tselect(fields) {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? void 0,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\ttagged: this.tagged\n\t\t}, PgAsyncSelectBase);\n\t}\n\tselectDistinct(fields) {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? void 0,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\tdistinct: true,\n\t\t\ttagged: this.tagged\n\t\t}, PgAsyncSelectBase);\n\t}\n\tselectDistinctOn(on, fields) {\n\t\treturn new PgSelectBuilder({\n\t\t\tfields: fields ?? void 0,\n\t\t\tsession: this.session,\n\t\t\tdialect: this.dialect,\n\t\t\tdistinct: { on },\n\t\t\ttagged: this.tagged\n\t\t}, PgAsyncSelectBase);\n\t}\n\t/**\n\t* Creates an update query.\n\t*\n\t* Calling this method without `.where()` clause will update all rows in a table. The `.where()` clause specifies which rows should be updated.\n\t*\n\t* Use `.set()` method to specify which values to update.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/update}\n\t*\n\t* @param table The table to update.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Update all rows in the 'cars' table\n\t* await db.update(cars).set({ color: 'red' });\n\t*\n\t* // Update rows with filters and conditions\n\t* await db.update(cars).set({ color: 'red' }).where(eq(cars.brand, 'BMW'));\n\t*\n\t* // Update with returning clause\n\t* const updatedCar: Car[] = await db.update(cars)\n\t* .set({ color: 'red' })\n\t* .where(eq(cars.id, 1))\n\t* .returning();\n\t* ```\n\t*/\n\tupdate(table) {\n\t\treturn new PgUpdateBuilder(table, this.session, this.dialect, void 0, PgAsyncUpdateBase);\n\t}\n\t/**\n\t* Creates an insert query.\n\t*\n\t* Calling this method will create new rows in a table. Use `.values()` method to specify which values to insert.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/insert}\n\t*\n\t* @param table The table to insert into.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Insert one row\n\t* await db.insert(cars).values({ brand: 'BMW' });\n\t*\n\t* // Insert multiple rows\n\t* await db.insert(cars).values([{ brand: 'BMW' }, { brand: 'Porsche' }]);\n\t*\n\t* // Insert with returning clause\n\t* const insertedCar: Car[] = await db.insert(cars)\n\t* .values({ brand: 'BMW' })\n\t* .returning();\n\t* ```\n\t*/\n\tinsert(table) {\n\t\treturn new PgInsertBuilder(table, this.session, this.dialect, void 0, void 0, PgAsyncInsertBase);\n\t}\n\t/**\n\t* Creates a delete query.\n\t*\n\t* Calling this method without `.where()` clause will delete all rows in a table. The `.where()` clause specifies which rows should be deleted.\n\t*\n\t* See docs: {@link https://orm.drizzle.team/docs/delete}\n\t*\n\t* @param table The table to delete from.\n\t*\n\t* @example\n\t*\n\t* ```ts\n\t* // Delete all rows in the 'cars' table\n\t* await db.delete(cars);\n\t*\n\t* // Delete rows with filters and conditions\n\t* await db.delete(cars).where(eq(cars.color, 'green'));\n\t*\n\t* // Delete with returning clause\n\t* const deletedCar: Car[] = await db.delete(cars)\n\t* .where(eq(cars.id, 1))\n\t* .returning();\n\t* ```\n\t*/\n\tdelete(table) {\n\t\treturn new PgAsyncDeleteBase(table, this.session, this.dialect);\n\t}\n\trefreshMaterializedView(view) {\n\t\treturn new PgAsyncRefreshMaterializedView(view, this.session, this.dialect);\n\t}\n\texecute(query) {\n\t\tconst sequel = typeof query === \"string\" ? sql.raw(query) : query.getSQL();\n\t\tconst builtQuery = this.dialect.sqlToQuery(sequel);\n\t\treturn new PgAsyncRaw(this.session.prepareQuery(builtQuery, \"raw\", false), sequel, builtQuery);\n\t}\n\ttransaction(transaction, config) {\n\t\treturn this.session.transaction(transaction, config);\n\t}\n};\nconst withReplicas = (primary, replicas, getReplica = () => replicas[Math.floor(Math.random() * replicas.length)]) => {\n\tconst select = (...args) => getReplica(replicas).select(...args);\n\tconst selectDistinct = (...args) => getReplica(replicas).selectDistinct(...args);\n\tconst selectDistinctOn = (...args) => getReplica(replicas).selectDistinctOn(...args);\n\tconst $count = (...args) => getReplica(replicas).$count(...args);\n\tconst _with = (...args) => getReplica(replicas).with(...args);\n\tconst $with = (arg) => getReplica(replicas).$with(arg);\n\tconst update = (...args) => primary.update(...args);\n\tconst insert = (...args) => primary.insert(...args);\n\tconst $delete = (...args) => primary.delete(...args);\n\tconst execute = (...args) => primary.execute(...args);\n\tconst transaction = (...args) => primary.transaction(...args);\n\tconst refreshMaterializedView = (...args) => primary.refreshMaterializedView(...args);\n\treturn {\n\t\t...primary,\n\t\tupdate,\n\t\tinsert,\n\t\tdelete: $delete,\n\t\texecute,\n\t\ttransaction,\n\t\trefreshMaterializedView,\n\t\t$primary: primary,\n\t\t$replicas: replicas,\n\t\tselect,\n\t\tselectDistinct,\n\t\tselectDistinctOn,\n\t\t$count,\n\t\t$with,\n\t\twith: _with,\n\t\tget query() {\n\t\t\treturn getReplica(replicas).query;\n\t\t}\n\t};\n};\n\n//#endregion\nexport { PgAsyncDatabase, withReplicas };\n//# sourceMappingURL=db.js.map",
93
+ "import { entityKind } from \"../entity.js\";\n\n//#region src/pg-core/session.ts\nvar PgBasePreparedQuery = class {\n\tstatic [entityKind] = \"PgBasePreparedQuery\";\n\tconstructor(query) {\n\t\tthis.query = query;\n\t}\n\tgetQuery() {\n\t\treturn this.query;\n\t}\n};\nvar PgSession = class {\n\tstatic [entityKind] = \"PgSession\";\n\tconstructor(dialect) {\n\t\tthis.dialect = dialect;\n\t}\n};\n\n//#endregion\nexport { PgBasePreparedQuery, PgSession };\n//# sourceMappingURL=session.js.map",
94
+ "import { entityKind } from \"../../entity.js\";\n\n//#region src/cache/core/cache.ts\nvar Cache = class {\n\tstatic [entityKind] = \"Cache\";\n};\nvar NoopCache = class extends Cache {\n\tstatic [entityKind] = \"NoopCache\";\n\tstrategy() {\n\t\treturn \"all\";\n\t}\n\tasync get(_key) {}\n\tasync put(_hashedQuery, _response, _tables, _config) {}\n\tasync onMutate(_params) {}\n};\nconst strategyFor = async (query, params, queryMetadata, withCacheConfig) => {\n\tif (!queryMetadata) return { type: \"skip\" };\n\tconst { type, tables } = queryMetadata;\n\tif ((type === \"insert\" || type === \"update\" || type === \"delete\") && tables.length > 0) return {\n\t\ttype: \"invalidate\",\n\t\ttables\n\t};\n\tif (!withCacheConfig) return { type: \"skip\" };\n\tif (!withCacheConfig.enabled) return { type: \"skip\" };\n\tif (type === \"select\") return {\n\t\ttype: \"try\",\n\t\tkey: withCacheConfig.tag ?? await hashQuery(query, params),\n\t\tisTag: typeof withCacheConfig.tag !== \"undefined\",\n\t\tautoInvalidate: withCacheConfig.autoInvalidate,\n\t\ttables: queryMetadata.tables,\n\t\tconfig: withCacheConfig.config\n\t};\n\treturn { type: \"skip\" };\n};\nasync function hashQuery(sql, params) {\n\tconst dataToHash = `${sql}-${JSON.stringify(params, (_, v) => typeof v === \"bigint\" ? `${v}n` : v)}`;\n\tconst data = new TextEncoder().encode(dataToHash);\n\tconst hashBuffer = await crypto.subtle.digest(\"SHA-256\", data);\n\treturn [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n//#endregion\nexport { Cache, NoopCache, hashQuery, strategyFor };\n//# sourceMappingURL=cache.js.map",
95
+ "import { PgAsyncDatabase } from \"./db.js\";\nimport { PgBasePreparedQuery, PgSession } from \"../session.js\";\nimport { entityKind, is } from \"../../entity.js\";\nimport { hasTelemetry, tracer } from \"../../tracing.js\";\nimport { assertUnreachable } from \"../../utils.js\";\nimport { fillPlaceholders, sql } from \"../../sql/sql.js\";\nimport { DrizzleQueryError, TransactionRollbackError } from \"../../errors.js\";\nimport { getMigrationsToRun } from \"../../migrator.utils.js\";\nimport { upgradeIfNeeded } from \"../../up-migrations/pg.js\";\nimport { NoopCache, strategyFor } from \"../../cache/core/cache.js\";\n\n//#region src/pg-core/async/session.ts\nvar PgAsyncPreparedQuery = class extends PgBasePreparedQuery {\n\tstatic [entityKind] = \"PgAsyncPreparedQuery\";\n\t/** @internal */\n\tmapper;\n\tfastPath;\n\tconstructor(executor, query, mapper, mode, logger, cache, queryMetadata, cacheConfig) {\n\t\tsuper(query);\n\t\tthis.executor = executor;\n\t\tthis.mode = mode;\n\t\tthis.logger = logger;\n\t\tthis.cache = cache;\n\t\tthis.queryMetadata = queryMetadata;\n\t\tthis.cacheConfig = cacheConfig;\n\t\tthis.mapper = mapper;\n\t\tif (cache && cache.strategy() === \"all\" && cacheConfig === void 0) this.cacheConfig = {\n\t\t\tenabled: true,\n\t\t\tautoInvalidate: true\n\t\t};\n\t\tif (!this.cacheConfig?.enabled) this.cacheConfig = void 0;\n\t\tthis.fastPath = cacheConfig === void 0 && (cache === void 0 || is(cache, NoopCache)) && !hasTelemetry;\n\t}\n\tasync execute(placeholderValues = {}) {\n\t\tconst { query, logger, executor, mapper, fastPath } = this;\n\t\tif (fastPath) {\n\t\t\tconst sql = query._sql ? query._sql.join(\" \") : query.sql;\n\t\t\tconst params = query.params.length === 0 ? query.params : fillPlaceholders(query.params, placeholderValues);\n\t\t\tlogger.logQuery(sql, params);\n\t\t\tconst res = executor(params).catch((e) => {\n\t\t\t\tthrow new DrizzleQueryError(sql, params, e);\n\t\t\t});\n\t\t\tif (!mapper) return res;\n\t\t\treturn res.then((rows) => mapper(rows));\n\t\t}\n\t\treturn tracer.startActiveSpan(\"drizzle.execute\", async (span) => {\n\t\t\tconst params = fillPlaceholders(this.query.params, placeholderValues);\n\t\t\tconst sql = this.query._sql ? this.query._sql.join(\" \") : this.query.sql;\n\t\t\tconst { mapper } = this;\n\t\t\tspan?.setAttributes({\n\t\t\t\t\"drizzle.query.text\": sql,\n\t\t\t\t\"drizzle.query.params\": JSON.stringify(params)\n\t\t\t});\n\t\t\tthis.logger.logQuery(sql, params);\n\t\t\tconst query = tracer.startActiveSpan(\"drizzle.driver.execute\", async (span) => {\n\t\t\t\tspan?.setAttributes({\n\t\t\t\t\t\"drizzle.query.text\": sql,\n\t\t\t\t\t\"drizzle.query.params\": JSON.stringify(params)\n\t\t\t\t});\n\t\t\t\treturn await this.queryWithCache(sql, params, () => this.executor(params));\n\t\t\t});\n\t\t\tif (!mapper) return query;\n\t\t\treturn query.then((rows) => tracer.startActiveSpan(\"drizzle.mapResponse\", () => mapper(rows)));\n\t\t});\n\t}\n\t/** @internal */\n\tasync queryWithCache(queryString, params, query) {\n\t\tconst cacheStrat = this.cache !== void 0 && !is(this.cache, NoopCache) ? await strategyFor(queryString, params, this.queryMetadata, this.cacheConfig) : { type: \"skip\" };\n\t\tif (cacheStrat.type === \"skip\") return query().catch((e) => {\n\t\t\tthrow new DrizzleQueryError(queryString, params, e);\n\t\t});\n\t\tconst cache = this.cache;\n\t\tif (cacheStrat.type === \"invalidate\") return Promise.all([query(), cache.onMutate({ tables: cacheStrat.tables })]).then((res) => res[0]).catch((e) => {\n\t\t\tthrow new DrizzleQueryError(queryString, params, e);\n\t\t});\n\t\tif (cacheStrat.type === \"try\") {\n\t\t\tconst { tables, key, isTag, autoInvalidate, config } = cacheStrat;\n\t\t\tconst fromCache = await cache.get(key, tables, isTag, autoInvalidate);\n\t\t\tif (fromCache === void 0) {\n\t\t\t\tconst result = await query().catch((e) => {\n\t\t\t\t\tthrow new DrizzleQueryError(queryString, params, e);\n\t\t\t\t});\n\t\t\t\tawait cache.put(key, result, autoInvalidate ? tables : [], isTag, config);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\treturn fromCache;\n\t\t}\n\t\tassertUnreachable(cacheStrat);\n\t}\n};\nvar PgAsyncSession = class extends PgSession {\n\tstatic [entityKind] = \"PgAsyncSession\";\n\texecute(query) {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\t\treturn this.prepareQuery(this.dialect.sqlToQuery(query), \"raw\", false);\n\t\t\t}).execute();\n\t\t});\n\t}\n\tarrays(query) {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\t\treturn this.prepareQuery(this.dialect.sqlToQuery(query), \"arrays\", false);\n\t\t\t}).execute();\n\t\t});\n\t}\n\tobjects(query) {\n\t\treturn tracer.startActiveSpan(\"drizzle.operation\", () => {\n\t\t\treturn tracer.startActiveSpan(\"drizzle.prepareQuery\", () => {\n\t\t\t\treturn this.prepareQuery(this.dialect.sqlToQuery(query), \"objects\", false);\n\t\t\t}).execute();\n\t\t});\n\t}\n};\nvar PgAsyncTransaction = class extends PgAsyncDatabase {\n\tstatic [entityKind] = \"PgAsyncTransaction\";\n\tconstructor(dialect, session, relations, nestedIndex = 0, parseRqbJson) {\n\t\tsuper(dialect, session, relations, parseRqbJson);\n\t\tthis.nestedIndex = nestedIndex;\n\t}\n\trollback() {\n\t\tthrow new TransactionRollbackError();\n\t}\n\t/** @internal */\n\tgetTransactionConfigSQL(config) {\n\t\tconst chunks = [];\n\t\tif (config.isolationLevel) chunks.push(`isolation level ${config.isolationLevel}`);\n\t\tif (config.accessMode) chunks.push(config.accessMode);\n\t\tif (typeof config.deferrable === \"boolean\") chunks.push(config.deferrable ? \"deferrable\" : \"not deferrable\");\n\t\treturn sql.raw(chunks.join(\" \"));\n\t}\n\tsetTransaction(config) {\n\t\treturn this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`);\n\t}\n};\nasync function migrate(migrations, db, config) {\n\tconst migrationsTable = typeof config === \"string\" ? \"__drizzle_migrations\" : config.migrationsTable ?? \"__drizzle_migrations\";\n\tconst migrationsSchema = typeof config === \"string\" ? \"drizzle\" : config.migrationsSchema ?? \"drizzle\";\n\tawait db.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`);\n\tconst { newDb } = await upgradeIfNeeded(migrationsSchema, migrationsTable, db, migrations);\n\tif (newDb) {\n\t\tconst migrationTableCreate = sql`\n\t\t\tCREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (\n\t\t\t\tid SERIAL PRIMARY KEY,\n\t\t\t\thash text NOT NULL,\n\t\t\t\tcreated_at bigint,\n\t\t\t\tname text,\n\t\t\t\tapplied_at timestamp with time zone DEFAULT now()\n\t\t\t)\n\t\t`;\n\t\tawait db.execute(migrationTableCreate);\n\t}\n\tconst dbMigrations = await db.session.objects(sql`select id, hash, created_at, name from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)}`);\n\tif (typeof config === \"object\" && config.init) {\n\t\tif (dbMigrations.length) return { exitCode: \"databaseMigrations\" };\n\t\tif (migrations.length > 1) return { exitCode: \"localMigrations\" };\n\t\tconst [migration] = migrations;\n\t\tif (!migration) return;\n\t\tawait db.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (\"hash\", \"created_at\", \"name\") values(${migration.hash}, ${migration.folderMillis}, ${migration.name ?? null})`);\n\t\treturn;\n\t}\n\tconst migrationsToRun = getMigrationsToRun({\n\t\tlocalMigrations: migrations,\n\t\tdbMigrations\n\t});\n\tawait db.transaction(async (tx) => {\n\t\tfor (const migration of migrationsToRun) {\n\t\t\tfor (const stmt of migration.sql) await tx.execute(sql.raw(stmt));\n\t\t\tawait tx.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} (\"hash\", \"created_at\", \"name\") values(${migration.hash}, ${migration.folderMillis}, ${migration.name ?? null})`);\n\t\t}\n\t});\n}\n\n//#endregion\nexport { PgAsyncPreparedQuery, PgAsyncSession, PgAsyncTransaction, migrate };\n//# sourceMappingURL=session.js.map",
96
+ "import { entityKind } from \"../entity.js\";\nimport { sql } from \"../sql/sql.js\";\nimport { NoopLogger } from \"../logger.js\";\nimport { PgAsyncPreparedQuery, PgAsyncSession, PgAsyncTransaction } from \"../pg-core/async/session.js\";\nimport { NoopCache } from \"../cache/core/cache.js\";\nimport { types } from \"@electric-sql/pglite\";\n\n//#region src/pglite/session.ts\nconst parsers = {\n\t[types.TIMESTAMP]: (value) => value,\n\t[types.TIMESTAMPTZ]: (value) => value,\n\t[types.INTERVAL]: (value) => value,\n\t[types.DATE]: (value) => value,\n\t[1231]: (value) => value,\n\t[1115]: (value) => value,\n\t[1185]: (value) => value,\n\t[1187]: (value) => value,\n\t[1182]: (value) => value\n};\nvar PgliteSession = class PgliteSession extends PgAsyncSession {\n\tstatic [entityKind] = \"PgliteSession\";\n\tlogger;\n\tcache;\n\tconstructor(client, dialect, relations, options = {}) {\n\t\tsuper(dialect);\n\t\tthis.client = client;\n\t\tthis.relations = relations;\n\t\tthis.options = options;\n\t\tthis.logger = options.logger ?? new NoopLogger();\n\t\tthis.cache = options.cache ?? new NoopCache();\n\t}\n\tprepareQuery(query, mode, _name, mapper, queryMetadata, cacheConfig) {\n\t\tconst executor = async (params) => {\n\t\t\treturn this.client.query(query.sql, params, {\n\t\t\t\trowMode: mode === \"arrays\" ? \"array\" : \"object\",\n\t\t\t\tparsers\n\t\t\t}).then((r) => mode === \"raw\" ? r : r.rows);\n\t\t};\n\t\treturn new PgAsyncPreparedQuery(executor, query, mapper, mode, this.logger, this.cache, queryMetadata, cacheConfig);\n\t}\n\tasync transaction(transaction, config) {\n\t\treturn this.client.transaction(async (client) => {\n\t\t\tconst session = new PgliteSession(client, this.dialect, this.relations, this.options);\n\t\t\tconst tx = new PgliteTransaction(this.dialect, session, this.relations, void 0, false);\n\t\t\tif (config) await tx.setTransaction(config);\n\t\t\treturn transaction(tx);\n\t\t});\n\t}\n};\nvar PgliteTransaction = class PgliteTransaction extends PgAsyncTransaction {\n\tstatic [entityKind] = \"PgliteTransaction\";\n\tasync transaction(transaction) {\n\t\tconst savepointName = `sp${this.nestedIndex + 1}`;\n\t\tconst tx = new PgliteTransaction(this.dialect, this.session, this._.relations, this.nestedIndex + 1, false);\n\t\tawait tx.execute(sql.raw(`savepoint ${savepointName}`));\n\t\ttry {\n\t\t\tconst result = await transaction(tx);\n\t\t\tawait tx.execute(sql.raw(`release savepoint ${savepointName}`));\n\t\t\treturn result;\n\t\t} catch (err) {\n\t\t\tawait tx.execute(sql.raw(`rollback to savepoint ${savepointName}`));\n\t\t\tthrow err;\n\t\t}\n\t}\n};\n\n//#endregion\nexport { PgliteSession, PgliteTransaction };\n//# sourceMappingURL=session.js.map",
97
+ "import { pgliteCodecs } from \"./codecs.js\";\nimport { PgliteSession } from \"./session.js\";\nimport { entityKind } from \"../entity.js\";\nimport { jitCompatCheck } from \"../utils.js\";\nimport { DefaultLogger } from \"../logger.js\";\nimport { PgAsyncDatabase } from \"../pg-core/async/db.js\";\nimport { PgDialect } from \"../pg-core/dialect.js\";\nimport { PGlite } from \"@electric-sql/pglite\";\n\n//#region src/pglite/driver.ts\nvar PgliteDatabase = class extends PgAsyncDatabase {\n\tstatic [entityKind] = \"PgliteDatabase\";\n};\nfunction construct(client, config = {}) {\n\tconst dialect = new PgDialect({\n\t\tuseJitMappers: jitCompatCheck(config.jit),\n\t\tcodecs: config.codecs ?? pgliteCodecs\n\t});\n\tlet logger;\n\tif (config.logger === true) logger = new DefaultLogger();\n\telse if (config.logger !== false) logger = config.logger;\n\tconst relations = config.relations ?? {};\n\tconst db = new PgliteDatabase(dialect, new PgliteSession(client, dialect, relations, {\n\t\tlogger,\n\t\tcache: config.cache\n\t}), relations);\n\tdb.$client = client;\n\tdb.$cache = config.cache;\n\tif (db.$cache) db.$cache[\"invalidate\"] = config.cache?.onMutate;\n\treturn db;\n}\nfunction drizzle(...params) {\n\tif (params[0] === void 0 || typeof params[0] === \"string\") return construct(new PGlite(params[0]), params[1]);\n\tconst { connection, client, ...DrizzlePgConfig } = params[0];\n\tif (client) return construct(client, DrizzlePgConfig);\n\tif (typeof connection === \"object\") {\n\t\tconst { dataDir, ...options } = connection;\n\t\treturn construct(new PGlite(dataDir, options), DrizzlePgConfig);\n\t}\n\treturn construct(new PGlite(connection), DrizzlePgConfig);\n}\n(function(_drizzle) {\n\tfunction mock(config) {\n\t\treturn construct({}, config);\n\t}\n\t_drizzle.mock = mock;\n})(drizzle || (drizzle = {}));\n\n//#endregion\nexport { PgliteDatabase, drizzle };\n//# sourceMappingURL=driver.js.map",
98
+ "/**\n * Static, type-driven read-path apply ladder (ADR-0009 decision 3).\n *\n * We own the registry's column types ahead of time and only ever target the latest PGlite, so the\n * bulk-insert strategy for a synced table is chosen **once, statically** from its column types —\n * never by probing `information_schema` at runtime. This module is the pure, dependency-free core\n * (no registry, no Drizzle import) so it stays in the fast unit lane; {@link deriveSyncColumnTypes}\n * in `registry.ts` bridges a `SyncTableEntry`'s Drizzle columns into {@link SyncColumnType}s.\n */\n\n/** The bulk-insert path the engine uses for a fresh subscription's initial backfill. */\nexport type ApplyStrategy = \"copy\" | \"json\" | \"insert\";\n\n/** Resolved column type descriptor for the apply ladder — derived from the registry, not the DB. */\nexport interface SyncColumnType {\n /** SQL column name (not the Drizzle property key). */\n name: string;\n /**\n * The column's base SQL type from Drizzle's `getSQLType()` (e.g. `\"uuid\"`, `\"text\"`, `\"jsonb\"`,\n * `\"bigint\"`, `\"timestamp with time zone\"`). Array-ness is carried separately in {@link isArray};\n * this string is the element/base type and is usable verbatim as a `json_to_recordset` cast type\n * (with `[]` appended when `isArray`).\n */\n sqlType: string;\n /** True when the column is an array of any dimension. */\n isArray: boolean;\n}\n\n/**\n * Postgres scalar types whose JS→CSV-text rendering is unambiguous, so PGlite `COPY ... FROM`\n * round-trips them losslessly. Deliberately **conservative** (ADR-0009 decision 3): never add a\n * type here unless `COPY` truly handles it. Notably EXCLUDES timestamps/dates (format nuances),\n * `numeric` (precision/format), `bytea`, `interval`, enums, `json`/`jsonb`, and arrays — those\n * route to the `json` tier (if json-representable) or the always-correct `insert` floor.\n */\nconst COPY_SAFE_BASE_TYPES = new Set<string>([\n \"text\",\n \"varchar\",\n \"character varying\",\n \"char\",\n \"character\",\n \"bpchar\",\n \"uuid\",\n \"boolean\",\n \"bool\",\n \"smallint\",\n \"int2\",\n \"integer\",\n \"int\",\n \"int4\",\n \"bigint\",\n \"int8\",\n \"real\",\n \"float4\",\n \"double precision\",\n \"float8\",\n]);\n\n/**\n * Normalises a Drizzle `getSQLType()` string to a bare base type for whitelist comparison: strips\n * array markers and type arguments (`varchar(255)` → `varchar`, `numeric(10, 2)` → `numeric`),\n * collapses whitespace, and lowercases.\n */\nfunction normalizeBaseType(sqlType: string): string {\n return sqlType\n .replace(/\\[\\]/g, \"\")\n .replace(/\\(.*\\)/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n .toLowerCase();\n}\n\nfunction isCopySafe(column: SyncColumnType): boolean {\n return !column.isArray && COPY_SAFE_BASE_TYPES.has(normalizeBaseType(column.sqlType));\n}\n\n/**\n * `json_to_recordset` extends the COPY-safe set with arrays, `json`, and `jsonb` — viable now that\n * the latest PGlite round-trips bigint and bigint[] correctly (ADR-0009 decision 3).\n */\nfunction isJsonSafe(column: SyncColumnType): boolean {\n if (isCopySafe(column)) {\n return true;\n }\n if (column.isArray) {\n return true;\n }\n const base = normalizeBaseType(column.sqlType);\n return base === \"json\" || base === \"jsonb\";\n}\n\n/**\n * Chooses the bulk-insert strategy for a table from its column types (ADR-0009 decision 3):\n * - every column COPY-safe → `copy`;\n * - else every column COPY-safe ∪ array/json/jsonb → `json`;\n * - else → `insert` (the always-correct floor for anything not positively whitelisted).\n *\n * Pure and total: an empty column list falls to `insert`.\n */\nexport function classifyApplyStrategy(columns: readonly SyncColumnType[]): ApplyStrategy {\n if (columns.length === 0) {\n return \"insert\";\n }\n\n let allCopySafe = true;\n let allJsonSafe = true;\n\n for (const column of columns) {\n if (!isCopySafe(column)) {\n allCopySafe = false;\n }\n if (!isJsonSafe(column)) {\n allJsonSafe = false;\n }\n }\n\n if (allCopySafe) {\n return \"copy\";\n }\n if (allJsonSafe) {\n return \"json\";\n }\n return \"insert\";\n}\n",
99
+ "import { z } from \"zod\";\n\nexport const unixMicrosecondsSchema = z.string().regex(/^[0-9]+$/);\n",
100
+ "import { pgTableWithSchema } from \"./table.js\";\nimport { PgMaterializedViewConfig, PgViewConfig } from \"./view-common.js\";\nimport { QueryBuilder } from \"./query-builders/query-builder.js\";\nimport { PgViewBase } from \"./view-base.js\";\nimport { entityKind, is } from \"../entity.js\";\nimport { getTableColumns } from \"../utils.js\";\nimport { SelectionProxyHandler } from \"../selection-proxy.js\";\n\n//#region src/pg-core/view.ts\nvar DefaultViewBuilderCore = class {\n\tstatic [entityKind] = \"PgDefaultViewBuilderCore\";\n\tconstructor(name, schema) {\n\t\tthis.name = name;\n\t\tthis.schema = schema;\n\t}\n\tconfig = {};\n\twith(config) {\n\t\tthis.config.with = config;\n\t\treturn this;\n\t}\n};\nvar ViewBuilder = class extends DefaultViewBuilderCore {\n\tstatic [entityKind] = \"PgViewBuilder\";\n\tas(qb) {\n\t\tif (typeof qb === \"function\") qb = qb(new QueryBuilder());\n\t\tconst selectionProxy = new SelectionProxyHandler({\n\t\t\talias: this.name,\n\t\t\tsqlBehavior: \"error\",\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\treplaceOriginalName: true\n\t\t});\n\t\tconst aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);\n\t\treturn new Proxy(new PgView({\n\t\t\tpgConfig: this.config,\n\t\t\tconfig: {\n\t\t\t\tname: this.name,\n\t\t\t\tschema: this.schema,\n\t\t\t\tselectedFields: aliasedSelection,\n\t\t\t\tquery: qb.withoutSelectionCastCodecs().getSQL().inlineParams()\n\t\t\t}\n\t\t}), selectionProxy);\n\t}\n};\nvar ManualViewBuilder = class extends DefaultViewBuilderCore {\n\tstatic [entityKind] = \"PgManualViewBuilder\";\n\tcolumns;\n\tconstructor(name, columns, schema, casing) {\n\t\tsuper(name, schema);\n\t\tthis.columns = getTableColumns(pgTableWithSchema(name, columns, void 0, schema, casing));\n\t}\n\texisting() {\n\t\treturn new Proxy(new PgView({\n\t\t\tpgConfig: void 0,\n\t\t\tconfig: {\n\t\t\t\tname: this.name,\n\t\t\t\tschema: this.schema,\n\t\t\t\tselectedFields: this.columns,\n\t\t\t\tquery: void 0\n\t\t\t}\n\t\t}), new SelectionProxyHandler({\n\t\t\talias: this.name,\n\t\t\tsqlBehavior: \"error\",\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\treplaceOriginalName: true\n\t\t}));\n\t}\n\tas(query) {\n\t\treturn new Proxy(new PgView({\n\t\t\tpgConfig: this.config,\n\t\t\tconfig: {\n\t\t\t\tname: this.name,\n\t\t\t\tschema: this.schema,\n\t\t\t\tselectedFields: this.columns,\n\t\t\t\tquery: query.inlineParams()\n\t\t\t}\n\t\t}), new SelectionProxyHandler({\n\t\t\talias: this.name,\n\t\t\tsqlBehavior: \"error\",\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\treplaceOriginalName: true\n\t\t}));\n\t}\n};\nvar MaterializedViewBuilderCore = class {\n\tstatic [entityKind] = \"PgMaterializedViewBuilderCore\";\n\tconstructor(name, schema) {\n\t\tthis.name = name;\n\t\tthis.schema = schema;\n\t}\n\tconfig = {};\n\tusing(using) {\n\t\tthis.config.using = using;\n\t\treturn this;\n\t}\n\twith(config) {\n\t\tthis.config.with = config;\n\t\treturn this;\n\t}\n\ttablespace(tablespace) {\n\t\tthis.config.tablespace = tablespace;\n\t\treturn this;\n\t}\n\twithNoData() {\n\t\tthis.config.withNoData = true;\n\t\treturn this;\n\t}\n};\nvar MaterializedViewBuilder = class extends MaterializedViewBuilderCore {\n\tstatic [entityKind] = \"PgMaterializedViewBuilder\";\n\tas(qb) {\n\t\tif (typeof qb === \"function\") qb = qb(new QueryBuilder());\n\t\tconst selectionProxy = new SelectionProxyHandler({\n\t\t\talias: this.name,\n\t\t\tsqlBehavior: \"error\",\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\treplaceOriginalName: true\n\t\t});\n\t\tconst aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy);\n\t\treturn new Proxy(new PgMaterializedView({\n\t\t\tpgConfig: {\n\t\t\t\twith: this.config.with,\n\t\t\t\tusing: this.config.using,\n\t\t\t\ttablespace: this.config.tablespace,\n\t\t\t\twithNoData: this.config.withNoData\n\t\t\t},\n\t\t\tconfig: {\n\t\t\t\tname: this.name,\n\t\t\t\tschema: this.schema,\n\t\t\t\tselectedFields: aliasedSelection,\n\t\t\t\tquery: qb.withoutSelectionCastCodecs().getSQL().inlineParams()\n\t\t\t}\n\t\t}), selectionProxy);\n\t}\n};\nvar ManualMaterializedViewBuilder = class extends MaterializedViewBuilderCore {\n\tstatic [entityKind] = \"PgManualMaterializedViewBuilder\";\n\tcolumns;\n\tconstructor(name, columns, schema, casing) {\n\t\tsuper(name, schema);\n\t\tthis.columns = getTableColumns(pgTableWithSchema(name, columns, void 0, schema, casing));\n\t}\n\texisting() {\n\t\treturn new Proxy(new PgMaterializedView({\n\t\t\tpgConfig: {\n\t\t\t\ttablespace: this.config.tablespace,\n\t\t\t\tusing: this.config.using,\n\t\t\t\twith: this.config.with,\n\t\t\t\twithNoData: this.config.withNoData\n\t\t\t},\n\t\t\tconfig: {\n\t\t\t\tname: this.name,\n\t\t\t\tschema: this.schema,\n\t\t\t\tselectedFields: this.columns,\n\t\t\t\tquery: void 0\n\t\t\t}\n\t\t}), new SelectionProxyHandler({\n\t\t\talias: this.name,\n\t\t\tsqlBehavior: \"error\",\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\treplaceOriginalName: true\n\t\t}));\n\t}\n\tas(query) {\n\t\treturn new Proxy(new PgMaterializedView({\n\t\t\tpgConfig: {\n\t\t\t\ttablespace: this.config.tablespace,\n\t\t\t\tusing: this.config.using,\n\t\t\t\twith: this.config.with,\n\t\t\t\twithNoData: this.config.withNoData\n\t\t\t},\n\t\t\tconfig: {\n\t\t\t\tname: this.name,\n\t\t\t\tschema: this.schema,\n\t\t\t\tselectedFields: this.columns,\n\t\t\t\tquery: query.inlineParams()\n\t\t\t}\n\t\t}), new SelectionProxyHandler({\n\t\t\talias: this.name,\n\t\t\tsqlBehavior: \"error\",\n\t\t\tsqlAliasedBehavior: \"alias\",\n\t\t\treplaceOriginalName: true\n\t\t}));\n\t}\n};\nvar PgView = class extends PgViewBase {\n\tstatic [entityKind] = \"PgView\";\n\t[PgViewConfig];\n\tconstructor({ pgConfig, config }) {\n\t\tsuper(config);\n\t\tif (pgConfig) this[PgViewConfig] = { with: pgConfig.with };\n\t}\n};\nvar PgMaterializedView = class extends PgViewBase {\n\tstatic [entityKind] = \"PgMaterializedView\";\n\t[PgMaterializedViewConfig];\n\tconstructor({ pgConfig, config }) {\n\t\tsuper(config);\n\t\tthis[PgMaterializedViewConfig] = {\n\t\t\twith: pgConfig?.with,\n\t\t\tusing: pgConfig?.using,\n\t\t\ttablespace: pgConfig?.tablespace,\n\t\t\twithNoData: pgConfig?.withNoData\n\t\t};\n\t}\n};\n/** @internal */\nfunction pgViewWithSchema(name, selection, schema, casing) {\n\tif (selection) return new ManualViewBuilder(name, selection, schema, casing);\n\treturn new ViewBuilder(name, schema);\n}\n/** @internal */\nfunction pgMaterializedViewWithSchema(name, selection, schema, casing) {\n\tif (selection) return new ManualMaterializedViewBuilder(name, selection, schema, casing);\n\treturn new MaterializedViewBuilder(name, schema);\n}\n/** @internal */\nfunction pgViewWithCasing(casing) {\n\treturn ((name, columns) => pgViewWithSchema(name, columns, void 0, casing));\n}\n/** @internal */\nfunction pgMaterializedViewWithCasing(casing) {\n\treturn ((name, columns) => pgMaterializedViewWithSchema(name, columns, void 0, casing));\n}\nconst pgView = pgViewWithCasing(void 0);\nconst pgMaterializedView = pgMaterializedViewWithCasing(void 0);\nfunction isPgView(obj) {\n\treturn is(obj, PgView);\n}\nfunction isPgMaterializedView(obj) {\n\treturn is(obj, PgMaterializedView);\n}\n\n//#endregion\nexport { DefaultViewBuilderCore, ManualMaterializedViewBuilder, ManualViewBuilder, MaterializedViewBuilder, MaterializedViewBuilderCore, PgMaterializedView, PgView, ViewBuilder, isPgMaterializedView, isPgView, pgMaterializedView, pgMaterializedViewWithCasing, pgMaterializedViewWithSchema, pgView, pgViewWithCasing, pgViewWithSchema };\n//# sourceMappingURL=view.js.map",
101
+ "import { sql, type AnyColumn, type SQL } from \"drizzle-orm\";\nimport { PgDialect } from \"drizzle-orm/pg-core\";\nimport { z } from \"zod\";\n\nconst pgDialect = new PgDialect();\n\nexport type TableMode = \"readonly\" | \"writeonly\" | \"readwrite\";\n\n/**\n * The per-writable-table Conflict policy (ADR-0015): what happens to a **stale** write — one whose\n * Base server version is behind the row's current Server version at apply (an external write\n * interleaved). It is a **required** declaration on every writable table; there is no silent default\n * (registry validation rejects an undeclared writable table — the third hard-require). v1:\n *\n * - `last-write-wins` — apply the stale write anyway. This is today's implicit behaviour, but now a\n * conscious, named choice rather than silent clobbering.\n * - `reject-if-stale` — do not apply; surface the conflict so the user's edit is kept (the optimistic\n * Overlay stays, marked conflicted) and resolved as a new write.\n *\n * `field-merge` (apply only the changed fields over the current row) and `custom-resolver` (a client\n * re-resolution protocol) are reserved; the union is additive so they slot in without a breaking\n * change.\n */\nexport type ConflictPolicy = \"last-write-wins\" | \"reject-if-stale\";\n\n/** The Conflict policy values accepted in v1 (ADR-0015). Source of truth for registry validation. */\nexport const CONFLICT_POLICIES = [\"last-write-wins\", \"reject-if-stale\"] as const satisfies readonly ConflictPolicy[];\n\n/** Type guard: is `value` one of the v1 {@link ConflictPolicy} values? */\nexport function isConflictPolicy(value: unknown): value is ConflictPolicy {\n return typeof value === \"string\" && (CONFLICT_POLICIES as readonly string[]).includes(value);\n}\n\n/**\n * Subscription timing for a synced table (ADR-0021): **when** its Electric shape subscribes.\n *\n * - `eager` (default) — subscribed in the boot set, as today.\n * - `lazy` — excluded from boot; subscribed on first query-reference. With `persistent` retention,\n * first use is a one-time ignition that promotes the table to a normal eager table for subsequent\n * sessions; with `ephemeral` retention it is session-scoped.\n *\n * A property of the **consistency group**: every table sharing a `consistencyGroup` must agree, since\n * a group commits atomically on one `MultiShapeStream` and cannot be partly lazy (ADR-0021 §4).\n */\nexport type SubscriptionTiming = \"eager\" | \"lazy\";\n\n/** The {@link SubscriptionTiming} values. Source of truth for registry validation. */\nexport const SUBSCRIPTION_TIMINGS = [\"eager\", \"lazy\"] as const satisfies readonly SubscriptionTiming[];\n\n/** Type guard: is `value` a {@link SubscriptionTiming}? */\nexport function isSubscriptionTiming(value: unknown): value is SubscriptionTiming {\n return typeof value === \"string\" && (SUBSCRIPTION_TIMINGS as readonly string[]).includes(value);\n}\n\n/**\n * Retention for a synced table (ADR-0021): **whether** its local copy is durable.\n *\n * - `persistent` (default) — the durable PGlite backend with a resumable subscription-state.\n * - `ephemeral` — the table's whole per-table local cluster (read cache, overlay, journal, sequence,\n * views, reconcile trigger/function) is emitted as `TEMP`, so reads **and** writes leave no durable\n * trace. Consequence: no durable offline write queue — pair a must-not-lose write with a pessimistic\n * flush (ADR-0022).\n *\n * Like {@link SubscriptionTiming}, a property of the consistency group: every table in a group agrees.\n */\nexport type Retention = \"persistent\" | \"ephemeral\";\n\n/** The {@link Retention} values. Source of truth for registry validation. */\nexport const RETENTIONS = [\"persistent\", \"ephemeral\"] as const satisfies readonly Retention[];\n\n/** Type guard: is `value` a {@link Retention}? */\nexport function isRetention(value: unknown): value is Retention {\n return typeof value === \"string\" && (RETENTIONS as readonly string[]).includes(value);\n}\n\n/**\n * Write-mode (ADR-0022): **how** a write reaches the server — the write-side twin of {@link Retention}.\n *\n * - `optimistic` (default) — the write enters the local journal with an optimistic overlay, the UI updates\n * immediately, and the convergence loop flushes the journal as one all-or-nothing batch; the canonical\n * row returns via the sync echo. The path that has always existed.\n * - `pessimistic` — the write is **server-authoritative**: it flush-routes to an authoritative endpoint that\n * applies it in its own isolated, serialised transaction and returns a per-mutation result (accepted, or\n * rejected-with-typed-reason) **before** the UI shows success. For invariants the client cannot evaluate\n * locally — a capacity/quota/uniqueness gate enforced by a server-side rule.\n *\n * Write-mode is a property of an atomic **write-unit**, not a single table (ADR-0022 §1): a unit is uniformly\n * one mode. The *static* write-unit is the **consistency group** — so, like {@link SubscriptionTiming} and\n * {@link Retention}, every table sharing a `consistencyGroup` must agree (validated). A *dynamic* override is\n * the imperative `transaction({ mode })` block, which scopes a mode to an ad-hoc set of mutations.\n */\nexport type WriteMode = \"optimistic\" | \"pessimistic\";\n\n/** The {@link WriteMode} values. Source of truth for registry validation. */\nexport const WRITE_MODES = [\"optimistic\", \"pessimistic\"] as const satisfies readonly WriteMode[];\n\n/** Type guard: is `value` a {@link WriteMode}? */\nexport function isWriteMode(value: unknown): value is WriteMode {\n return typeof value === \"string\" && (WRITE_MODES as readonly string[]).includes(value);\n}\n\n/**\n * Minimal verified-JWT claim shape the sync layer understands. Providers may\n * attach arbitrary extra claims; those stay reachable through index access and\n * ownership claim paths (e.g. \"app_metadata.person_id\"). Parse decoded JWT\n * payloads with this schema at the auth boundary so the static type is honest.\n */\nexport const jwtClaimsSchema = z.looseObject({\n sub: z.string().optional(),\n app_metadata: z\n .looseObject({\n roles: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\nexport type JwtClaims = z.infer<typeof jwtClaimsSchema>;\n\nexport interface PrimaryKeySpec {\n columns: string[];\n}\n\nexport interface ShapeSpec {\n tableName: string;\n shapeKey: string;\n /**\n * INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the\n * shape's own `tableName`. A read PROJECTION (`defineReadProjection`) sets it to the OWNING table's\n * name so several shapes can read one physical table under distinct `shapeKey`s; the engine resolves\n * an incoming request by `shapeKey` and consults this only on egress, to build the upstream Electric\n * `table` param. `attachSyncRegistrySchema` also fills/qualifies it for schema-bound registries.\n *\n * Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or\n * wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The\n * combinator derives it from the owner; `defineSyncTable` never sets it from input.\n */\n electricTable?: string;\n rowFilter?: RowFilterSpec;\n}\n\n/** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.\n * When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.\n * `electricTable` is deliberately absent — it is a resolved/internal field, never a consumer input\n * (see {@link ShapeSpec.electricTable}); a read projection over an existing table is authored with\n * `defineReadProjection`, which derives it from the owner. */\nexport type ShapeSpecInput = Omit<ShapeSpec, \"tableName\" | \"shapeKey\" | \"electricTable\"> & {\n tableName?: string;\n shapeKey?: string;\n};\n\n/** Context available to a {@link RowTransform}: the verified claims and any extra runtime params. */\nexport interface RowTransformContext {\n claims: JwtClaims | null;\n params?: Record<string, unknown>;\n}\n\n/**\n * Per-row rewrite applied in the proxy response path (after the row filter, before\n * column omission). Receives a shape-log row's column map (keys are wire/column names)\n * and returns a possibly-rewritten one — letting the server strip a *sub-document* of a\n * jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses\n * what a static, whole-column `omitColumns` cannot.\n *\n * It runs only in the proxy's per-response path: it never alters the local PGlite schema,\n * never changes the Electric shape URL, and so never pollutes Electric's shared shape\n * cache. Return the same `row` reference to signal \"no change\".\n */\nexport type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;\n\nexport interface ClientProjectionSpec {\n syncedTable?: string;\n overlayTable?: string;\n journalTable?: string;\n omitColumns?: readonly string[];\n localPrimaryKey?: PrimaryKeySpec;\n}\n\n/**\n * Server-side projection applied in the proxy response path. This is server\n * authority, not client shape — it never alters the local PGlite schema or the\n * Electric shape URL — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).\n */\nexport interface ServerProjectionSpec {\n /**\n * Optional per-row rewrite applied in the proxy response path. Runs before column\n * omission, so it may read a column (e.g. a control flag) that\n * `clientProjection.omitColumns` then removes from the client-visible row. See\n * {@link RowTransform}.\n */\n rowTransform?: RowTransform;\n}\n\nexport interface DeferrableConstraintSpec {\n constraintName: string;\n columns: string[];\n initiallyDeferred?: boolean;\n}\n\nexport type ManagedFieldApplyOn = \"create\" | \"update\";\n\n/**\n * How the applier stamps a server-managed column (it overrides any client-sent value — the client write\n * payload omits managed fields, and the apply function re-derives them under the verified request claims):\n *\n * - `nowMicroseconds` — `clock_timestamp()` microseconds, stamped via the canonical `pgxsinkit_clock_us()`\n * DB function (installed by the utilities migration). The audit/version columns (`created_at_us`,\n * `updated_at_us`); the `updated_at_us`-on-update field is the strictly-monotonic Server version (ADR-0010).\n * - `authClaim` — a value read from the **verified JWT claims** at a JSON {@link ManagedFieldSpec.claimPath}\n * (e.g. `[\"sub\"]` for the auth subject, or `[\"app_metadata\",\"person_id\"]` for an app-minted identity). This\n * is the single claim-stamping strategy: the old `authUid` is exactly `{ claimPath: [\"sub\"], cast: \"uuid\" }`,\n * so there is one mechanism, not a `sub`-only special case beside a general one.\n */\nexport type ManagedFieldStrategy = \"nowMicroseconds\" | \"authClaim\";\n\nexport interface ManagedFieldSpec {\n column: string;\n applyOn: ManagedFieldApplyOn[];\n strategy: ManagedFieldStrategy;\n /**\n * For `strategy: \"authClaim\"` only (required there, forbidden otherwise): the JSON path into the verified\n * request claims to stamp from — `[\"sub\"]`, `[\"app_metadata\", \"person_id\"]`, etc. Each segment must be a\n * plain identifier (`[A-Za-z_][A-Za-z0-9_]*`); it is emitted into the apply-function DDL as a `jsonb #>>`\n * text-array path, so it is never a value-injection surface.\n */\n claimPath?: string[];\n /**\n * Optional SQL cast for an `authClaim` value (`jsonb #>>` yields text). Defaults to the **target column's\n * own SQL type** (so a `uuid` column casts to `uuid` with no declaration needed). Override only to force a\n * different cast; must be a plain SQL type name.\n */\n cast?: string;\n}\n\nexport interface TableGovernanceSpec {\n deferrableConstraints?: DeferrableConstraintSpec[];\n managedFields?: ManagedFieldSpec[];\n}\n\nexport interface TableSpecInput {\n mode: TableMode;\n primaryKey: PrimaryKeySpec;\n shape?: ShapeSpec;\n clientProjection?: ClientProjectionSpec;\n governance?: TableGovernanceSpec;\n /**\n * Consistency group (ADR-0009 decision 2): tables sharing a group sync on one `MultiShapeStream`\n * and commit atomically at a shared LSN frontier. Absent → the table is its own singleton group.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` table is excluded from the boot\n * subscription set and subscribed on first query-reference. See {@link SubscriptionTiming}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021). Absent → `persistent`. An `ephemeral` table's whole local cluster is emitted\n * as `TEMP` — no durable trace. See {@link Retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022). Absent → `optimistic`. A `pessimistic` consistency group is a standing\n * server-authoritative write-unit whose writes flush-route to the authoritative endpoint. See\n * {@link WriteMode}.\n */\n writeMode?: WriteMode;\n}\n\nexport interface SyncConfigInput<TTables extends Record<string, TableSpecInput> = Record<string, TableSpecInput>> {\n electricUrl: string;\n localSchema?: string;\n tables: TTables;\n}\n\nexport function getLocalSyncPrimaryKey(source: {\n primaryKey: PrimaryKeySpec;\n clientProjection?: Pick<ClientProjectionSpec, \"localPrimaryKey\">;\n}) {\n return source.clientProjection?.localPrimaryKey ?? source.primaryKey;\n}\n\nexport function getLocalSyncPrimaryKeyColumns(source: {\n primaryKey: PrimaryKeySpec;\n clientProjection?: Pick<ClientProjectionSpec, \"localPrimaryKey\">;\n}) {\n return [...getLocalSyncPrimaryKey(source).columns];\n}\n\nexport interface RowFilterSpec {\n /**\n * The row filter: returns the Electric shape `where` for this request, or `null` to bypass\n * filtering (e.g. admin access). **Prefer returning a Drizzle `SQL` fragment** built from the\n * table's columns: reference each column through {@link c} (a bare, rename-safe identifier) and\n * embed request-derived values directly — they become **bound `$n` params**, never hand-escaped\n * literals. Enum columns must be cast to text (`${c(col)}::text = 'x'`) for Electric's grammar,\n * and subqueries must be self-contained (not correlated), since Electric needs plain column refs.\n *\n * Returning a raw **string** is the escape hatch for a predicate Drizzle can't express. SECURITY:\n * a string is interpolated verbatim into the `where` — it is NOT escaped, so any request-derived\n * value you embed must be escaped/validated (`escapeSqlLiteral`) inside this function, or it is a\n * SQL-injection vector. Reach for the string form only when the Drizzle fragment cannot express it.\n */\n customWhere?: (claims: JwtClaims, params?: Record<string, unknown>) => string | SQL | null;\n /** Column projection for the shape URL (e.g. [\"id\", \"source_text\"]). */\n columns?: string[];\n /**\n * An opaque version tag for the part of this filter the fingerprint cannot see — the `customWhere`\n * body (you cannot hash a closure; only its *presence* is fingerprinted). Bump this (any new\n * string/number) whenever you change that logic so the fingerprint shifts and the local read cache\n * rebuilds + the shape subscription resets. Leaving it unchanged after a `customWhere`\n * authorization change would silently serve the stale shape.\n */\n revision?: string | number;\n}\n\n/**\n * The non-parameterized inline `where` for a filter: the string a `customWhere` returns (the raw\n * escape hatch), or `null` when there is no filter or `customWhere` returns a Drizzle `SQL` fragment\n * (which is parameterized by {@link buildRowFilterShape}, not inlined here). Most callers want\n * `buildRowFilterShape` — this is the inline-string view it composes from.\n */\nexport function buildRowFilterWhere(\n filter: RowFilterSpec,\n claims: JwtClaims | null,\n params?: Record<string, unknown>,\n): string | null {\n const custom = filter.customWhere?.(claims ?? {}, params);\n return typeof custom === \"string\" && custom ? custom : null;\n}\n\n/**\n * A **bare** (table-unqualified) quoted identifier for a Drizzle column — `\"workspace_id\"`, never\n * `\"work_items\".\"workspace_id\"`. Electric's shape `where` grammar requires *plain* column references\n * (it rejects a qualified one with \"Expected a plain column reference\"), and Drizzle qualifies columns\n * by default — so reference columns through `c()` when authoring a `customWhere` Drizzle fragment. The\n * column object keeps the reference rename-safe and existence-checked at compile time; only the bare\n * name reaches the wire. Subqueries must stay self-contained (not correlated), since bare names then\n * resolve unambiguously to each FROM — a correlated subquery would need qualification Electric rejects.\n */\nexport function c(column: AnyColumn): SQL {\n return sql`${sql.identifier(column.name)}`;\n}\n\n/**\n * The deny-all row filter: a `customWhere` returns this to make **no** rows visible (e.g. an\n * unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows\n * visible). It is a Drizzle `SQL` fragment (`false`), so it stays on the typed/parameterized path\n * with the rest of the filter rather than being a hand-written `\"1 = 0\"` string. `WHERE false`\n * matches nothing; Electric accepts it (verified) exactly as it accepts `1 = 0`.\n */\nexport const DENY_ALL: SQL = sql`false`;\n\n/**\n * The ownership shape `where` — the read-path mirror of an owner-column RLS policy: rows whose owner\n * column equals the caller's subject, {@link DENY_ALL} for an unauthenticated caller. Takes the real\n * Drizzle owner column (bare via {@link c}, rename-safe); the subject rides as a typed interpolation —\n * a bound param through `buildRowFilterShape`, or a drizzle-escaped literal when a proxy renders it\n * inline for a shape URL.\n */\nexport function buildOwnershipShapeWhere(ownerColumn: AnyColumn, subject: string | null | undefined): SQL {\n return subject == null || subject === \"\" ? DENY_ALL : sql`${c(ownerColumn)} = ${subject}`;\n}\n\n/** The parameterized shape filter the proxy sends to Electric: a `where` and its positional params. */\nexport interface RowFilterShape {\n where: string;\n params: string[];\n}\n\n/**\n * The shape filter the proxy sends to Electric: the `where` plus its positional `params` (`$1`, `$2`,\n * …). A `customWhere` returning a Drizzle `SQL` fragment is serialized here, so request-derived values\n * become **bound params** — never hand-escaped literals; a string `customWhere` is the raw escape\n * hatch (no params). Returns `null` when there is no filter (all rows visible).\n */\nexport function buildRowFilterShape(\n filter: RowFilterSpec,\n claims: JwtClaims | null,\n params?: Record<string, unknown>,\n): RowFilterShape | null {\n const custom = filter.customWhere?.(claims ?? {}, params);\n\n if (custom == null) {\n return null;\n }\n\n if (typeof custom === \"string\") {\n return custom ? { where: custom, params: [] } : null;\n }\n\n const compiled = pgDialect.sqlToQuery(custom);\n return { where: compiled.sql, params: compiled.params.map((value) => String(value)) };\n}\n",
102
+ "import { is } from \"./entity.js\";\nimport { Column } from \"./column.js\";\nimport { Table, getTableName } from \"./table.js\";\nimport { Param, SQL, View } from \"./sql/sql.js\";\nimport { Subquery } from \"./subquery.js\";\nimport { ViewBaseConfig } from \"./view-common.js\";\n\n//#region src/utils.ts\n/** @internal */\nfunction mapResultRow(columns, row, joinsNotNullableMap) {\n\tconst nullifyMap = {};\n\tconst result = columns.reduce((result, { path, field, codec, arrayDimensions }, columnIndex) => {\n\t\tlet decoder;\n\t\tif (is(field, Column)) decoder = field;\n\t\telse if (is(field, SQL)) decoder = field.decoder;\n\t\telse if (is(field, Subquery)) decoder = field._.sql.decoder;\n\t\telse decoder = field.sql.decoder;\n\t\tlet node = result;\n\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) if (pathChunkIndex < path.length - 1) {\n\t\t\tif (!(pathChunk in node)) node[pathChunk] = {};\n\t\t\tnode = node[pathChunk];\n\t\t} else {\n\t\t\tconst rawValue = row[columnIndex];\n\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(codec ? codec(rawValue, arrayDimensions) : rawValue);\n\t\t\tif (joinsNotNullableMap && is(field, Column) && path.length === 2) {\n\t\t\t\tconst objectName = path[0];\n\t\t\t\tif (!(objectName in nullifyMap)) nullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\telse if (typeof nullifyMap[objectName] === \"string\" && nullifyMap[objectName] !== getTableName(field.table)) nullifyMap[objectName] = false;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}, {});\n\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) if (typeof tableName === \"string\" && !joinsNotNullableMap[tableName]) result[objectName] = null;\n\t}\n\treturn result;\n}\n/** @internal bypass bundle-time filtering */\nconst FnConstructor = Object.getPrototypeOf(() => null).constructor;\n/** @internal */\nfunction makeJitQueryMapperInner(columns, joinsNotNullableMap = {}) {\n\tconst preFn = [];\n\tconst fn = [];\n\tfn.push(`const [ ${columns.map((_, i) => `c${i}`).join(\", \")} ] = rows[i];`);\n\tconst nullifyMap = {};\n\tconst objectIds = {};\n\tconst decodes = Array.from({ length: columns.length });\n\tfor (let idx = 0; idx < columns.length; ++idx) {\n\t\tconst { field, path, codec, arrayDimensions } = columns[idx];\n\t\tlet decoder;\n\t\tlet decoderStr;\n\t\tlet decoderFieldDestructure;\n\t\tlet isColumn = false;\n\t\tif (is(field, Column)) {\n\t\t\tisColumn = true;\n\t\t\tdecoder = field;\n\t\t\tdecoderFieldDestructure = `field: decoder${idx}`;\n\t\t} else if (is(field, SQL)) {\n\t\t\tdecoder = field.decoder;\n\t\t\tdecoderFieldDestructure = `field: { decoder: decoder${idx} }`;\n\t\t} else if (is(field, Subquery)) {\n\t\t\tdecoder = field._.sql.decoder;\n\t\t\tdecoderFieldDestructure = `field: { _: { sql: { decoder: decoder${idx} } } }`;\n\t\t} else {\n\t\t\tdecoder = field.sql.decoder;\n\t\t\tdecoderFieldDestructure = `field: { sql: { decoder: decoder${idx} } }`;\n\t\t}\n\t\tdecoderStr = `decoder${idx}.mapFromDriverValue`;\n\t\tif (decoder.mapFromDriverValue.isNoop) decoderStr = \"\";\n\t\tif (decoderStr) preFn.push(`const { ${decoderFieldDestructure}${codec ? `, codec: codec${idx}` : \"\"} } = columns[${idx}];`);\n\t\telse if (codec) preFn.push(`const { codec: codec${idx} } = columns[${idx}];`);\n\t\tconst colStr = `c${idx}`;\n\t\tlet decodedValue = colStr;\n\t\tif (codec) decodedValue = `codec${idx}(${decodedValue}, ${arrayDimensions})`;\n\t\tif (decoderStr) decodedValue = `${decoderStr}(${decodedValue})`;\n\t\tdecodes[idx] = colStr === decodedValue ? `${colStr}` : `${colStr} === null ? ${colStr} : ${decodedValue}`;\n\t\tif (path.length !== 2 || !isColumn) continue;\n\t\tif (objectIds[path[0]] === void 0) objectIds[path[0]] = [`c${idx}`];\n\t\telse objectIds[path[0]]?.push(`c${idx}`);\n\t\tconst [objectName] = path;\n\t\tconst tableName = getTableName(field.table);\n\t\tnullifyMap[objectName] = joinsNotNullableMap[tableName] ? false : typeof nullifyMap[objectName] === \"string\" ? nullifyMap[objectName] === tableName ? tableName : false : tableName;\n\t}\n\tfn.push(`mapped[i] = {`);\n\tlet currentObjectPath = [];\n\tfor (let idx = 0; idx < columns.length; ++idx) {\n\t\tconst { path } = columns[idx];\n\t\tconst jsonPath = path.map((e) => JSON.stringify(e));\n\t\tconst decodedValue = decodes[idx];\n\t\tconst objectPath = path.slice(0, -1);\n\t\tlet commonLen = 0;\n\t\twhile (commonLen < currentObjectPath.length && commonLen < objectPath.length && currentObjectPath[commonLen] === objectPath[commonLen]) commonLen++;\n\t\tfor (let d = currentObjectPath.length - 1; d >= commonLen; --d) fn.push(`${\"\t\".repeat(d + 1)}},`);\n\t\tfor (let d = commonLen; d < objectPath.length; ++d) fn.push(`${\"\t\".repeat(d + 1)}${jsonPath[d]}: ${d === 0 && objectPath.length === 1 && typeof nullifyMap[path[0]] === \"string\" ? `${objectIds[path[0]]?.map((c) => `${c} === null`).join(\" && \")} ? null : {` : \"{\"}`);\n\t\tcurrentObjectPath = objectPath;\n\t\tfn.push(`${\"\t\".repeat(path.length)}${jsonPath[path.length - 1]}: ${decodedValue},`);\n\t}\n\tfor (let d = currentObjectPath.length - 1; d >= 0; --d) fn.push(`${\"\t\".repeat(d + 1)}},`);\n\tfn.push(`};`);\n\treturn `${preFn.length ? `${preFn.join(\"\\n\t\")}\\n\\t` : \"\"}for (let i = 0; i < length; ++i) {\n\t\t${fn.join(\"\\n\t\t\")}\n\t}`;\n}\nfunction makeJitQueryMapper(columns, joinsNotNullableMap) {\n\tconst internals = `\\t\"use strict\";\n\tconst { columns } = this;\n\tconst { length } = rows;\n\tconst mapped = Array.from({ length });\n\t${makeJitQueryMapperInner(columns, joinsNotNullableMap)}\n\treturn mapped;\n\t//# sourceURL=drizzle:jit-query-mapper`;\n\treturn Object.assign(new FnConstructor(\"rows\", internals).bind({ columns }), { body: `function jitQueryMapper (rows) {\\n${internals}\\n}` });\n}\n/** @internal */\nfunction jitCompatCheck(isEnabled) {\n\tif (!isEnabled) return false;\n\ttry {\n\t\tconst res = new FnConstructor(\"input\", \"\\\"use strict\\\"; return input;\")(true);\n\t\tif (res !== true) {\n\t\t\tconsole.warn(\"Unable to use jit mappers due to incompatibility: corrupted jit function output.\\nFalling back to premade mappers.\\nError details:\");\n\t\t\tconsole.error(`Expected to receive \\`true\\`, got: ${res}`);\n\t\t}\n\t\treturn true;\n\t} catch (e) {\n\t\tconsole.warn(\"Unable to use jit mappers due to incompatibility.\\nFalling back to premade mappers.\\nError details:\");\n\t\tconsole.error(e);\n\t\treturn false;\n\t}\n}\nfunction makeDefaultQueryMapper(columns, joinsNotNullableMap) {\n\tconst interpretedData = columns.map(({ field, codec, arrayDimensions, path }) => {\n\t\tlet processNullifyMap;\n\t\tlet decoderSrc;\n\t\tif (is(field, Column)) {\n\t\t\tdecoderSrc = field;\n\t\t\tif (joinsNotNullableMap && path.length === 2) {\n\t\t\t\tconst objectName = path[0];\n\t\t\t\tprocessNullifyMap = (nullifyMap, value) => {\n\t\t\t\t\tif (!(objectName in nullifyMap)) nullifyMap[objectName] = value === null ? getTableName(field.table) : false;\n\t\t\t\t\telse if (typeof nullifyMap[objectName] === \"string\" && nullifyMap[objectName] !== getTableName(field.table)) nullifyMap[objectName] = false;\n\t\t\t\t};\n\t\t\t}\n\t\t} else if (is(field, SQL)) decoderSrc = field.decoder;\n\t\telse if (is(field, Subquery)) decoderSrc = field._.sql.decoder;\n\t\telse decoderSrc = field.sql.decoder;\n\t\tlet decoder;\n\t\tif (decoderSrc.mapFromDriverValue.isNoop) decoder = codec ? (v) => codec(v, arrayDimensions) : void 0;\n\t\telse decoder = codec ? (v) => decoderSrc.mapFromDriverValue(codec(v, arrayDimensions)) : (v) => decoderSrc.mapFromDriverValue(v);\n\t\treturn [decoder, processNullifyMap];\n\t});\n\treturn ((rows) => rows.map((row) => {\n\t\tconst nullifyMap = {};\n\t\tconst result = columns.reduce((result, { path }, columnIndex) => {\n\t\t\tlet node = result;\n\t\t\tfor (const [pathChunkIndex, pathChunk] of path.entries()) if (pathChunkIndex < path.length - 1) {\n\t\t\t\tif (!(pathChunk in node)) node[pathChunk] = {};\n\t\t\t\tnode = node[pathChunk];\n\t\t\t} else {\n\t\t\t\tconst [decoder, processNullifyMap] = interpretedData[columnIndex];\n\t\t\t\tconst rawValue = row[columnIndex];\n\t\t\t\tconst value = node[pathChunk] = rawValue === null ? null : decoder ? decoder(rawValue) : rawValue;\n\t\t\t\tprocessNullifyMap?.(nullifyMap, value);\n\t\t\t}\n\t\t\treturn result;\n\t\t}, {});\n\t\tif (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) {\n\t\t\tfor (const [objectName, tableName] of Object.entries(nullifyMap)) if (typeof tableName === \"string\" && !joinsNotNullableMap[tableName]) result[objectName] = null;\n\t\t}\n\t\treturn result;\n\t}));\n}\nfunction make$ReturningResponseMapper(returningIds, generatedIds) {\n\tif (!returningIds) return;\n\treturn ({ insertId, affectedRows }) => {\n\t\tconst returningResponse = [];\n\t\tlet j = 0;\n\t\tfor (let i = insertId; i < insertId + affectedRows; i++) {\n\t\t\tfor (const column of returningIds) {\n\t\t\t\tconst key = returningIds[0].path[0];\n\t\t\t\tif (is(column.field, Column)) {\n\t\t\t\t\tif (column.field.primary && column.field.autoIncrement) returningResponse.push({ [key]: i });\n\t\t\t\t\tif (column.field.defaultFn && generatedIds) returningResponse.push({ [key]: generatedIds[j][key] });\n\t\t\t\t}\n\t\t\t}\n\t\t\tj++;\n\t\t}\n\t\treturn returningResponse;\n\t};\n}\n/** @internal */\nfunction orderSelectedFields(fields, pathPrefix, codecs) {\n\treturn Object.entries(fields).reduce((result, [name, field]) => {\n\t\tif (typeof name !== \"string\") return result;\n\t\tconst newPath = pathPrefix ? [...pathPrefix, name] : [name];\n\t\tif (is(field, Column)) result.push({\n\t\t\tpath: newPath,\n\t\t\tfield,\n\t\t\tcodec: codecs?.get(field, \"normalize\"),\n\t\t\tarrayDimensions: field.dimensions,\n\t\t\tcolumn: field\n\t\t});\n\t\telse if (is(field, SQL) || is(field, SQL.Aliased)) {\n\t\t\tconst col = getColumnFromDecoder(field);\n\t\t\tresult.push(col ? {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield,\n\t\t\t\tcodec: codecs?.get(col, \"normalize\"),\n\t\t\t\tarrayDimensions: col.dimensions,\n\t\t\t\tcolumn: col\n\t\t\t} : {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield\n\t\t\t});\n\t\t} else if (is(field, Subquery)) {\n\t\t\tlet column;\n\t\t\tconst entry = Object.values(field._.selectedFields)[0];\n\t\t\tlet fieldDecoder;\n\t\t\tif (is(entry, Column)) {\n\t\t\t\tcolumn = entry;\n\t\t\t\tfieldDecoder = entry;\n\t\t\t} else if (is(entry, SQL)) {\n\t\t\t\tcolumn = getColumnFromDecoder(entry);\n\t\t\t\tfieldDecoder = entry.decoder;\n\t\t\t} else {\n\t\t\t\tcolumn = getColumnFromDecoder(entry);\n\t\t\t\tfieldDecoder = entry.sql.decoder;\n\t\t\t}\n\t\t\tif (fieldDecoder) field._.sql.decoder = fieldDecoder;\n\t\t\tresult.push(column ? {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield,\n\t\t\t\tcodec: codecs?.get(column, \"normalize\"),\n\t\t\t\tarrayDimensions: column.dimensions,\n\t\t\t\tcolumn\n\t\t\t} : {\n\t\t\t\tpath: newPath,\n\t\t\t\tfield\n\t\t\t});\n\t\t} else if (is(field, Table)) result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath, codecs));\n\t\telse result.push(...orderSelectedFields(field, newPath, codecs));\n\t\treturn result;\n\t}, []);\n}\nfunction getColumnFromDecoder(source) {\n\tconst query = source.getSQL();\n\tif (is(query.decoder, Column)) return query.decoder;\n}\nfunction haveSameKeys(left, right) {\n\tconst leftKeys = Object.keys(left);\n\tconst rightKeys = Object.keys(right);\n\tif (leftKeys.length !== rightKeys.length) return false;\n\tfor (const [index, key] of leftKeys.entries()) if (key !== rightKeys[index]) return false;\n\treturn true;\n}\n/** @internal */\nfunction mapUpdateSet(table, values) {\n\tconst entries = Object.entries(values).filter(([, value]) => value !== void 0).map(([key, value]) => {\n\t\tif (is(value, SQL) || is(value, Column)) return [key, value];\n\t\telse return [key, new Param(value, table[Table.Symbol.Columns][key])];\n\t});\n\tif (entries.length === 0) throw new Error(\"No values to set\");\n\treturn Object.fromEntries(entries);\n}\n/** @internal */\nfunction applyMixins(baseClass, extendedClasses) {\n\tfor (const extendedClass of extendedClasses) for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) {\n\t\tif (name === \"constructor\") continue;\n\t\tObject.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null));\n\t}\n}\n/**\n* @deprecated\n* Use `getColumns` instead\n*/\nfunction getTableColumns(table) {\n\treturn table[Table.Symbol.Columns];\n}\nfunction getViewSelectedFields(view) {\n\treturn view[ViewBaseConfig].selectedFields;\n}\nfunction getColumns(table) {\n\treturn is(table, Table) ? table[Table.Symbol.Columns] : is(table, View) ? table[ViewBaseConfig].selectedFields : table._.selectedFields;\n}\n/** @internal */\nfunction getTableLikeName(table) {\n\treturn is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? void 0 : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName];\n}\n/** @internal */\nfunction getColumnNameAndConfig(a, b) {\n\treturn {\n\t\tname: typeof a === \"string\" && a.length > 0 ? a : \"\",\n\t\tconfig: typeof a === \"object\" ? a : b\n\t};\n}\nfunction isConfig(data) {\n\tif (typeof data !== \"object\" || data === null) return false;\n\tif (data.constructor.name !== \"Object\") return false;\n\tif (\"logger\" in data) {\n\t\tconst type = typeof data[\"logger\"];\n\t\tif (type !== \"boolean\" && (type !== \"object\" || typeof data[\"logger\"][\"logQuery\"] !== \"function\") && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"schema\" in data) {\n\t\tconst type = typeof data[\"schema\"];\n\t\tif (type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"relations\" in data) {\n\t\tconst type = typeof data[\"relations\"];\n\t\tif (type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"connection\" in data) {\n\t\tconst type = typeof data[\"connection\"];\n\t\tif (type !== \"string\" && type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"client\" in data) {\n\t\tconst type = typeof data[\"client\"];\n\t\tif (type !== \"object\" && type !== \"function\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"jit\" in data) {\n\t\tconst type = typeof data[\"jit\"];\n\t\tif (type !== \"boolean\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (\"codecs\" in data) {\n\t\tconst type = typeof data[\"connection\"];\n\t\tif (type !== \"object\" && type !== \"undefined\") return false;\n\t\treturn true;\n\t}\n\tif (Object.keys(data).length === 0) return true;\n\treturn false;\n}\nconst textDecoder = typeof TextDecoder === \"undefined\" ? null : new TextDecoder();\nfunction assertUnreachable(_x) {\n\tthrow new Error(\"Didn't expect to get here\");\n}\nfunction isWithEnum(value) {\n\treturn (typeof value === \"object\" && value !== null || typeof value === \"function\") && \"enumValues\" in value && Array.isArray(value.enumValues) && value.enumValues.length > 0;\n}\nconst CONSTANTS = {\n\tINT8_MIN: -128,\n\tINT8_MAX: 127,\n\tINT8_UNSIGNED_MAX: 255,\n\tINT16_MIN: -32768,\n\tINT16_MAX: 32767,\n\tINT16_UNSIGNED_MAX: 65535,\n\tINT24_MIN: -8388608,\n\tINT24_MAX: 8388607,\n\tINT24_UNSIGNED_MAX: 16777215,\n\tINT32_MIN: -2147483648,\n\tINT32_MAX: 2147483647,\n\tINT32_UNSIGNED_MAX: 4294967295,\n\tINT48_MIN: -0x800000000000,\n\tINT48_MAX: 0x7fffffffffff,\n\tINT48_UNSIGNED_MAX: 0xffffffffffff,\n\tINT64_MIN: -9223372036854775808n,\n\tINT64_MAX: 9223372036854775807n,\n\tINT64_UNSIGNED_MAX: 18446744073709551615n\n};\nfunction base64ToUint8Array(base64) {\n\tif (!base64) return new Uint8Array(0);\n\tconst binary = atob(base64);\n\tconst len = binary.length;\n\tconst bytes = new Uint8Array(len);\n\tfor (let i = 0; i < len; ++i) bytes[i] = binary.charCodeAt(i);\n\treturn bytes;\n}\n\n//#endregion\nexport { CONSTANTS, FnConstructor, applyMixins, assertUnreachable, base64ToUint8Array, getColumnFromDecoder, getColumnNameAndConfig, getColumns, getTableColumns, getTableLikeName, getViewSelectedFields, haveSameKeys, isConfig, isWithEnum, jitCompatCheck, make$ReturningResponseMapper, makeDefaultQueryMapper, makeJitQueryMapper, mapResultRow, mapUpdateSet, orderSelectedFields, textDecoder };\n//# sourceMappingURL=utils.js.map",
103
+ "import type { ColumnBuilderBase, InferInsertModel, InferSelectModel } from \"drizzle-orm\";\nimport {\n bigint,\n getTableConfig,\n pgTable,\n pgView,\n type AnyPgTable,\n type PgBigInt64Builder,\n type PgBuildColumns,\n type PgBuildExtraConfigColumns,\n type PgPolicy,\n type PgTableExtraConfigValue,\n type PgTableWithColumns,\n type PgVarcharBuilder,\n type PgView,\n type PgViewWithSelection,\n type SetNotNull,\n} from \"drizzle-orm/pg-core\";\nimport type { pgSchema } from \"drizzle-orm/pg-core\";\nimport { varchar } from \"drizzle-orm/pg-core\";\nimport type { ExtractTablesWithRelations } from \"drizzle-orm/relations\";\nimport { getColumns } from \"drizzle-orm/utils\";\n\nimport { type ApplyStrategy, classifyApplyStrategy, type SyncColumnType } from \"./apply-strategy\";\nimport {\n CONFLICT_POLICIES,\n isConflictPolicy,\n isRetention,\n isSubscriptionTiming,\n isWriteMode,\n RETENTIONS,\n SUBSCRIPTION_TIMINGS,\n WRITE_MODES,\n type ClientProjectionSpec,\n type ConflictPolicy,\n type DeferrableConstraintSpec,\n type ManagedFieldApplyOn,\n type ManagedFieldSpec,\n type ManagedFieldStrategy,\n type PrimaryKeySpec,\n type Retention,\n type RowFilterSpec,\n type ServerProjectionSpec,\n type ShapeSpec,\n type ShapeSpecInput,\n type SubscriptionTiming,\n type TableGovernanceSpec as TableGovernanceSpecBase,\n type TableMode,\n type WriteMode,\n} from \"./config\";\n\ntype PgSchemaType = ReturnType<typeof pgSchema>;\n\n// PgView's parameters all default to their upper bounds, so the bare name\n// covers any pg view instance.\ntype AnyPgView = PgView;\n\ntype TableColumnsShape<TTable extends AnyPgTable> = TTable extends {\n _: {\n columns: infer TColumns;\n };\n}\n ? TColumns\n : never;\n\nexport type TableColumnKey<TTable extends AnyPgTable> = Extract<keyof TableColumnsShape<TTable>, string>;\n\nexport type DeferrableConstraintSpecForTable<TTable extends AnyPgTable> = Omit<DeferrableConstraintSpec, \"columns\"> & {\n columns: Array<TableColumnKey<TTable>>;\n};\n\nexport type ManagedFieldSpecForTable<TTable extends AnyPgTable> = Omit<ManagedFieldSpec, \"column\"> & {\n column: TableColumnKey<TTable>;\n};\n\nexport interface ResolvedManagedFieldSpecForTable<TTable extends AnyPgTable> {\n column: TableColumnKey<TTable>;\n applyOn: ManagedFieldApplyOn[];\n strategy: ManagedFieldStrategy;\n}\n\nexport type ClientProjectionSpecForTable<TTable extends AnyPgTable> = Omit<ClientProjectionSpec, \"omitColumns\"> & {\n omitColumns?: readonly TableColumnKey<TTable>[];\n};\n\nexport interface ProjectedTableColumn<TTable extends AnyPgTable = AnyPgTable> {\n propertyKey: TableColumnKey<TTable>;\n columnName: string;\n column: ReturnType<typeof getColumns<AnyPgTable>>[string];\n}\n\nexport type TableGovernanceSpecForTable<TTable extends AnyPgTable> = Omit<\n TableGovernanceSpecBase,\n \"deferrableConstraints\" | \"managedFields\"\n> & {\n deferrableConstraints?: Array<DeferrableConstraintSpecForTable<TTable>>;\n managedFields?: Array<ManagedFieldSpecForTable<TTable>>;\n};\n\ndeclare const syncTableInputGovernanceSymbol: unique symbol;\n\ntype SyncTableInputGovernanceMarker<TGovernance> = {\n [syncTableInputGovernanceSymbol]?: TGovernance;\n};\n\nexport interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTable extends AnyPgTable = TTable> {\n table: TTable;\n /**\n * Projected client-side table for PGlite use. Columns listed in\n * `clientProjection.omitColumns` (e.g. `created_by_id`) are absent from\n * both the runtime table definition and the TypeScript shape of this table.\n */\n localTable: TLocalTable;\n view?: AnyPgView;\n mode: TableMode;\n primaryKey: PrimaryKeySpec;\n shape?: ShapeSpec;\n clientProjection?: ClientProjectionSpecForTable<TTable>;\n serverProjection?: ServerProjectionSpec;\n governance?: TableGovernanceSpecForTable<TTable>;\n /**\n * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable\n * tables** (registry validation rejects an undeclared one — the third hard-require); ignored for\n * `readonly` tables (they have no write path). See {@link ConflictPolicy}.\n */\n conflictPolicy?: ConflictPolicy;\n /**\n * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced on one\n * `MultiShapeStream` and committed atomically at a shared LSN frontier, so a local reader never\n * sees one grouped table advanced past another for the same server transaction. Omitted → the\n * table is its own singleton group (independent frontier, today's behaviour). The latency cost (a\n * group advances only as fast as its slowest shape) is contained to the tables that opt in.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021): `eager` (default) | `lazy`. A `lazy` table is excluded from the\n * boot subscription set and subscribed on first query-reference. A property of the **consistency\n * group** — every table sharing a `consistencyGroup` must agree (validated). See\n * {@link SubscriptionTiming}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021): `persistent` (default) | `ephemeral`. An `ephemeral` table's whole local\n * cluster is emitted as `TEMP` — no durable trace, no durable offline write queue. A property of the\n * consistency group — every table sharing a `consistencyGroup` must agree (validated). See\n * {@link Retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. A `pessimistic` consistency group is a\n * standing server-authoritative write-unit — its writes flush-route to the authoritative endpoint and\n * the UI shows success only after the server confirms. Write-mode is a property of the **write-unit**;\n * the static write-unit is the consistency group, so every table sharing a `consistencyGroup` must agree\n * (validated). See {@link WriteMode}.\n */\n writeMode?: WriteMode;\n /**\n * True when this entry is a read PROJECTION over a table OWNED by another entry (built by\n * {@link defineReadProjection}). Such an entry owns no physical table — its `table` is the owner's,\n * and only its `localTable` + `shape` are its own — so migration/apply/RLS generation skips it and a\n * consumer's schema barrel must never export a fresh table for it. Absent → the entry owns its table.\n */\n readProjection?: boolean;\n /**\n * The column-builder factory that produced this entry's table (set by {@link defineSyncTable}).\n * Retained so {@link defineReadProjection} can reuse the owner's column definitions to build a typed\n * column subset without restating them, AND — since ADR-0029 P1 — so the client can derive every\n * synced-table object (the local synced read cache, overlay, journal) via\n * `getSyncedLocalTable` → `projectedColumnBuilders`. It is therefore read-derivation machinery, not a\n * write handle: it is carried through every projection ({@link asReadonly}, `withRetention`,\n * `defineReadProjection`), NOT fingerprinted (functions are invisible to the read-contract hash), and\n * required on every registered entry — `defineSyncRegistry`/`validateSyncTableEntry` reject a\n * hand-assembled entry that lacks it, since the client hard-requires it at boot.\n */\n makeColumns?: () => Record<string, ColumnBuilderBase>;\n}\n\n/** Column property key names from a `makeColumns` factory function. */\ntype ColumnKeys<TColumns extends Record<string, ColumnBuilderBase>> = keyof TColumns & string;\n\ntype ProjectedColumnsShape<\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = ColumnKeys<TColumns> extends TOmittedColumns[number] ? TColumns : Omit<TColumns, TOmittedColumns[number]>;\n\n// Explicit shapes for the projected local table and the read-model view.\n// Their drizzle-inferred types cannot survive declaration emit: the printer\n// reproduces pgTable/pgView internals as `PgBuildColumn<TTableName, ...>` with\n// drizzle's own out-of-scope generic, breaking the published .d.ts. The\n// constructed values are cast to these equivalent, printable types instead.\ntype ProjectedLocalTable<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = PgTableWithColumns<{\n name: TName;\n schema: string | undefined;\n columns: PgBuildColumns<TName, ProjectedColumnsShape<TColumns, TOmittedColumns>>;\n dialect: \"pg\";\n}>;\n\n/**\n * The local table TYPE for a {@link defineReadProjection} entry: the OWNER's already-built columns\n * (`TableColumnsShape<TOwnerTable>`) restricted to the kept keys (`TKeptKey`), under the projection's own\n * local name (`TAs`).\n *\n * Why this exists rather than reusing the inner `defineSyncTable`'s `localTable` type: a projection\n * rebuilds its columns from the owner's stashed `makeColumns`, but {@link SyncTableEntry.makeColumns} is\n * type-erased to `() => Record<string, ColumnBuilderBase>`, so a `localTable` inferred through it collapses\n * to an open index signature — forcing bracket-access + `!` in consumers. Picking directly off\n * `TOwnerTable`'s real column types restores rename-safe, per-column typing.\n *\n * Sound by construction — never an over-claim: the runtime keeps `columns ∪ primaryKey`, a SUPERSET of\n * `TKeptKey`, so every typed column exists at runtime. A primary-key column not listed in `columns` is\n * kept at runtime but omitted from the type (a safe under-claim; include it in `columns` to type it).\n */\ntype ProjectionLocalTable<\n TOwnerTable extends AnyPgTable,\n TAs extends string,\n TKeptKey extends string,\n> = PgTableWithColumns<{\n name: TAs;\n schema: string | undefined;\n columns: Pick<TableColumnsShape<TOwnerTable>, TKeptKey & keyof TableColumnsShape<TOwnerTable>>;\n dialect: \"pg\";\n}>;\n\ntype ReadModelView<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n> = PgViewWithSelection<\n `${TName}_read_model`,\n true,\n PgBuildColumns<\n `${TName}_read_model`,\n ProjectedColumnsShape<TColumns, TOmittedColumns> & {\n overlay_kind: SetNotNull<PgVarcharBuilder<[string, ...string[]]>>;\n local_updated_at_us: SetNotNull<PgBigInt64Builder>;\n }\n >\n>;\n\n/** Governance spec for `defineSyncTable` — columns are typed from `makeColumns`. */\nexport type SyncTableInputGovernance<TColumns extends Record<string, ColumnBuilderBase>> = Omit<\n TableGovernanceSpecBase,\n \"deferrableConstraints\" | \"managedFields\"\n> & {\n deferrableConstraints?: Array<Omit<DeferrableConstraintSpec, \"columns\"> & { columns: Array<ColumnKeys<TColumns>> }>;\n managedFields?: Array<Omit<ManagedFieldSpec, \"column\"> & { column: ColumnKeys<TColumns> }>;\n};\n\n/** Projection spec for `defineSyncTable` — omitColumns typed from `makeColumns`. */\nexport type SyncTableInputProjection<\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n> = Omit<ClientProjectionSpec, \"omitColumns\"> & {\n omitColumns?: TOmittedColumns;\n};\n\n/**\n * A row filter for {@link defineSyncTable}'s `shape`: either a static {@link RowFilterSpec}, or a\n * function of the table's built (typed) columns. The function form is the all-in-one way to author a\n * typed-Drizzle row filter inline — reference columns through `c(columns.x)` exactly as `extras`\n * does with its `self` argument, so `customWhere` builds parameterized Electric `where`s from real,\n * rename-safe column objects instead of hand-written column-name strings.\n */\nexport type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> =\n | RowFilterSpec\n | ((columns: PgBuildExtraConfigColumns<TColumns>) => RowFilterSpec);\n\n/** {@link ShapeSpecInput} whose `rowFilter` may also be a function of the built columns (typed by `TColumns`). */\nexport type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<\n ShapeSpecInput,\n \"rowFilter\"\n> & {\n rowFilter?: RowFilterInput<TColumns>;\n};\n\n/**\n * Input for `defineSyncTable`. Supply `tableName + makeColumns` — the Drizzle table\n * (and, for `readwrite` mode, the read-model view) are created internally.\n *\n * Access the built objects via `.table` and `.view` on the returned entry.\n */\nexport type SyncTableInput<\n TName extends string,\n TColumns extends Record<string, ColumnBuilderBase>,\n TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n> = {\n tableName: TName;\n makeColumns: () => TColumns;\n /** RLS policies (or other table extras) attached to the Postgres table. */\n policies?: PgPolicy[];\n /**\n * Extra constraints or indexes on the server-side Postgres table (unique, index, etc.).\n * Receives the built column map — same signature as `pgTable`'s third argument.\n * Not applied to `localTable`.\n */\n extras?: (self: PgBuildExtraConfigColumns<TColumns>) => PgTableExtraConfigValue[];\n /** Place the table in this schema (e.g. for perf-lab schemed tables). */\n schema?: PgSchemaType;\n /** @default \"readonly\" */\n mode?: TableMode;\n /**\n * Primary key column names. Defaults to `[\"id\"]`.\n * Use an array with multiple entries for composite keys.\n */\n primaryKey?: string[];\n shape?: ShapeSpecInputFor<TColumns>;\n clientProjection?: SyncTableInputProjection<TColumns, TOmittedColumns>;\n /** Server-side response-path projection (e.g. `rowTransform`). Server authority, not client shape. */\n serverProjection?: ServerProjectionSpec;\n governance?: SyncTableInputGovernance<TColumns>;\n /**\n * Conflict policy (ADR-0015): what happens to a stale write on this table. **Required for writable\n * tables** — `defineSyncTable`/`defineSyncRegistry` reject a writable table without one. See\n * {@link ConflictPolicy}.\n */\n conflictPolicy?: ConflictPolicy;\n /**\n * Bind this table into a consistency group (ADR-0009 decision 2): grouped tables sync on one\n * `MultiShapeStream` and commit atomically. Omit for the default singleton group. See\n * {@link SyncTableEntry.consistencyGroup}.\n */\n consistencyGroup?: string;\n /**\n * Subscription timing (ADR-0021): `eager` (default) | `lazy`. See\n * {@link SyncTableEntry.subscription}.\n */\n subscription?: SubscriptionTiming;\n /**\n * Retention (ADR-0021): `persistent` (default) | `ephemeral`. See {@link SyncTableEntry.retention}.\n */\n retention?: Retention;\n /**\n * Write-mode (ADR-0022): `optimistic` (default) | `pessimistic`. See {@link SyncTableEntry.writeMode}.\n */\n writeMode?: WriteMode;\n};\n\nexport type SyncTableRegistry = Record<string, SyncTableEntry>;\n\nexport interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {\n schema?: string;\n tables: TRegistry;\n}\n\nexport const syncRegistrySchemaSymbol = Symbol.for(\"@pgxsinkit/contracts/syncRegistrySchema\");\n\nexport type RegistryTables<TRegistry extends SyncTableRegistry> = {\n [TKey in keyof TRegistry]: TRegistry[TKey][\"table\"];\n};\n\nexport type RegistryViews<TRegistry extends SyncTableRegistry> = {\n [TKey in keyof TRegistry as TRegistry[TKey] extends { view: AnyPgView } ? TKey : never]: NonNullable<\n TRegistry[TKey][\"view\"]\n >;\n};\n\nexport type RegistryRelations<TRegistry extends SyncTableRegistry> = ExtractTablesWithRelations<\n {},\n RegistryTables<TRegistry>\n>;\n\nexport type SyncTableName<TRegistry extends SyncTableRegistry> = keyof TRegistry & string;\n\ntype GovernanceShapeForEntry<TEntry> =\n TEntry extends SyncTableInputGovernanceMarker<infer TGovernance>\n ? TGovernance\n : TEntry extends { governance?: infer TGovernance }\n ? TGovernance\n : never;\n\ntype ManagedFieldColumnKeysForOperation<TEntry, TOperation extends ManagedFieldApplyOn> =\n GovernanceShapeForEntry<TEntry> extends {\n managedFields?: ReadonlyArray<infer TField>;\n }\n ? TField extends {\n column: infer TColumn extends string;\n applyOn: ReadonlyArray<ManagedFieldApplyOn>;\n }\n ? TOperation extends TField[\"applyOn\"][number]\n ? TColumn\n : never\n : never\n : never;\n\nexport type SyncTableCreateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>\n ? Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], \"create\">>\n : never;\n\nexport type SyncTableUpdateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>\n ? Partial<Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], \"update\">>>\n : never;\n\nexport type SyncTableRecord<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =\n TRegistry[TKey] extends SyncTableEntry<infer TTable extends AnyPgTable, AnyPgTable>\n ? InferSelectModel<TTable>\n : never;\n\n/**\n * Filters a columns object, omitting keys in `omitSet`, while preserving TypeScript column types.\n * When `omitSet` is empty the original object is returned unchanged (no copy, no type loss).\n */\nfunction viewColumnsForProjection<\n TColumns extends Record<string, ColumnBuilderBase>,\n const TOmittedColumns extends readonly ColumnKeys<TColumns>[],\n>(columns: TColumns, omittedColumns: TOmittedColumns): ProjectedColumnsShape<TColumns, TOmittedColumns> {\n if (omittedColumns.length === 0) {\n return columns as ProjectedColumnsShape<TColumns, TOmittedColumns>;\n }\n\n const omitSet = new Set<string>(omittedColumns);\n return Object.fromEntries(Object.entries(columns).filter(([key]) => !omitSet.has(key))) as ProjectedColumnsShape<\n TColumns,\n TOmittedColumns\n >;\n}\n\n/**\n * Defines a sync table entry. Provide `tableName` and `makeColumns` — the Drizzle\n * `pgTable` (and, for `readwrite` mode, the `_read_model` view) are created here.\n *\n * Access the built objects via `.table` and `.view` on the returned entry.\n */\nexport function defineSyncTable<\n const TName extends string,\n const TColumns extends Record<string, ColumnBuilderBase>,\n const TOmittedColumns extends readonly ColumnKeys<TColumns>[] = [],\n const TGovernance extends SyncTableInputGovernance<TColumns> | undefined = undefined,\n>(input: Omit<SyncTableInput<TName, TColumns, TOmittedColumns>, \"governance\"> & { governance?: TGovernance }) {\n const {\n tableName,\n makeColumns,\n policies,\n extras,\n schema,\n mode,\n primaryKey,\n governance,\n clientProjection,\n serverProjection,\n shape,\n ...otherRest\n } = input;\n\n const resolvedMode: TableMode = mode ?? \"readonly\";\n const resolvedPrimaryKey: PrimaryKeySpec = { columns: primaryKey ?? [\"id\"] };\n\n const resolvedClientProjection =\n resolvedMode !== \"writeonly\" || clientProjection != null\n ? {\n ...(clientProjection ?? {}),\n syncedTable: clientProjection?.syncedTable ?? tableName,\n ...(resolvedMode === \"readwrite\"\n ? {\n overlayTable: clientProjection?.overlayTable ?? `${tableName}_overlay`,\n journalTable: clientProjection?.journalTable ?? `${tableName}_mutations`,\n }\n : {}),\n }\n : undefined;\n\n const extrasFn =\n policies || extras\n ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => [\n ...(policies ?? []),\n ...(extras ? extras(self) : []),\n ]\n : undefined;\n const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);\n\n // A function-form `shape.rowFilter` is resolved here against the built (typed) columns, so an\n // all-in-one `defineSyncTable` can author a row filter with `c(columns.x)` Drizzle fragments — the\n // same typed columns `extras` receives — instead of hand-written column-name strings. A static\n // `RowFilterSpec` passes through unchanged.\n const resolvedRowFilter: RowFilterSpec | undefined =\n typeof shape?.rowFilter === \"function\"\n ? shape.rowFilter(getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>)\n : (shape?.rowFilter ?? undefined);\n const resolvedShape: ShapeSpec | undefined =\n resolvedMode !== \"writeonly\" || shape != null\n ? {\n tableName: shape?.tableName ?? tableName,\n shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,\n // `electricTable` is never set from input (it is not in ShapeSpecInput) — an owner reads its\n // own table. It is filled by `attachSyncRegistrySchema` (schema qualification) or by\n // `defineReadProjection` (which points a projection at the owning physical table).\n ...(resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}),\n }\n : undefined;\n\n const omittedColumns = (clientProjection?.omitColumns ?? []) as TOmittedColumns;\n const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);\n const localTable = (\n schema ? schema.table(tableName, projectedCols) : pgTable(tableName, projectedCols)\n ) as ProjectedLocalTable<TName, TColumns, TOmittedColumns>;\n\n const viewColumns = viewColumnsForProjection(makeColumns(), omittedColumns);\n const view =\n resolvedMode === \"readwrite\"\n ? (pgView(`${tableName}_read_model`, {\n ...viewColumns,\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n }).existing() as ReadModelView<TName, TColumns, TOmittedColumns>)\n : undefined;\n\n const entry = {\n ...otherRest,\n mode: resolvedMode,\n primaryKey: resolvedPrimaryKey,\n ...(resolvedShape != null ? { shape: resolvedShape } : {}),\n // The input specs are typed over the builder columns map (keys of\n // TColumns); the entry fields demand specs typed over the built table.\n // The key sets are equal by construction (BuildColumns preserves keys),\n // but that equality is unprovable while TColumns is an open generic.\n ...(governance != null ? { governance: governance as TableGovernanceSpecForTable<typeof table> } : {}),\n ...(resolvedClientProjection != null\n ? { clientProjection: resolvedClientProjection as unknown as ClientProjectionSpecForTable<typeof table> }\n : {}),\n ...(serverProjection != null ? { serverProjection } : {}),\n table,\n localTable,\n ...(view != null ? { view } : {}),\n // Retained so `defineReadProjection` can reuse these column definitions for a typed subset.\n makeColumns: makeColumns as () => Record<string, ColumnBuilderBase>,\n };\n validateSyncTableEntry(entry as unknown as SyncTableEntry<AnyPgTable>);\n return entry as typeof entry & SyncTableInputGovernanceMarker<TGovernance>;\n}\n\n/**\n * Define a **read projection**: a second client shape over a table an `owner` entry already owns. The\n * projection reads the SAME physical rows under a DISTINCT local identity (`as`) and its own narrower\n * shape — a typed column subset and/or an admin/role-scoped `rowFilter` — without owning, migrating, or\n * RLS-guarding any new table. The first use is a light admin view of a heavy authoring table (titles,\n * not the jsonb), while the learner keeps reading the full table through the owner's shape.\n *\n * It is the *obvious, DRY* way to express \"another shape over this table\", versus the bare\n * `shape.electricTable` string it replaces (a footgun — config that silently un-asserts table\n * ownership):\n *\n * - **Owns nothing.** The returned entry's `table` IS `owner.table` (the same object), so there is no\n * new `pgTable` to migrate or to leak into a drizzle-kit schema barrel. Only `localTable` (named `as`)\n * and `shape` are its own. `readProjection` is set so generators skip it.\n * - **DRY columns.** `columns` is a typed subset of the owner's column keys; the local table is built by\n * filtering the owner's own column definitions (never restated), and the same subset becomes the\n * Electric `columns` allow-list so an omitted (e.g. heavy jsonb) column never crosses the wire. The\n * primary key is always kept. Omit `columns` to sync every column.\n * - **Source is derived, never named.** The physical Electric target is taken from the owner — there is\n * no consumer-facing source field to get wrong (see {@link ShapeSpec.electricTable}).\n * - **Readonly.** A projection has no write path; the engine resolves an incoming shape request by its\n * unique `shapeKey` (= `as`) and consults the derived physical target only on egress.\n *\n * The `rowFilter` callback receives the OWNER's full columns — `customWhere` runs in Electric against\n * the physical table, so it may reference a column the local subset omits. RLS for the projection's\n * reads lives on the OWNER's table (a projection adds no DDL to a table it does not own); its\n * `customWhere` must be a subset of what that RLS allows.\n *\n * The `owner` may be a `defineSyncTable` entry OR an `asReadonly` of one — an `asReadonly` projection\n * preserves the full read contract (physical table, columns, primary key) and only drops the write path,\n * so projecting off it is equivalent to projecting off its writable source. A CHAINED read projection\n * (an owner that is itself a `defineReadProjection`) is rejected, because it composes wrongly — see below.\n *\n * ### Server-side egress redaction (`serverProjection` + `serverOnlyColumns`)\n *\n * A projection may carry its own `serverProjection` (a {@link ServerProjectionSpec}, typically a\n * `rowTransform`) — resolved by the projection's `shapeKey` and run on the proxy egress path for this\n * shape only. The order on egress is **transform first, then omission**: the transform runs against the\n * fetched row, then column omission strips this projection's omitted columns (the client keep-set is\n * `columns ∪ primaryKey`) before the row reaches the client wire. This lets a \"secure window\" over a\n * keyed table stream the body while stripping the keys per row.\n *\n * `serverOnlyColumns` are owner column keys the transform must READ but that are NOT in the client shape\n * (e.g. a `keysWithheld` control flag). Such a key stays omitted from the client keep-set, yet is ADDED\n * to the Electric fetch allow-list — so it is fetched from Electric, visible to the transform, and then\n * stripped on egress by the same omission pass, never reaching the client. It requires a\n * `serverProjection.rowTransform` (a fetch no transform reads is dead weight) AND `columns` (with\n * `columns` omitted every column is already kept, so \"server-only\" is a contradiction), and must be\n * disjoint from `columns` and the primary key.\n *\n * **No inheritance — ENFORCED.** A projection does NOT inherit its owner's `serverProjection`. That is\n * deliberate: an inherited transform whose input column is absent from the projection's fetch list would\n * read `undefined` and silently fail OPEN (serving the un-redacted body) — half-protection worse than\n * none. Because a bare projection over a redacting owner would therefore egress RAW owner rows, the\n * registry no longer merely warns: when `owner.serverProjection?.rowTransform` exists, this function\n * THROWS at definition time unless the projection declares a posture. You must either declare your own\n * `serverProjection` on the projection (typically the same transform fn, plus `serverOnlyColumns` for its\n * control-flag inputs), or — only after confirming the projection's kept columns leak nothing — opt out\n * explicitly with the literal `serverProjection: \"unredacted\"`, which attaches no transform (egress raw)\n * but records that as a visible, reviewed decision at the definition site. The opt-out is meaningful only\n * where it applies: `\"unredacted\"` over an owner with NO egress `rowTransform` is itself rejected, so a\n * stale opt-out cannot silently pre-authorize a leak the day the owner grows one.\n */\nexport function defineReadProjection<\n const TOwnerTable extends AnyPgTable,\n const TOwnerLocal extends AnyPgTable,\n const TAs extends string,\n // Captures `opts.columns` as a literal tuple so the projection's local table can carry the OWNER's real\n // per-column types restricted to the kept keys. Defaults to \"all owner keys\" (its `[number]` is the full\n // key union), which is exactly the shape when `columns` is omitted — one uniform kept-key expression.\n const TColumns extends readonly TableColumnKey<TOwnerTable>[] = readonly TableColumnKey<TOwnerTable>[],\n>(\n // Two table params so an owner that uses `omitColumns` (its `table` and `localTable` types differ) is\n // accepted — `TOwnerTable` (the physical table) is what `columns`/`rowFilter` are typed against.\n owner: SyncTableEntry<TOwnerTable, TOwnerLocal>,\n opts: {\n /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */\n as: TAs;\n /** Column keys (of the owner) to sync locally + fetch from Electric. The PK is always kept. Omit → all. */\n columns?: TColumns;\n /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */\n rowFilter?: RowFilterSpec | ((columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec);\n /**\n * Server-side egress projection (ADR-0004) for THIS shape — typically a `rowTransform` that redacts a\n * sub-document of a kept column conditionally on row data. A projection does NOT inherit its owner's\n * `serverProjection` (see the docblock's no-inheritance caution): an inherited transform whose input\n * column is unfetched would fail OPEN, so inheritance is refused, not silent. When the OWNER declares\n * an egress `rowTransform`, this is therefore **required** — the registry throws at definition time\n * unless you either declare your own spec here (typically the same transform fn, plus\n * `serverOnlyColumns` for its control-flag inputs) OR opt out with the literal `\"unredacted\"`. Use\n * `\"unredacted\"` only after confirming this projection's kept columns leak nothing; it attaches NO\n * egress transform (the shape streams raw owner rows), but records that as a visible, reviewed\n * decision at the definition site. `\"unredacted\"` over a transform-less owner is itself rejected — a\n * stale opt-out would silently pre-authorize a leak the day the owner grows a transform.\n */\n serverProjection?: ServerProjectionSpec | \"unredacted\";\n /**\n * Owner column keys the `serverProjection.rowTransform` must READ but which are NOT part of the client\n * shape (e.g. a `keysWithheld` control flag). They are added to the Electric fetch allow-list so the\n * transform can see them, then stripped on egress before the client wire. Requires\n * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.\n */\n serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];\n consistencyGroup?: string;\n subscription?: SubscriptionTiming;\n retention?: Retention;\n },\n) {\n // A read projection composes off the OWNER's physical table + full columns. A chained projection (an\n // owner that is itself a read projection) would silently discard the intermediate's OWN column subset\n // and rowFilter — this derivation reads the intermediate's `table`/`makeColumns` (the physical table,\n // full columns), not its narrowed shape — so it cannot mean \"project the projection\". Reject it and\n // point at the owning defineSyncTable entry, which is the only sound base. (An `asReadonly` owner is\n // NOT a read projection and IS accepted — see the docblock.)\n if (owner.readProjection) {\n throw new Error(\n `defineReadProjection: owner \"${opts.as}\" is itself a read projection — chained projections compose ` +\n `wrongly (this derives off the owner's physical table + full columns, so the intermediate's own ` +\n `column subset and rowFilter would be silently discarded). Project off the owning defineSyncTable ` +\n `entry instead.`,\n );\n }\n\n // Defensive: every registrable entry (defineSyncTable + every transform — asReadonly / asEphemeral /\n // withRetention) now carries the column factory, so its absence means a hand-assembled owner, which\n // cannot be projected (there is nothing to derive columns from).\n const ownerMakeColumns = owner.makeColumns;\n if (!ownerMakeColumns) {\n throw new Error(\n `defineReadProjection: owner \"${getTableConfig(owner.table).name}\" has no column factory — pass an ` +\n `entry built by defineSyncTable (or an asReadonly of one), not a hand-assembled entry.`,\n );\n }\n\n const physicalTable = getTableConfig(owner.table).name;\n const allKeys = Object.keys(ownerMakeColumns());\n const pkKeys = owner.primaryKey.columns;\n const keep = opts.columns ? new Set<string>([...opts.columns, ...pkKeys]) : new Set(allKeys);\n // The subset is expressed as `omitColumns` over the OWNER's full columns, so every column-derivation\n // helper (deriveSyncColumnTypes / classifyTableApplyStrategy / getProjectedColumnNames) — which read\n // `entry.table` minus `omitColumns` — yields the right subset for the client, with `entry.table`\n // staying the owner's physical table (nothing new to migrate). The primary key is always kept.\n const omittedKeys = allKeys.filter((key) => !keep.has(key));\n\n // serverOnlyColumns — owner keys the egress rowTransform must READ but that are NOT in the client\n // keep-set. They stay omitted client-side (so local DDL/apply exclude them AND the proxy strips them on\n // egress), yet are added to the Electric fetch allow-list below so the transform can see them. Each\n // guard fails loud: a mis-declared server-only column would silently mis-fetch or fail open.\n // Fail-closed posture guard. A projection does NOT inherit its owner's egress `serverProjection`\n // (see the docblock's no-inheritance caution: an inherited transform whose input column is unfetched\n // reads `undefined` and fails OPEN — half-protection worse than none). So if the OWNER redacts on\n // egress via `serverProjection.rowTransform`, this projection would silently egress RAW owner rows\n // unless it declares a posture. We REFUSE that silence: the projection must either declare its own\n // `serverProjection` (an object spec) or opt out with the literal `serverProjection: \"unredacted\"`.\n const optServerProjection = opts.serverProjection;\n const ownerHasEgressTransform = owner.serverProjection?.rowTransform != null;\n if (optServerProjection === \"unredacted\" && !ownerHasEgressTransform) {\n // A stale \"unredacted\" over a transform-less owner would silently pre-authorize a leak if the owner\n // later grew a transform. Keep the opt-out meaningful exactly where it applies.\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverProjection: \"unredacted\", but owner ` +\n `\"${physicalTable}\" declares no egress rowTransform — the opt-out masks nothing here and would ` +\n `silently pre-authorize a leak if the owner later gains one. Remove the opt-out so it cannot mask ` +\n `a future one.`,\n );\n }\n if (ownerHasEgressTransform && optServerProjection == null) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" projects over owner \"${physicalTable}\", which declares ` +\n `an egress rowTransform — a projection does NOT inherit it, so this shape would egress RAW owner ` +\n `rows. Declare your own serverProjection (typically the same transform fn, plus serverOnlyColumns ` +\n `for its control-flag inputs) or — only after confirming the projection's kept columns leak nothing ` +\n `— opt out with serverProjection: \"unredacted\".`,\n );\n }\n // Only an object spec attaches to the entry; \"unredacted\" attaches NOTHING (egress raw, but now a\n // visible, reviewed decision at the definition site).\n const serverProjection = typeof optServerProjection === \"object\" ? optServerProjection : undefined;\n const serverOnlyColumns = opts.serverOnlyColumns ?? [];\n if (serverOnlyColumns.length > 0) {\n if (optServerProjection === \"unredacted\") {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverProjection: \"unredacted\" together ` +\n `with serverOnlyColumns — the opt-out runs no transform, so there is nothing to read them. Drop ` +\n `serverOnlyColumns, or declare a serverProjection.rowTransform that reads them.`,\n );\n }\n if (!serverProjection?.rowTransform) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverOnlyColumns but no ` +\n `serverProjection.rowTransform — a server-only fetch that no transform reads is dead weight. ` +\n `Add the rowTransform that reads them, or drop serverOnlyColumns.`,\n );\n }\n if (!opts.columns) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" declares serverOnlyColumns without columns — with ` +\n `columns omitted every column is already kept client-side, so a \"server-only\" column is a ` +\n `contradiction. Declare columns (the client subset) so some columns can be genuinely server-only.`,\n );\n }\n const clientKept = new Set<string>([...opts.columns, ...pkKeys]);\n for (const key of serverOnlyColumns) {\n if (!allKeys.includes(key)) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" serverOnlyColumns names \"${key}\", which is not a ` +\n `column of owner \"${physicalTable}\". It feeds the Electric fetch allow-list, so a typo would ` +\n `silently mis-fetch — name an existing owner column key.`,\n );\n }\n if (clientKept.has(key)) {\n throw new Error(\n `defineReadProjection: projection \"${opts.as}\" lists \"${key}\" in BOTH serverOnlyColumns and the ` +\n `client shape (columns or primary key) — it is already fetched and kept client-side, so ` +\n `declaring it server-only is contradictory. Remove it from serverOnlyColumns.`,\n );\n }\n }\n }\n\n // The local table (subset) + base shape (tableName/shapeKey = `as`) + readonly validation come from the\n // normal constructor — reusing the OWNER's column definitions, never restating them. Below we override\n // only what a projection differs in (it owns no table; it reads the owner's physical table).\n const built = defineSyncTable({\n tableName: opts.as,\n makeColumns: ownerMakeColumns,\n mode: \"readonly\",\n primaryKey: [...pkKeys],\n ...(omittedKeys.length > 0\n ? { clientProjection: { omitColumns: omittedKeys as unknown as readonly never[] } }\n : {}),\n ...(opts.consistencyGroup != null ? { consistencyGroup: opts.consistencyGroup } : {}),\n ...(opts.subscription != null ? { subscription: opts.subscription } : {}),\n ...(opts.retention != null ? { retention: opts.retention } : {}),\n });\n\n // Resolve the row filter against the OWNER's full columns (the customWhere runs in Electric on the\n // physical table, so it may reference a column the subset omits).\n const resolvedRowFilter: RowFilterSpec | undefined =\n typeof opts.rowFilter === \"function\"\n ? opts.rowFilter(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>)\n : opts.rowFilter;\n\n // When a subset is requested, set the Electric `columns` allow-list to the KEPT physical column names\n // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.\n // serverOnlyColumns are added ON TOP of the kept names: a server-only column must be FETCHED (so the\n // egress rowTransform can read it) even though it is omitted from the client keep-set — proxy omission\n // then strips it after the transform runs. Resolve key -> physical name the same way getProjectedColumns\n // does (the drizzle column's `.name`), never a hand-map. A full-width projection (no omitted keys, hence\n // no serverOnlyColumns — validated above) declares no allow-list at all.\n const ownerColumns = getColumns(owner.table) as Record<string, { name: string }>;\n const serverOnlyColumnNames = serverOnlyColumns.map((key) => ownerColumns[key]!.name);\n const allowListColumns =\n omittedKeys.length > 0 ? [...getProjectedColumnNames(built), ...serverOnlyColumnNames] : undefined;\n\n const rowFilter: RowFilterSpec | undefined =\n resolvedRowFilter != null || allowListColumns != null\n ? {\n ...(resolvedRowFilter ?? {}),\n ...(allowListColumns != null ? { columns: allowListColumns } : {}),\n }\n : undefined;\n\n const shape: ShapeSpec = {\n tableName: opts.as,\n shapeKey: opts.as,\n electricTable: physicalTable,\n ...(rowFilter != null ? { rowFilter } : {}),\n };\n\n // Point `table` at the owner's physical table and flag `readProjection` — that flag (not the absence of\n // a column factory) is what generators/appliers key on to skip owning-table work (see plpgsql-apply's\n // `!entry.readProjection` filter). The owner's `makeColumns` is KEPT (it rode in via `built`): since\n // ADR-0029 P1 the client derives a projection's OWN local synced object from it too\n // (`getSyncedLocalTable` → `projectedColumnBuilders`, with this entry's `omitColumns` applied), so a\n // subscribed read projection that dropped it would fail to boot exactly as an `asReadonly` entry did.\n // `built` was validated by defineSyncTable and only its `table` is replaced (with the owner's,\n // structurally identical role), so the result is a sound SyncTableEntry — cast past the spread's\n // exactOptional friction to a clean entry type that keeps the projected local-table shape.\n // `serverProjection` is attached HERE on the outer object (mirroring `shape`), NOT threaded through the\n // inner `defineSyncTable` call — that alone makes the proxy's shapeKey resolution find and run the\n // projection's egress transform (getRowTransformForTable → resolveEntryByShapeKey(…)?.serverProjection).\n const projection = {\n ...built,\n table: owner.table,\n shape,\n readProjection: true as const,\n ...(serverProjection != null ? { serverProjection } : {}),\n };\n // The local table carries the OWNER's real column types restricted to the kept keys (`TColumns[number]`\n // — the full owner key union when `columns` was omitted), NOT the type-erased `built.localTable` (which\n // collapses to an open index signature because it is rebuilt through the stashed `makeColumns`).\n return projection as unknown as SyncTableEntry<\n TOwnerTable,\n ProjectionLocalTable<TOwnerTable, TAs, TColumns[number]>\n > & { readProjection: true };\n}\n\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n registry: TRegistry,\n): TRegistry;\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n definition: SyncRegistryDefinition<TRegistry>,\n): TRegistry;\nexport function defineSyncRegistry<const TRegistry extends { [TKey in keyof TRegistry]: SyncTableEntry }>(\n input: TRegistry | SyncRegistryDefinition<TRegistry>,\n) {\n if (isSyncRegistryDefinition(input)) {\n for (const entry of getRegistryEntries(input.tables)) {\n validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);\n }\n validateRegistryTableUniqueness(input.tables);\n validateRegistryLifecycleGroups(input.tables);\n\n return attachSyncRegistrySchema(input.tables, input.schema);\n }\n\n for (const entry of getRegistryEntries(input)) {\n validateSyncTableEntry(entry as SyncTableEntry<AnyPgTable>);\n }\n validateRegistryTableUniqueness(input);\n validateRegistryLifecycleGroups(input);\n\n return input;\n}\n\n/** The local/shape identity an entry resolves to: its `shape.tableName` (the unique shape key a client\n * requests and the local PGlite table), falling back to the Drizzle table name when an entry has no\n * shape (a write-only table). A read projection carries a distinct `shape.tableName` (`as`) even though\n * its `table` is the owner's, so it is identified here by `as`, never by the shared physical table. */\nfunction localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.shape?.tableName ?? getTableConfig(entry.table).name;\n}\n\n/**\n * A registry must not declare the same local table twice. Every entry resolves to one local identity\n * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a\n * request by — so two entries sharing it would collide locally (one shadows the other) and make the\n * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a\n * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.electricTable`,\n * so several shapes read one physical table while their local identities stay unique. Fails closed at\n * module-eval, for every consumer.\n */\nfunction validateRegistryTableUniqueness(registry: SyncTableRegistry) {\n const declaredBy = new Map<string, string>();\n\n for (const [key, entry] of Object.entries(registry)) {\n const identity = localShapeIdentity(entry as SyncTableEntry<AnyPgTable>);\n const firstKey = declaredBy.get(identity);\n\n if (firstKey !== undefined) {\n throw new Error(\n `local table \"${identity}\" is declared by two registry entries (\"${firstKey}\" and \"${key}\"): ` +\n `each entry must map to a unique local table. A second shape over an existing physical table ` +\n `must use defineReadProjection (a distinct \"as\") rather than a second owning entry.`,\n );\n }\n\n declaredBy.set(identity, key);\n }\n}\n\n/**\n * ADR-0021 §4 / ADR-0022 §1–2: subscription timing, retention, and write-mode are properties of a\n * **consistency group**, not a single table — a group commits atomically on one `MultiShapeStream`\n * (so it cannot be partly lazy or partly ephemeral) and a consistency group *is* the static\n * write-unit (so it cannot be partly pessimistic). Reject a registry whose grouped tables disagree on\n * any of the three. Tables without a `consistencyGroup` are their own singleton group and are\n * unconstrained.\n */\nfunction validateRegistryLifecycleGroups(registry: SyncTableRegistry) {\n const groups = new Map<\n string,\n Array<{ tableName: string; subscription: SubscriptionTiming; retention: Retention; writeMode: WriteMode }>\n >();\n\n for (const entry of getRegistryEntries(registry)) {\n if (!entry.consistencyGroup) {\n continue;\n }\n\n const members = groups.get(entry.consistencyGroup) ?? [];\n members.push({\n tableName: getTableConfig(entry.table).name,\n subscription: entry.subscription ?? \"eager\",\n retention: entry.retention ?? \"persistent\",\n writeMode: entry.writeMode ?? \"optimistic\",\n });\n groups.set(entry.consistencyGroup, members);\n }\n\n for (const [group, members] of groups) {\n const subscriptions = new Set(members.map((member) => member.subscription));\n const retentions = new Set(members.map((member) => member.retention));\n const writeModes = new Set(members.map((member) => member.writeMode));\n\n if (subscriptions.size > 1 || retentions.size > 1 || writeModes.size > 1) {\n throw new Error(\n `consistency group \"${group}\" mixes lifecycle (ADR-0021 §4 / ADR-0022 §1): every table in a ` +\n `group must share one subscription, one retention, and one write-mode; got ` +\n members\n .map((member) => `${member.tableName}=${member.subscription}/${member.retention}/${member.writeMode}`)\n .join(\", \"),\n );\n }\n }\n}\n\nexport function getProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);\n\n return Object.entries(getColumns(entry.table)).flatMap(([propertyKey, column]) => {\n if (omittedColumns.has(propertyKey as TableColumnKey<TTable>)) {\n return [];\n }\n\n return [\n {\n propertyKey: propertyKey as TableColumnKey<TTable>,\n columnName: column.name,\n column,\n } satisfies ProjectedTableColumn<TTable>,\n ];\n });\n}\n\nexport function getOmittedProjectedColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n const omittedColumns = new Set(entry.clientProjection?.omitColumns ?? []);\n\n return Object.entries(getColumns(entry.table)).flatMap(([propertyKey, column]) => {\n if (!omittedColumns.has(propertyKey as TableColumnKey<TTable>)) {\n return [];\n }\n\n return [\n {\n propertyKey: propertyKey as TableColumnKey<TTable>,\n columnName: column.name,\n column,\n } satisfies ProjectedTableColumn<TTable>,\n ];\n });\n}\n\nexport function getProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return getProjectedColumns(entry).map(({ columnName }) => columnName);\n}\n\n/**\n * Resolves the {@link SyncColumnType}s of a synced table's client-projected columns from its Drizzle\n * definition (ADR-0009 decision 3) — the same `getSQLType()`/`dimensions` introspection the local\n * schema generator uses, so the apply ladder and the generated DDL can never disagree about a\n * column's type. Drives both {@link classifyTableApplyStrategy} and the engine's `json` apply cast,\n * removing the runtime `information_schema` round-trip.\n */\nexport function deriveSyncColumnTypes<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): SyncColumnType[] {\n return getProjectedColumns(entry).map(({ column, columnName }) => {\n const typedColumn = column as { getSQLType?: () => string; dimensions?: number };\n const sqlType = normalizeCastPositionType(typedColumn.getSQLType?.() ?? \"\");\n return {\n name: columnName,\n sqlType,\n isArray: (typedColumn.dimensions ?? 0) > 0,\n } satisfies SyncColumnType;\n });\n}\n\n/**\n * `serial`/`bigserial`/`smallserial` are DDL-position conveniences (an integer column plus a sequence\n * default), NOT real cast-position types: `json_to_recordset(… AS x(id serial))` and `value::serial`\n * are both invalid SQL. {@link SyncColumnType.sqlType} is contracted to be usable verbatim as a cast\n * type, so we normalise the serial family to its underlying integer type here — the single derivation\n * point — which also lets the column classify as COPY-safe rather than falling to the `insert` floor.\n *\n * Exported so any code deriving a {@link SyncColumnType} from a bare Drizzle column (e.g. test-support\n * `makeApplyTarget`, which cannot go through {@link deriveSyncColumnTypes} without a registry entry)\n * stays byte-faithful to this single normalisation rather than re-`getSQLType()`ing without it.\n */\nexport function normalizeCastPositionType(sqlType: string): string {\n switch (sqlType.trim().toLowerCase()) {\n case \"serial\":\n return \"integer\";\n case \"bigserial\":\n return \"bigint\";\n case \"smallserial\":\n return \"smallint\";\n default:\n return sqlType;\n }\n}\n\n/** The statically-chosen bulk-insert strategy for a synced table (ADR-0009 decision 3). */\nexport function classifyTableApplyStrategy<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): ApplyStrategy {\n return classifyApplyStrategy(deriveSyncColumnTypes(entry));\n}\n\nexport function getOmittedProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return getOmittedProjectedColumns(entry).map(({ columnName }) => columnName);\n}\n\nexport function getLocalSyncedTablePrimaryKeyColumns<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>) {\n return [...(entry.clientProjection?.localPrimaryKey?.columns ?? entry.primaryKey.columns)];\n}\n\n/**\n * The Server version column (ADR-0010): the `nowMicroseconds`-on-update managed field a writable\n * table stamps on every write (conventionally `updated_at_us`), made strictly monotonic by the\n * applier. Returns its **column name**, resolving the managed field's drizzle property key. Returns\n * `undefined` when none is declared — registry validation rejects that for writable tables, so the\n * convergence barrier never has to degrade.\n */\nexport function resolveServerVersionColumnName<TTable extends AnyPgTable>(\n entry: SyncTableEntry<TTable>,\n): string | undefined {\n const field = (entry.governance?.managedFields ?? []).find(\n (managed) => managed.strategy === \"nowMicroseconds\" && managed.applyOn.includes(\"update\"),\n );\n\n if (!field) {\n return undefined;\n }\n\n const columns = getColumns(entry.table);\n // `field.column` is the drizzle property key; resolve it to the underlying column name.\n const byProperty = (columns as Record<string, { name: string } | undefined>)[field.column as string];\n if (byProperty) {\n return byProperty.name;\n }\n\n // Defensive: a managed field declared by column name rather than property key.\n return Object.values(columns).find((column) => column.name === field.column)?.name;\n}\n\nexport function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry, schema?: string) {\n const normalizedSchema = normalizeSchemaName(schema);\n\n if (!normalizedSchema) {\n return registry;\n }\n\n for (const entry of Object.values(registry)) {\n const tableSchema = getTableConfig(entry.table).schema ?? \"public\";\n\n if (tableSchema !== normalizedSchema) {\n throw new Error(\n `Registry schema ${normalizedSchema} does not match table schema ${tableSchema} for ${getTableConfig(entry.table).name}`,\n );\n }\n\n if (!entry.shape) {\n continue;\n }\n\n const qualify = (name: string) => (name.includes(\".\") ? name : `${normalizedSchema}.${name}`);\n const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;\n entry.shape = {\n ...entry.shape,\n // A read projection sets electricTable to the owner's (bare) physical name; qualify it the same\n // way the owner's own target is qualified, so both shapes hit one schema-qualified table on egress.\n // An owner (no electricTable) qualifies its own tableName. An already-qualified value is left as-is.\n electricTable: entry.shape.electricTable ? qualify(entry.shape.electricTable) : qualifiedTableName,\n ...(entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}),\n };\n }\n\n Object.defineProperty(registry, syncRegistrySchemaSymbol, {\n value: normalizedSchema,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return registry;\n}\n\nexport function getSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const schema = Reflect.get(registry, syncRegistrySchemaSymbol) as unknown;\n return typeof schema === \"string\" && schema.length > 0 ? schema : \"public\";\n}\n\nfunction isSyncRegistryDefinition<TRegistry extends SyncTableRegistry>(\n input: TRegistry | SyncRegistryDefinition<TRegistry>,\n): input is SyncRegistryDefinition<TRegistry> {\n return (\n typeof input === \"object\" &&\n input !== null &&\n \"tables\" in input &&\n typeof input.tables === \"object\" &&\n input.tables !== null\n );\n}\n\nfunction normalizeSchemaName(schema: string | undefined) {\n const trimmed = schema?.trim();\n return trimmed && trimmed !== \"public\" ? trimmed : undefined;\n}\n\nfunction getRegistryEntries<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n return Object.values(registry) as Array<SyncTableEntry<AnyPgTable>>;\n}\n\nfunction validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {\n const tableName = getTableConfig(entry.table).name;\n\n // ADR-0029 P1: the client derives every synced-table object (the local synced read cache, and — for a\n // writable table — the overlay/journal) from this column-builder factory (getSyncedLocalTable →\n // projectedColumnBuilders), so it is hard-required at client boot. Promote the check to registry-build\n // time (better DX than an opaque engine-boot throw): defineSyncTable always stashes it, and every\n // projection (asReadonly / withRetention / defineReadProjection) carries it through — only a\n // hand-assembled entry can lack it, and such an entry cannot be synced.\n if (typeof entry.makeColumns !== \"function\") {\n throw new Error(\n `sync table ${tableName} has no makeColumns factory: every registered entry must be built by ` +\n `defineSyncTable (or a projection of one — asReadonly / asEphemeral / defineReadProjection), which ` +\n `stashes the column-builder factory the client requires (ADR-0029 P1) to derive its local ` +\n `synced/overlay/journal objects. Hand-assembled entries are unsupported.`,\n );\n }\n\n // ADR-0010: a writable synced table must declare a Server version — a nowMicroseconds-on-update\n // managed field (conventionally updated_at_us) the applier stamps and keeps strictly monotonic.\n // Optimistic convergence is unsound without a per-row version (the barrier would degenerate to a\n // flicker-prone key-match), so this is a hard requirement, not a silent degraded fallback.\n if (entry.mode !== \"readonly\" && resolveServerVersionColumnName(entry) === undefined) {\n throw new Error(\n `writable table ${tableName} must declare a Server version: a managed field with strategy ` +\n `\"nowMicroseconds\" and applyOn including \"update\" (conventionally updated_at_us) — ADR-0010`,\n );\n }\n\n // ADR-0015: every writable table must declare a Conflict policy — what happens to a stale write.\n // There is no silent default: silent last-write-wins is exactly the data loss the policy exists to\n // turn into a conscious per-table decision. This is the third hard-require (after the Server version\n // above and the server-PK-in-projection rule below), accepted as consistent with the footgun-averse\n // stance.\n if (entry.mode !== \"readonly\" && !isConflictPolicy(entry.conflictPolicy)) {\n throw new Error(\n `writable table ${tableName} must declare a Conflict policy (ADR-0015): conflictPolicy must be ` +\n `one of ${CONFLICT_POLICIES.join(\", \")}` +\n (entry.conflictPolicy === undefined ? \" (none was declared)\" : ` (got ${String(entry.conflictPolicy)})`),\n );\n }\n\n // ADR-0021: the lifecycle axes are optional (default eager/persistent), but a declared value must be\n // valid. Group-level uniformity (every table in a consistency group agrees) is checked at the\n // registry level in defineSyncRegistry, where the whole table set is visible.\n if (entry.subscription !== undefined && !isSubscriptionTiming(entry.subscription)) {\n throw new Error(\n `table ${tableName} has an invalid subscription (ADR-0021): must be one of ` +\n `${SUBSCRIPTION_TIMINGS.join(\", \")} (got ${String(entry.subscription)})`,\n );\n }\n if (entry.retention !== undefined && !isRetention(entry.retention)) {\n throw new Error(\n `table ${tableName} has an invalid retention (ADR-0021): must be one of ` +\n `${RETENTIONS.join(\", \")} (got ${String(entry.retention)})`,\n );\n }\n\n // ADR-0022: write-mode is optional (default optimistic), but a declared value must be valid and\n // meaningful. `pessimistic` governs the write path, which a `readonly` table does not have, so reject\n // it there. Group-level uniformity is checked at the registry level alongside the lifecycle axes.\n if (entry.writeMode !== undefined && !isWriteMode(entry.writeMode)) {\n throw new Error(\n `table ${tableName} has an invalid writeMode (ADR-0022): must be one of ` +\n `${WRITE_MODES.join(\", \")} (got ${String(entry.writeMode)})`,\n );\n }\n if (entry.writeMode === \"pessimistic\" && entry.mode === \"readonly\") {\n throw new Error(\n `readonly table ${tableName} cannot be pessimistic (ADR-0022): write-mode governs the write path, ` +\n `which a readonly table does not have. Declare writeMode only on a writable table.`,\n );\n }\n\n // The single claim-stamping strategy (ADR-0026): an `authClaim` managed field reads a value from the\n // verified request claims at a JSON path, emitted into the apply-function DDL — so the path segments\n // must be plain identifiers and any cast a plain type name (never a value-injection surface). A\n // non-authClaim field carrying claimPath/cast is an authoring slip; reject it rather than ignore it.\n for (const field of entry.governance?.managedFields ?? []) {\n if (field.strategy === \"authClaim\") {\n if (!Array.isArray(field.claimPath) || field.claimPath.length === 0) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} (strategy \"authClaim\") must declare a non-empty ` +\n `claimPath (e.g. [\"sub\"] or [\"app_metadata\",\"person_id\"]) — ADR-0026`,\n );\n }\n for (const segment of field.claimPath) {\n if (typeof segment !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(segment)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} has an invalid claimPath segment ` +\n `${JSON.stringify(segment)}: each segment must match [A-Za-z_][A-Za-z0-9_]* (it is emitted into ` +\n `the apply-function DDL)`,\n );\n }\n }\n if (field.cast !== undefined && !/^[A-Za-z_][A-Za-z0-9_ ]*$/.test(field.cast)) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} has an invalid cast ${JSON.stringify(field.cast)}: ` +\n `must be a plain SQL type name (e.g. \"uuid\", \"text\")`,\n );\n }\n } else if (field.claimPath !== undefined || field.cast !== undefined) {\n throw new Error(\n `managed field ${tableName}.${String(field.column)} declares claimPath/cast but its strategy is ` +\n `\"${field.strategy}\" — those apply only to \"authClaim\"`,\n );\n }\n }\n\n const columns = Object.entries(getColumns(entry.table)).map(([propertyKey, column]) => ({\n propertyKey,\n columnName: column.name,\n column,\n }));\n const columnsByPropertyKey = new Map(columns.map((column) => [column.propertyKey, column]));\n const columnsByColumnName = new Map(columns.map((column) => [column.columnName, column]));\n const omitColumns = entry.clientProjection?.omitColumns ?? [];\n const localPrimaryKeyColumns = entry.clientProjection?.localPrimaryKey?.columns ?? [];\n\n if (omitColumns.length === 0 && localPrimaryKeyColumns.length === 0) {\n return;\n }\n\n const unknownColumns = omitColumns.filter((propertyKey) => !columnsByPropertyKey.has(propertyKey));\n\n if (unknownColumns.length > 0) {\n throw new Error(\n `clientProjection.omitColumns contains unknown columns for ${tableName}: ${unknownColumns.join(\", \")}`,\n );\n }\n\n const unknownLocalPrimaryKeyColumns = localPrimaryKeyColumns.filter(\n (columnName) => !columnsByColumnName.has(columnName),\n );\n\n if (unknownLocalPrimaryKeyColumns.length > 0) {\n throw new Error(\n `clientProjection.localPrimaryKey contains unknown columns for ${tableName}: ${unknownLocalPrimaryKeyColumns.join(\", \")}`,\n );\n }\n\n if (entry.mode !== \"readonly\" && localPrimaryKeyColumns.length > 0) {\n throw new Error(`clientProjection.localPrimaryKey is only supported for readonly table ${tableName}`);\n }\n\n const omittedColumnsSet = new Set(omitColumns);\n const omittedLocalPrimaryKeyColumns = localPrimaryKeyColumns.filter((columnName) =>\n omittedColumnsSet.has(columnName),\n );\n\n if (omittedLocalPrimaryKeyColumns.length > 0) {\n throw new Error(\n `clientProjection.localPrimaryKey must not include omitted columns for ${tableName}: ${omittedLocalPrimaryKeyColumns.join(\", \")}`,\n );\n }\n\n const primaryKeyOmissions = omitColumns.filter((propertyKey) => {\n const column = columnsByPropertyKey.get(propertyKey);\n return column\n ? entry.primaryKey.columns.includes(column.columnName) || entry.primaryKey.columns.includes(propertyKey)\n : false;\n });\n\n if (primaryKeyOmissions.length > 0) {\n if (entry.mode === \"readonly\" && localPrimaryKeyColumns.length > 0) {\n return;\n }\n\n throw new Error(\n `clientProjection.omitColumns must not omit primary-key columns for ${tableName}: ${primaryKeyOmissions.join(\", \")}`,\n );\n }\n\n if (entry.mode === \"readonly\") {\n return;\n }\n\n const createManagedColumns = new Set(\n (entry.governance?.managedFields ?? [])\n .filter((field) => field.applyOn.includes(\"create\"))\n .map((field) => field.column),\n );\n\n const createRequiredOmissions = omitColumns.filter((propertyKey) => {\n const column = columnsByPropertyKey.get(propertyKey);\n\n if (!column) {\n return false;\n }\n\n return column.column.notNull && !column.column.hasDefault && !createManagedColumns.has(propertyKey);\n });\n\n if (createRequiredOmissions.length > 0) {\n throw new Error(\n `clientProjection.omitColumns must only omit create-safe columns for writable table ${tableName}: ${createRequiredOmissions.join(\", \")}`,\n );\n }\n}\n",
104
+ "/**\n * The single SQL identifier and literal resolver (ADR-0004).\n *\n * Every package routes identifier quoting and literal escaping through this module\n * so there is exactly one definition of \"what is a bare-safe identifier\", the\n * reserved-word set, quoting, and string-literal escaping. Previously five-plus\n * copies disagreed — one of them (the client mutation path) left reserved-word\n * table names unquoted, the same class of bug the local-schema generator had to fix.\n *\n * Note: this is the bare-quoting concern. Validation guards that merely assert a\n * value is a syntactically valid identifier (e.g. allowing uppercase, which is legal\n * but must be quoted) are a distinct concern and live with their callers.\n */\n\n// PostgreSQL fully-reserved keywords: cannot be used as a bare identifier.\nconst RESERVED_SQL_KEYWORDS = new Set([\n \"all\",\n \"analyse\",\n \"analyze\",\n \"and\",\n \"any\",\n \"array\",\n \"as\",\n \"asc\",\n \"asymmetric\",\n \"both\",\n \"case\",\n \"cast\",\n \"check\",\n \"collate\",\n \"column\",\n \"constraint\",\n \"create\",\n \"current_catalog\",\n \"current_date\",\n \"current_role\",\n \"current_time\",\n \"current_timestamp\",\n \"current_user\",\n \"default\",\n \"deferrable\",\n \"desc\",\n \"distinct\",\n \"do\",\n \"else\",\n \"end\",\n \"except\",\n \"false\",\n \"fetch\",\n \"for\",\n \"foreign\",\n \"from\",\n \"grant\",\n \"group\",\n \"having\",\n \"in\",\n \"initially\",\n \"intersect\",\n \"into\",\n \"lateral\",\n \"leading\",\n \"limit\",\n \"localtime\",\n \"localtimestamp\",\n \"not\",\n \"null\",\n \"offset\",\n \"on\",\n \"only\",\n \"or\",\n \"order\",\n \"placing\",\n \"primary\",\n \"references\",\n \"returning\",\n \"select\",\n \"session_user\",\n \"some\",\n \"symmetric\",\n \"table\",\n \"then\",\n \"to\",\n \"trailing\",\n \"true\",\n \"union\",\n \"unique\",\n \"user\",\n \"using\",\n \"variadic\",\n \"when\",\n \"where\",\n \"window\",\n \"with\",\n]);\n\n/** Always wrap an identifier in double quotes, escaping any embedded quote. */\nexport function quoteIdentifier(value: string): string {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** Escape a SQL string-literal body (`'` -> `''`); does not add the surrounding quotes. */\nexport function escapeSqlLiteral(value: string): string {\n return value.replace(/'/g, \"''\");\n}\n\n/** A SQL string literal, surrounding quotes included. */\nexport function quoteSqlLiteral(value: string): string {\n return `'${escapeSqlLiteral(value)}'`;\n}\n\n/**\n * A bare-safe identifier: a simple lowercase identifier Postgres will neither fold\n * nor misparse. Uppercase is excluded because Postgres folds an unquoted identifier\n * to lowercase, which would change its meaning. Internal to {@link maybeQuoteIdentifier}.\n */\nfunction isSimpleIdentifier(value: string): boolean {\n return /^[a-z_][a-z0-9_]*$/.test(value);\n}\n\n/**\n * Quote only when required: bare for a simple, non-reserved identifier; quoted\n * otherwise. Keeps generated SQL stable for the common case while never emitting a\n * reserved word or mixed-case name unquoted.\n */\nexport function maybeQuoteIdentifier(value: string): string {\n if (isSimpleIdentifier(value) && !RESERVED_SQL_KEYWORDS.has(value)) {\n return value;\n }\n return quoteIdentifier(value);\n}\n",
105
+ "import { z } from \"zod\";\n\nimport { unixMicrosecondsSchema } from \"./common\";\n\nexport const mutationKindSchema = z.enum([\"create\", \"update\", \"delete\"]);\n/**\n * The full Mutation-journal status machine — every status a journal row can hold, including the two\n * terminal states (`quarantined`, ADR-0006; `conflicted`, ADR-0015). Kept in lockstep with the\n * client's `MutationStatus` (packages/client/src/mutation-state.ts). Distinct from\n * {@link mutationAckStatusSchema}, the narrower *transport* subset a server ack may carry.\n */\nexport const mutationStatusSchema = z.enum([\n \"pending\",\n \"sending\",\n \"acked\",\n \"failed\",\n \"quarantined\",\n \"conflicted\",\n \"rejected\",\n]);\n/**\n * The *transport* statuses a server ack may carry. `acked` (applied), `failed` (transient, retry),\n * `conflicted` (ADR-0015 stale write — overlay KEPT, resolve as a new write), and `rejected` (ADR-0022 —\n * a business rejection from the authoritative endpoint: a server-side invariant the client cannot evaluate\n * said no, so the optimistic overlay is auto-discarded for the whole write-unit and the typed reason is\n * surfaced).\n */\nexport const mutationAckStatusSchema = z.enum([\"acked\", \"failed\", \"conflicted\", \"rejected\"]);\n\nexport const entityKeySchema = z.record(z.string().trim().min(1), z.string().trim().min(1));\n\nexport const mutationEnvelopeSchema = z\n .object({\n tableName: z.string().trim().min(1),\n entityKey: entityKeySchema,\n // INVARIANT — the public mutation surface is UUID-only by contract (this schema, the ack/rejection\n // schemas below, and the client's `mutation_id UUID` journal). The generated apply function and the\n // `operations_log` accept an OPAQUE TEXT id for one narrow case: a DIRECT server-side caller that\n // derives child envelopes (composite `${parentId}:<tag>:<n>` ids) and calls the apply function\n // itself, never crossing this HTTP route or the client journal. So a non-UUID id can never enter a\n // request that this schema validates. See packages/server/src/mutations/plpgsql-apply.ts.\n mutationId: z.uuid(),\n mutationSeq: z.number().int().nonnegative(),\n kind: mutationKindSchema,\n payload: z.unknown(),\n clientTimestampUs: unixMicrosecondsSchema,\n /**\n * The Base server version this write was authored against (ADR-0015): the row's Server version\n * at enqueue for a chain head, or its predecessor's resolved version for a chained write. The\n * applier compares the row's *current* Server version to it — `current > base` ⇒ a stale write\n * (an external write interleaved). Absent on a `create` (its conflict is a PK collision, a\n * separate concern) and on any write whose table predates the policy; absence means no stale\n * check runs.\n */\n baseServerVersion: unixMicrosecondsSchema.optional(),\n })\n .strict();\n\nexport const mutationAckSchema = z\n .object({\n tableName: z.string().trim().min(1),\n entityKey: entityKeySchema,\n // UUID-only (public-surface invariant; see mutationEnvelopeSchema). The route builds every ack from\n // the request envelope's own UUID `mutationId` — never from the apply function's returned conflict\n // rows (which are TEXT and, for a direct caller's derived child, non-UUID) — so a text id can never\n // reach this ack: the conflict map is keyed by returned text ids but only looked up by request UUIDs.\n mutationId: z.uuid(),\n mutationSeq: z.number().int().nonnegative(),\n status: mutationAckStatusSchema,\n serverUpdatedAtUs: unixMicrosecondsSchema.optional(),\n conflictReason: z.string().trim().min(1).optional(),\n /**\n * The typed reason a `rejected` ack carries (ADR-0022): the authoritative endpoint's account of why the\n * write-unit was declined (a capacity/quota/uniqueness rule — e.g. the DB constraint or trigger message).\n * Surfaced to the app when the optimistic overlay is auto-discarded.\n */\n rejectionReason: z.string().trim().min(1).optional(),\n httpStatus: z.number().int().min(100).max(599).optional(),\n })\n .strict();\n\nexport const batchMutationRequestSchema = z\n .object({\n mutations: z.array(mutationEnvelopeSchema).min(1),\n })\n .strict();\n\n/**\n * The body of an **authoritative write** (ADR-0022 §3, mechanism c): one pessimistic write-**unit** — a set\n * of co-committed mutations the server applies in its **own isolated transaction**, atomically, returning a\n * per-mutation ack. `writeUnit` is the client's unit id (the dynamic `transaction` tag, or the static\n * consistency-group key), carried for attribution. Distinct from `batchMutationRequestSchema` only in\n * *semantics* (atomic unit + a constraint exception → a clean `rejected` ack, never a whole-batch 500) and\n * its endpoint path; the mutation envelope is identical.\n */\nexport const authoritativeWriteRequestSchema = z\n .object({\n writeUnit: z.string().trim().min(1).optional(),\n mutations: z.array(mutationEnvelopeSchema).min(1),\n })\n .strict();\n\nexport const batchMutationAckSchema = z\n .object({\n acks: z.array(mutationAckSchema),\n })\n .strict();\n\n/**\n * Per-mutation attribution for a structural batch rejection. The batch write is atomic —\n * one structurally-invalid mutation rejects the whole POST with a single non-2xx — so the\n * server names the offending mutation(s) here. That lets the client quarantine exactly those\n * and keep the innocent siblings retryable, instead of dragging the whole offline queue to\n * quarantine at the shared attempt cap.\n */\nexport const mutationRejectionSchema = z\n .object({\n tableName: z.string().trim().min(1),\n // UUID-only (public-surface invariant; see mutationEnvelopeSchema). Attribution names an offending\n // request mutation, whose id this same contract already validated as a UUID.\n mutationId: z.uuid(),\n mutationSeq: z.number().int().nonnegative(),\n reason: z.string().trim().min(1),\n })\n .strict();\n\n/**\n * The body of a non-2xx batch-mutation response. `rejections` is present only when the fault\n * is attributable to specific mutations (payload validation); whole-batch faults (execution\n * 5xx, auth, malformed envelope) carry just a `message`. Unknown extra fields are stripped.\n */\nexport const batchMutationErrorSchema = z.object({\n message: z.string().optional(),\n rejections: z.array(mutationRejectionSchema).optional(),\n});\n\nexport type MutationKind = z.infer<typeof mutationKindSchema>;\nexport type MutationStatus = z.infer<typeof mutationStatusSchema>;\nexport type MutationAckStatus = z.infer<typeof mutationAckStatusSchema>;\nexport type EntityKey = z.infer<typeof entityKeySchema>;\nexport type MutationEnvelope = z.infer<typeof mutationEnvelopeSchema>;\nexport type MutationAck = z.infer<typeof mutationAckSchema>;\nexport type BatchMutationRequest = z.infer<typeof batchMutationRequestSchema>;\nexport type AuthoritativeWriteRequest = z.infer<typeof authoritativeWriteRequestSchema>;\nexport type BatchMutationAck = z.infer<typeof batchMutationAckSchema>;\nexport type MutationRejection = z.infer<typeof mutationRejectionSchema>;\nexport type BatchMutationError = z.infer<typeof batchMutationErrorSchema>;\n",
106
+ "import { sql, type SQL } from \"drizzle-orm\";\n\n/**\n * The BODY of the canonical microsecond clock — `clock_timestamp()` epoch microseconds as BIGINT.\n * This text is the SINGLE source for the `public.pgxsinkit_clock_us()` function body rendered by the\n * server's utilities migration ({@link renderPgxsinkitUtilitiesMigration}) and NOTHING else. No column\n * DEFAULT and no generated apply-function DDL may embed this expression — every surface CALLS the\n * function ({@link CLOCK_US_CALL_SQL_TEXT} / {@link clockMicrosecondsSql}), so the semantic choices\n * (`clock_timestamp()` over `now()`; `FLOOR` + `BIGINT`) live in exactly one reviewable body.\n */\nexport const NOW_MICROSECONDS_SQL_TEXT = \"CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)\";\n\n/**\n * The CALL form of the canonical microsecond clock, for string-rendering contexts (the apply-function\n * generator's PL/pgSQL literals). Deliberately `clock_timestamp()` (via the function body), never\n * `now()`/`transaction_timestamp()`: `now()` freezes at transaction start, but LWW/audit ordering of a\n * multi-row apply within one transaction needs an ADVANCING clock. The DB function is the canonical\n * home — never inline the expression at a call site.\n */\nexport const CLOCK_US_CALL_SQL_TEXT = \"public.pgxsinkit_clock_us()\";\n\n/**\n * The canonical microsecond clock as a Drizzle fragment, for `.default(...)` column positions — the\n * CALL form `public.pgxsinkit_clock_us()`, never the inline expression. Deliberately `clock_timestamp()`\n * (inside the function), never `now()`/`transaction_timestamp()`: `now()` freezes at transaction start,\n * whereas LWW/audit ordering of a multi-row apply within one transaction needs an advancing clock. The\n * DB function (installed by the utilities migration) is the canonical home; never inline the expression.\n */\nexport const clockMicrosecondsSql: SQL = sql.raw(CLOCK_US_CALL_SQL_TEXT);\n",
107
+ "import { and, eq, getTableName, or, sql, type AnyColumn, type SQL } from \"drizzle-orm\";\nimport { PgDialect, pgPolicy, type AnyPgTable, type PgRole } from \"drizzle-orm/pg-core\";\n\nimport { c, DENY_ALL, type JwtClaims } from \"./config\";\n\n// Render a typed fragment to inline-literal SQL text (CREATE POLICY DDL cannot carry `$n` binds).\n// The tier-② discipline for the text builders below: values enter as typed `${value}` interpolations\n// and drizzle owns the escaping; only the claim-extraction leaves stay raw text.\nconst textDialect = new PgDialect();\nfunction renderInlineSql(fragment: SQL): string {\n return textDialect.sqlToQuery(fragment.inlineParams()).sql;\n}\n\ntype SupabaseOwnerOrAdminPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\ntype SupabaseOwnerOrAdminPolicyShape = {\n command: SupabaseOwnerOrAdminPolicyKind;\n using: boolean;\n withCheck: boolean;\n};\n\n// Options for the raw predicate *text* builder (`buildSupabaseOwnerOrAdminPredicateSqlText`) — the\n// documented escape hatch that returns the predicate as a SQL string (for a hand-written trigger or\n// migration). It takes a column *name* because text has no column object. The native policy builder\n// below takes a real Drizzle column instead.\nexport type SupabaseOwnerOrAdminPredicateOptions = {\n ownerSqlColumn?: string;\n adminRoleName?: string;\n subjectCastType?: string;\n};\n\nexport type SupabaseOwnerOrAdminNativePoliciesOptions = {\n /** Owner column on the governed row (e.g. `authors.ownerId`). The governed table name is derived from it. */\n ownerColumn: AnyColumn;\n role: PgRole;\n /** Role value (in `app_metadata.roles`) that bypasses ownership (default \"admin\"). */\n adminRoleName?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n};\n\nconst defaultOwnerSqlColumn = \"owner_id\";\nconst defaultOwnerPropertyKey = \"ownerId\";\nconst defaultAuthenticatedRoleName = \"authenticated\";\nconst defaultAdminRoleName = \"admin\";\nconst defaultSubjectCastType = \"uuid\";\n\nconst ownerOrAdminPolicyShapes: SupabaseOwnerOrAdminPolicyShape[] = [\n {\n command: \"select\",\n using: true,\n withCheck: false,\n },\n {\n command: \"insert\",\n using: false,\n withCheck: true,\n },\n {\n command: \"update\",\n using: true,\n withCheck: true,\n },\n {\n command: \"delete\",\n using: true,\n withCheck: false,\n },\n];\n\nfunction assertIdentifier(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL identifier: ${value}`);\n }\n}\n\nfunction assertTypeName(value: string, label: string): void {\n if (!/^[A-Za-z_][A-Za-z0-9_]*(?:\\s+[A-Za-z_][A-Za-z0-9_]*)*$/.test(value)) {\n throw new Error(`${label} must be a valid SQL type name: ${value}`);\n }\n}\n\nfunction buildOwnerOrAdminPolicyName(tableName: string, command: SupabaseOwnerOrAdminPolicyKind) {\n return `${tableName}_${command}_owner_or_admin`;\n}\n\n// ---------------------------------------------------------------------------\n// Shared predicate leaves (used by both policy families). RLS is the *write* path\n// (Postgres), so columns may serialize qualified — unlike the Electric read `where`,\n// which needs bare columns. The only bits that stay raw `sql` are genuinely-Postgres\n// expressions with no Drizzle operator: the JWT-subject `(select current_setting(...)::type)`\n// and the admin-roles `EXISTS`. Literal values use `eq(col, value).inlineParams()` so the\n// value is inlined into the DDL — a bare `$n` is something `CREATE POLICY` cannot carry.\n// ---------------------------------------------------------------------------\n\n// The governed table name (for policy identifiers) derived from a built Drizzle column, so renaming\n// the table renames its policies. Columns built inside `defineSyncTable`'s `extras` callback carry\n// their `.table` — which is where these builders are meant to be called (the table object does not\n// yet exist when its own `policies:` array would be built).\nfunction tableNameForColumn(column: AnyColumn, label: string): string {\n const table = (column as { table?: AnyPgTable }).table;\n if (!table) {\n throw new Error(\n `${label} must be a built Drizzle column carrying its table — call this builder inside defineSyncTable's \\`extras\\` callback`,\n );\n }\n return getTableName(table);\n}\n\n// The JWT subject as a Postgres expression (irreducibly raw: `current_setting` + cast). Used as the\n// right-hand side of `eq(ownerColumn, subject)` — eq splices an SQL fragment verbatim (no bound\n// param), so the DDL carries the literal expression, not a `$n` CREATE POLICY cannot bind. Wrapped in\n// a scalar subquery — the Supabase RLS performance idiom: the stable `current_setting` expression is\n// evaluated once per statement (InitPlan), not once per row.\nfunction buildSubjectSql(subjectCastType: string): SQL {\n assertTypeName(subjectCastType, \"subjectCastType\");\n return sql.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);\n}\n\nfunction buildSubjectSqlText(subjectCastType: string): string {\n return `coalesce(\n nullif(current_setting('request.jwt.claim.sub', true), ''),\n (nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')\n )::${subjectCastType}`;\n}\n\n// The admin-bypass test: `app_metadata.roles` (from the JWT claims) contains `adminRoleName`. No\n// column reference and no recursion risk, so it is inlined as text (shared by the text builder and\n// the native builder). The role value enters as a typed interpolation (drizzle owns the escaping);\n// the claim-extraction body is the allowed raw leaf.\nfunction buildAdminRoleExistsSqlText(adminRoleName: string): string {\n return renderInlineSql(sql`EXISTS (\n SELECT 1\n FROM jsonb_array_elements_text(\n COALESCE(\n (\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb -> 'app_metadata' -> 'roles'\n ),\n '[]'::jsonb\n )\n ) AS assigned_role(role_name_value)\n WHERE assigned_role.role_name_value = ${adminRoleName}\n )`);\n}\n\nfunction normalizePredicateOptions(options: SupabaseOwnerOrAdminPredicateOptions = {}) {\n const ownerSqlColumn = options.ownerSqlColumn ?? defaultOwnerSqlColumn;\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subjectCastType = options.subjectCastType ?? defaultSubjectCastType;\n\n assertIdentifier(ownerSqlColumn, \"ownerSqlColumn\");\n assertTypeName(subjectCastType, \"subjectCastType\");\n\n return {\n ownerSqlColumn,\n adminRoleName,\n subjectCastType,\n };\n}\n\n/**\n * The owner-or-admin predicate as raw SQL **text** — the escape hatch for when you need the predicate\n * as a string (a hand-written trigger, a manual migration). For attaching RLS to a Drizzle table,\n * prefer `buildSupabaseOwnerOrAdminNativePolicies`, which takes the real column and is rename-tracked.\n */\nexport function buildSupabaseOwnerOrAdminPredicateSqlText(options: SupabaseOwnerOrAdminPredicateOptions = {}): string {\n const normalized = normalizePredicateOptions(options);\n\n return `\n ${normalized.ownerSqlColumn} = ${buildSubjectSqlText(normalized.subjectCastType)}\n OR ${buildAdminRoleExistsSqlText(normalized.adminRoleName)}\n`;\n}\n\n// owner-or-admin predicate built from the real Drizzle column: `eq(ownerColumn, subject)` (qualified,\n// rename-tracked) OR the raw admin-roles EXISTS (no column, no Drizzle operator). The single boolean\n// is `or(...)`.\nexport function buildSupabaseOwnerOrAdminNativePolicies(options: SupabaseOwnerOrAdminNativePoliciesOptions) {\n const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;\n const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);\n const adminExists = sql.raw(buildAdminRoleExistsSqlText(adminRoleName));\n const predicate = or(eq(options.ownerColumn, subject), adminExists)!;\n const tableName = tableNameForColumn(options.ownerColumn, \"ownerColumn\");\n\n return ownerOrAdminPolicyShapes.map((shape) =>\n pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\nexport const supabaseOwnerOrAdminDefaults = {\n ownerSqlColumn: defaultOwnerSqlColumn,\n ownerPropertyKey: defaultOwnerPropertyKey,\n authenticatedRoleName: defaultAuthenticatedRoleName,\n adminRoleName: defaultAdminRoleName,\n subjectCastType: defaultSubjectCastType,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Membership-scoped policies (generic). A row belongs to a *container* and is\n// visible/writable through membership of that container — not just ownership.\n// This is the readwrite counterpart to a membership row-filter: every member of\n// the container may read the row (fan-out to non-owners); only the owner may\n// create it (as themselves) and edit it, while a container *manager* may moderate\n// any row. Domain-agnostic: the container, membership table, and manager role are\n// all parameters.\n//\n// The container, membership, and owner references are **real Drizzle columns/tables**\n// (not name strings), so the policy tracks the schema — a column or table rename is a\n// compile error, and the governed table name is *derived* from the container column\n// (no redundant `tableName` to drift). Predicate structure is built with Drizzle\n// operators (`and`/`or`/`eq`, with `.inlineParams()` on the `'manager'` / `false` literals so\n// they inline instead of becoming a `$n` CREATE POLICY cannot carry); only the irreducibly-Postgres\n// leaves stay `sql`: the `IN (subquery)` containment (Drizzle's `inArray` cannot wrap a raw subquery)\n// and the `(select current_setting(...)::type)` JWT-subject expression (wrapped in a scalar subquery —\n// the Supabase per-statement-eval RLS perf idiom). Columns serialize qualified\n// (`\"work_items\".\"workspace_id\"`) — fine for Postgres RLS (the write path, unlike Electric's bare rule).\n// ---------------------------------------------------------------------------\n\ntype MembershipPolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nexport type SupabaseMembershipPredicateColumns = {\n /** Column on the governed row naming its container (e.g. `workItems.workspaceId`). */\n containerColumn: AnyColumn;\n /** Membership link table (e.g. the `workspace_members` table). */\n membershipTable: AnyPgTable;\n /** Container column on the membership link table (e.g. `workspaceMembers.workspaceId`). */\n membershipContainerColumn: AnyColumn;\n /** Subject (member) column on the membership link table, compared to the JWT sub. */\n membershipSubjectColumn: AnyColumn;\n /** Owner column on the governed row (e.g. `workItems.ownerId`). */\n ownerColumn: AnyColumn;\n /** Optional role column on the membership link enabling manager moderation. */\n managerRoleColumn?: AnyColumn;\n /** Role value that grants moderation (default \"manager\"); only used with managerRoleColumn. */\n managerRoleValue?: string;\n /** SQL type the JWT subject is cast to before comparison (default \"uuid\"). */\n subjectCastType?: string;\n};\n\n// Optional write-state gate (generic). When supplied, INSERT and UPDATE are additionally gated on\n// mutable state: a *locked* container admits writes only from a manager (e.g. a frozen discussion\n// thread), and a *muted* member may not write at all. SELECT and DELETE are unaffected — reads and\n// moderation deletes still flow. Domain-agnostic: the container/lock and membership/mute columns are\n// parameters. Requires managerRoleColumn (managers bypass the lock).\nexport type SupabaseMembershipWriteGateColumns = {\n /** Container table holding the lock flag (e.g. the `workspaces` table). */\n containerTable: AnyPgTable;\n /** PK column on the container table the governed row's container column references (e.g. `workspaces.id`). */\n containerPkColumn: AnyColumn;\n /** Boolean column on the container table; when true, only a manager may write (e.g. `workspaces.locked`). */\n containerLockColumn: AnyColumn;\n /** Boolean column on the membership table; when true, that member may not write (e.g. `workspaceMembers.muted`). */\n membershipMutedColumn: AnyColumn;\n};\n\nexport type SupabaseMembershipNativePoliciesOptions = SupabaseMembershipPredicateColumns & {\n role: PgRole;\n /** Optional write-state gate applied to INSERT and UPDATE only. */\n writeGate?: SupabaseMembershipWriteGateColumns;\n};\n\nconst defaultManagerRoleValue = \"manager\";\n\nconst membershipPolicyShapes: { command: MembershipPolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\ntype NormalizedMembershipColumns = SupabaseMembershipPredicateColumns & {\n managerRoleValue: string;\n subjectCastType: string;\n};\n\nfunction normalizeMembershipColumns(options: SupabaseMembershipPredicateColumns): NormalizedMembershipColumns {\n return {\n ...options,\n managerRoleValue: options.managerRoleValue ?? defaultManagerRoleValue,\n subjectCastType: options.subjectCastType ?? defaultSubjectCastType,\n };\n}\n\n// Containment form (not a correlated EXISTS): the governed row's container column must be in the set\n// of containers the subject belongs to. Two reasons it is `= ANY(ARRAY(subquery))` and not\n// `IN (subquery)`, both load-bearing:\n// 1. Correctness — the subquery stays uncorrelated (its `WHERE` references only the subject), so the\n// membership table's same-named column can't shadow the outer container column. A correlated\n// `EXISTS (… WHERE m.container = container …)` would collapse the correlation.\n// 2. Performance — for a runtime-resolved set (the subject comes from `current_setting`, opaque to\n// the planner) `IN (subquery)` is costed as a hashed semi-join → **sequential scan** of the\n// governed table; `= ANY(ARRAY(subquery))` materializes the set once (InitPlan) and the\n// ScalarArrayOp drives a **bitmap index scan**. At scale that is ~25-45× faster (the rls-read\n// perf track proves it). `inArray` can't wrap a raw subquery, so this stays `sql`.\nfunction membershipMatch(cols: NormalizedMembershipColumns, subject: SQL, requireManager: boolean): SQL {\n const subjectIsMember = eq(cols.membershipSubjectColumn, subject);\n const where =\n requireManager && cols.managerRoleColumn\n ? and(subjectIsMember, eq(cols.managerRoleColumn, cols.managerRoleValue).inlineParams())!\n : subjectIsMember;\n\n return sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;\n}\n\n/** owner-or-manager predicate (edit / moderate). */\nfunction ownerOrManager(cols: NormalizedMembershipColumns, subject: SQL): SQL {\n const owner = eq(cols.ownerColumn, subject);\n return cols.managerRoleColumn ? or(owner, membershipMatch(cols, subject, true))! : owner;\n}\n\n// write-state gate: ((container not locked) OR caller is a manager) AND caller's membership not muted.\n// Same `= ANY(ARRAY(subquery))` containment discipline as membershipMatch (uncorrelated set, index-scan\n// friendly), so the container/membership tables can reuse their own column names without shadowing the\n// governed row's container column.\nfunction membershipWriteGate(\n cols: NormalizedMembershipColumns,\n gate: SupabaseMembershipWriteGateColumns,\n subject: SQL,\n): SQL {\n const unlocked = sql`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;\n const notMuted = sql`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;\n return and(or(unlocked, membershipMatch(cols, subject, true))!, notMuted)!;\n}\n\nexport function buildSupabaseMembershipNativePolicies(options: SupabaseMembershipNativePoliciesOptions) {\n const cols = normalizeMembershipColumns(options);\n const subject = buildSubjectSql(cols.subjectCastType);\n const tableName = tableNameForColumn(cols.containerColumn, \"containerColumn\");\n\n const memberPredicate = membershipMatch(cols, subject, false);\n const ownerAndMember = and(eq(cols.ownerColumn, subject), memberPredicate)!;\n const ownerOrManagerPredicate = ownerOrManager(cols, subject);\n\n let writeGateClause: SQL | null = null;\n if (options.writeGate) {\n if (!cols.managerRoleColumn) {\n throw new Error(\"writeGate requires managerRoleColumn so a manager can write into a locked container\");\n }\n writeGateClause = membershipWriteGate(cols, options.writeGate, subject);\n }\n\n const gatedForWrite = (base: SQL): SQL => (writeGateClause ? and(base, writeGateClause)! : base);\n\n const predicateFor = (command: MembershipPolicyKind): SQL => {\n switch (command) {\n case \"select\":\n return memberPredicate;\n case \"insert\":\n return gatedForWrite(ownerAndMember);\n case \"update\":\n return gatedForWrite(ownerOrManagerPredicate);\n case \"delete\":\n return ownerOrManagerPredicate;\n }\n };\n\n return membershipPolicyShapes.map((shape) => {\n const predicate = predicateFor(shape.command);\n\n return pgPolicy(`${tableName}_${shape.command}_membership`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n });\n });\n}\n\n// ---------------------------------------------------------------------------\n// Grant-scope policies (generic). Authorization is carried IN THE JWT, not a DB\n// table: `app_metadata.authorization.grants` is an array of\n// `{ role, scope: { kind, <kind>Id } }` minted into the token. A row is visible\n// when its scope column (e.g. `offering_id`) appears among the caller's grants for\n// one of the accepting roles. Because the grant set lives in the token, the\n// predicate needs NO join — it parses the claims jsonb and tests set membership.\n//\n// Two forms, deliberately:\n// - default (InitPlan-correct): an **uncorrelated** `scope_col IN (SELECT …\n// jsonb_array_elements(claims) …)`. The subquery never references the outer row,\n// so the planner hoists it to an InitPlan and the JWT is parsed **once per\n// statement**.\n// - `naive: true` (the cliff): a **correlated** `EXISTS (… WHERE (g->…->>id) =\n// scope_col)`. Referencing the outer row forces per-row re-evaluation — the JWT\n// is re-parsed for **every row scanned**. It exists only to demonstrate and\n// regression-guard the InitPlan discipline (see the `rls-read-load` perf track);\n// never ship it.\n//\n// The same grant set is mirrored on the Electric read path by {@link resolveGrantScopeIds}\n// + {@link buildGrantScopeShapeWhere}: the proxy resolves the ids from the claims in JS\n// and injects a literal `scope_col IN ('a','b')` — Electric cannot read RLS, so the two\n// surfaces are generated from one declaration and must agree.\n// ---------------------------------------------------------------------------\n\ntype GrantScopePolicyKind = \"select\" | \"insert\" | \"update\" | \"delete\";\n\nconst defaultGrantsClaimPath = [\"app_metadata\", \"authorization\", \"grants\"] as const;\nconst defaultGrantScopeCastType = \"uuid\";\n\nexport type GrantScopeClaimOptions = {\n /** Value matched against each grant's `scope.kind` (e.g. \"offering\"). */\n scopeKind: string;\n /** Grant `role` values that confer access (e.g. [\"teacher\", \"assistant\"]). */\n roleValues: string[];\n /** Field within `scope` holding the id (e.g. \"offeringId\"). Defaults to `${scopeKind}Id`. */\n scopeIdField?: string;\n /** Path to the grants array in the claims. Defaults to `app_metadata.authorization.grants`. */\n grantsClaimPath?: string[];\n};\n\nexport type SupabaseGrantScopePredicateColumns = GrantScopeClaimOptions & {\n /** Column on the governed row naming its scope (e.g. `offerings.id` reference column). Table name is derived from it. */\n scopeColumn: AnyColumn;\n /** SQL type the extracted grant id is cast to before comparison (default \"uuid\"). */\n scopeCastType?: string;\n /**\n * Optional unconditional bypass: any grant whose `role` ∈ `bypass.roleValues` and whose\n * `scope.kind` = `bypass.scopeKind` (default \"platform\") grants all rows — e.g. a\n * platform-scoped `platform_admin`. The bypass is an **uncorrelated** EXISTS, so it stays\n * InitPlan-hoisted in both the correct and naive forms.\n */\n bypass?: { roleValues: string[]; scopeKind?: string };\n};\n\nexport type SupabaseGrantScopeNativePoliciesOptions = SupabaseGrantScopePredicateColumns & {\n role: PgRole;\n /** Emit the deliberately-naive per-row correlated form (cliff demo / regression guard only). */\n naive?: boolean;\n};\n\nconst grantScopePolicyShapes: { command: GrantScopePolicyKind; using: boolean; withCheck: boolean }[] = [\n { command: \"select\", using: true, withCheck: false },\n { command: \"insert\", using: false, withCheck: true },\n { command: \"update\", using: true, withCheck: true },\n { command: \"delete\", using: true, withCheck: false },\n];\n\nfunction resolveGrantsClaimPath(path: readonly string[] | undefined): string[] {\n const segments = path && path.length > 0 ? [...path] : [...defaultGrantsClaimPath];\n for (const segment of segments) {\n assertIdentifier(segment, \"grantsClaimPath segment\");\n }\n return segments;\n}\n\n// The grants array as a Postgres jsonb expression, defaulting to `[]` when absent so\n// `jsonb_array_elements` never errors. `#>` takes a text[] path; the segments are validated\n// identifiers, so the `'{…}'` path literal is injection-safe.\nfunction buildGrantsArraySqlText(path: string[]): string {\n return `coalesce(\n (\n coalesce(\n nullif(current_setting('request.jwt.claim', true), ''),\n nullif(current_setting('request.jwt.claims', true), '')\n )::jsonb #> '{${path.join(\",\")}}'\n ),\n '[]'::jsonb\n )`;\n}\n\nfunction buildRoleInListSqlText(roleValues: string[]): string {\n if (roleValues.length === 0) {\n throw new Error(\"grant-scope policy requires at least one role value\");\n }\n return renderInlineSql(\n sql.join(\n roleValues.map((role) => sql`${role}`),\n sql`, `,\n ),\n );\n}\n\nfunction resolveGrantScopeIdField(options: GrantScopeClaimOptions): string {\n const field = options.scopeIdField ?? `${options.scopeKind}Id`;\n assertIdentifier(field, \"scopeIdField\");\n return field;\n}\n\n// Uncorrelated bypass test (never references the governed row), so it is InitPlan-hoisted in both forms.\nfunction buildBypassExistsSqlText(bypass: { roleValues: string[]; scopeKind?: string }, grantsText: string): string {\n const scopeKind = bypass.scopeKind ?? \"platform\";\n return `exists (\n select 1\n from jsonb_array_elements(${grantsText}) as bypass_grant\n where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)}\n and bypass_grant ->> 'role' in (${buildRoleInListSqlText(bypass.roleValues)})\n )`;\n}\n\nfunction buildGrantScopePredicate(options: SupabaseGrantScopeNativePoliciesOptions): SQL {\n const scopeKind = options.scopeKind;\n assertIdentifier(scopeKind, \"scopeKind\");\n const scopeIdField = resolveGrantScopeIdField(options);\n const castType = options.scopeCastType ?? defaultGrantScopeCastType;\n assertTypeName(castType, \"scopeCastType\");\n const grantsText = buildGrantsArraySqlText(resolveGrantsClaimPath(options.grantsClaimPath));\n const roleIn = buildRoleInListSqlText(options.roleValues);\n const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;\n const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql`${scopeIdField}`)})::${castType}`;\n\n // Correct: uncorrelated `= ANY(ARRAY(select …))` → the grant set materializes once (InitPlan, JWT\n // parsed once) and the ScalarArrayOp drives a bitmap index scan on the scope column — ~25-45× faster\n // at scale than `IN (select …)`, which the planner costs as a hashed semi-join → sequential scan (the\n // rls-read perf track proves both). Naive: correlated `EXISTS` referencing the governed scope column →\n // re-evaluated per row (JWT parsed per row). The column object is spliced so it serializes qualified —\n // valid CREATE POLICY DDL on the write path.\n const base = options.naive\n ? sql`exists (select 1 from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)} and ${sql.raw(idExpr)} = ${options.scopeColumn})`\n : sql`${options.scopeColumn} = any(array(select ${sql.raw(idExpr)} from jsonb_array_elements(${sql.raw(grantsText)}) as grant_elem where ${sql.raw(kindMatch)}))`;\n\n if (!options.bypass) {\n return base;\n }\n return or(base, sql.raw(buildBypassExistsSqlText(options.bypass, grantsText)))!;\n}\n\n/**\n * Native Drizzle RLS policies for a JWT-resident grant set (see the section comment). Pass the real\n * scope column; the governed table name is derived from it. By default the predicate is the\n * InitPlan-correct uncorrelated `IN (subquery)`; pass `naive: true` for the correlated cliff variant.\n */\nexport function buildSupabaseGrantScopeNativePolicies(options: SupabaseGrantScopeNativePoliciesOptions) {\n const predicate = buildGrantScopePredicate(options);\n const tableName = tableNameForColumn(options.scopeColumn, \"scopeColumn\");\n const suffix = options.naive ? \"grant_scope_naive\" : \"grant_scope\";\n\n return grantScopePolicyShapes.map((shape) =>\n pgPolicy(`${tableName}_${shape.command}_${suffix}`, {\n as: \"permissive\",\n for: shape.command,\n to: options.role,\n ...(shape.using ? { using: predicate } : {}),\n ...(shape.withCheck ? { withCheck: predicate } : {}),\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Electric read-path mirror of the grant-scope policy. Electric cannot read RLS, so the proxy must\n// resolve the same visible scope-id set from the claims in JS and inject a literal `IN (…)` shape\n// `where`. These two helpers are the read-path counterpart to the policy above — one declaration,\n// two enforcement surfaces, derived from the same grant data so they cannot drift.\n// ---------------------------------------------------------------------------\n\nfunction readClaimsPath(claims: JwtClaims | null, path: string[]): unknown {\n let current: unknown = claims;\n for (const segment of path) {\n if (typeof current !== \"object\" || current === null || Array.isArray(current)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * The set of scope ids the caller can see, resolved from the JWT grants — the JS mirror of the\n * grant-scope RLS subquery. Returns a de-duplicated list (empty → no rows visible).\n */\nexport function resolveGrantScopeIds(claims: JwtClaims | null, options: GrantScopeClaimOptions): string[] {\n const grants = readClaimsPath(claims, resolveGrantsClaimPath(options.grantsClaimPath));\n if (!Array.isArray(grants)) {\n return [];\n }\n\n const scopeIdField = resolveGrantScopeIdField(options);\n const roleValues = new Set(options.roleValues);\n const ids = new Set<string>();\n\n for (const grant of grants) {\n if (typeof grant !== \"object\" || grant === null) {\n continue;\n }\n const record = grant as Record<string, unknown>;\n if (!roleValues.has(String(record[\"role\"]))) {\n continue;\n }\n const scope = record[\"scope\"];\n if (typeof scope !== \"object\" || scope === null) {\n continue;\n }\n const scopeRecord = scope as Record<string, unknown>;\n if (scopeRecord[\"kind\"] !== options.scopeKind) {\n continue;\n }\n const id = scopeRecord[scopeIdField];\n if (typeof id === \"string\" && id.length > 0) {\n ids.add(id);\n }\n }\n\n return [...ids];\n}\n\n/**\n * The Electric shape `where` for a grant-scope table: an `IN (…)` over the resolved ids (what the\n * proxy injects). Takes the real Drizzle scope column — referenced bare via `c()` (Electric's grammar\n * requires bare columns), so the reference is rename-safe — and returns a typed fragment whose ids\n * are **bound params** once `buildRowFilterShape` serializes it (never hand-escaped literals). An\n * empty id set denies all rows ({@link DENY_ALL}), mirroring the policy returning no rows.\n */\nexport function buildGrantScopeShapeWhere(scopeColumn: AnyColumn, ids: string[]): SQL {\n if (ids.length === 0) {\n return DENY_ALL;\n }\n return sql`${c(scopeColumn)} in (${sql.join(\n ids.map((id) => sql`${id}`),\n sql`, `,\n )})`;\n}\n",
108
+ "// Opt-in runtime instrumentation for diagnosing convergence / sync latency in a live app (e.g. the\n// board demo). It is OFF by default and adds nothing to a normal run: every call early-returns unless\n// `globalThis.__pgxsinkitDebug` is truthy, so it is safe to leave the call sites in shipping code.\n//\n// Enable it from the browser console (`globalThis.__pgxsinkitDebug = true`) — or set it before the\n// client boots; the board's dev build turns it on automatically. Each line is stamped with a monotonic\n// millisecond clock so the gaps between phases (enqueue → flush → server ack → Electric echo →\n// overlay clear → live-query render) can be read straight off the console.\n\ninterface DebugGlobal {\n __pgxsinkitDebug?: boolean;\n}\n\nconst isEnabled = (): boolean => (globalThis as DebugGlobal).__pgxsinkitDebug === true;\n\nconst now = (): number => (typeof performance !== \"undefined\" ? performance.now() : Date.now());\n\n/**\n * A sink that receives every `syncDebug` line (event, the worker's monotonic stamp, optional data),\n * INDEPENDENT of the local `__pgxsinkitDebug` console gate. This is the seam `defineSyncWorker` installs\n * to forward the debug rail to tabs (ADR-0032 decision 7): a SharedWorker's own console is invisible\n * (`chrome://inspect`), so lines must cross the bridge and each tab re-prints them gated on ITS OWN flag.\n * Unset by default → no forwarding and zero cost on the in-process path.\n */\ntype SyncDebugSink = (event: string, stamp: number, data?: Record<string, unknown>) => void;\nlet syncDebugSink: SyncDebugSink | undefined;\n\n/** Install (or clear, with `undefined`) the debug-rail sink. Idempotent; `defineSyncWorker` owns it. */\nexport function setSyncDebugSink(sink: SyncDebugSink | undefined): void {\n syncDebugSink = sink;\n}\n\n/**\n * Log one timestamped event. Prints to the console only when `globalThis.__pgxsinkitDebug` is on, but ALSO\n * feeds any installed {@link setSyncDebugSink} sink (so the worker can forward the rail to tabs even when the\n * worker's own console gate is off). No sink AND not enabled → an early return, so the off-path pays nothing.\n */\nexport function syncDebug(event: string, data?: Record<string, unknown>): void {\n const enabled = isEnabled();\n if (!enabled && syncDebugSink === undefined) return;\n const stamp = now();\n if (enabled) {\n const prefix = `[pgxsinkit ${stamp.toFixed(0)}ms]`;\n if (data) {\n console.debug(`${prefix} ${event}`, data);\n } else {\n console.debug(`${prefix} ${event}`);\n }\n }\n syncDebugSink?.(event, stamp, data);\n}\n\n/** The request URL of a `fetch` first argument, in any of its accepted forms; undefined if unreadable. */\nfunction fetchInputUrl(input: Parameters<typeof fetch>[0]): string | undefined {\n if (typeof input === \"string\") return input;\n if (input instanceof URL) return input.toString();\n if (typeof input === \"object\" && input !== null && \"url\" in input) {\n return (input as { url: string }).url;\n }\n return undefined;\n}\n\n/**\n * Wrap a `fetch` so every ShapeStream request (the Electric read-path long-poll/catch-up) emits a start\n * line (shape/table, offset, live — derived from the request URL params) and a completion line (status,\n * ms, and whether the response is up-to-date). Passthrough when instrumentation is off: the early return\n * runs before any URL parsing, so the off-path pays nothing per request beyond this closure itself.\n *\n * Inject it as a ShapeStream `fetchClient`; pass the stream's existing `fetchClient` (if any) as the base\n * so the instrumentation composes rather than replaces.\n */\nexport function instrumentShapeFetch(baseFetch: typeof fetch = fetch): typeof fetch {\n const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> => {\n if (!isEnabled()) return baseFetch(input, init);\n const url = fetchInputUrl(input);\n const params = url ? new URL(url).searchParams : undefined;\n // Derive the shape identity ONCE and name it on BOTH the start and done lines, so a start/done pair\n // is readable without cross-referencing timing (multiple shapes' requests interleave on the rail).\n const shape = params?.get(\"table\") ?? undefined;\n const live = params?.get(\"live\") === \"true\";\n const offset = params?.get(\"offset\") ?? undefined;\n // The handle chain is the backlog-0001 forensic: WHICH handle each request carried, which one the\n // response minted, and whether the stale-cache ladder's params were on the wire — so a\n // dead-handle-served-N-times storm reads straight off the rail (same responseHandle across busted\n // attempts) instead of needing a network-tab capture at the moment of recurrence.\n const requestHandle = params?.get(\"handle\") ?? undefined;\n const cacheBuster = params?.has(\"cache-buster\") ?? false;\n const expiredHandle = params?.get(\"expired_handle\") ?? undefined;\n // The whole request identity rides in ONE compact string field: Chrome's console preview truncates\n // object previews at ~5 properties, and a captured log (the only artifact of a live recurrence) keeps\n // just the preview — separate fields silently vanish exactly when they matter (backlog 0001).\n const cursor = params?.get(\"cursor\") ?? undefined;\n const req = [\n `${shape ?? \"?\"}@${offset ?? \"?\"}`,\n live ? \"live\" : \"catchup\",\n requestHandle ? `h=${requestHandle}` : \"no-handle\",\n // The live-cycle cursor is Electric's CDN-collapse defense — its absence or non-advancement on\n // live polls is itself a finding (backlog 0001).\n cursor ? `c=${cursor}` : live ? \"NO-CURSOR\" : \"\",\n cacheBuster ? \"BUSTED\" : \"\",\n expiredHandle ? `expired=${expiredHandle}` : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n syncDebug(\"shape request start\", { req });\n const startedAt = now();\n return baseFetch(input, init).then((response) => {\n // Same single-string discipline for the response half: status/ms stay first-class (they are what\n // rail readers scan), the forensic chain (up-to-date, minted handle, end offset) folds into `resp`.\n const responseHandle = response.headers.get(\"electric-handle\");\n const responseOffset = response.headers.get(\"electric-offset\");\n const responseCursor = response.headers.get(\"electric-cursor\");\n const age = response.headers.get(\"age\");\n const resp = [\n response.headers.has(\"electric-up-to-date\") ? \"up-to-date\" : \"\",\n responseHandle && responseHandle !== requestHandle ? `minted h=${responseHandle}` : \"\",\n responseOffset ? `end=${responseOffset}` : \"\",\n responseCursor ? `c=${responseCursor}` : \"\",\n age ? `age=${age}` : \"\",\n ]\n .filter(Boolean)\n .join(\" \");\n syncDebug(\"shape request done\", {\n req,\n status: response.status,\n ms: Math.round(now() - startedAt),\n ...(resp ? { resp } : {}),\n });\n return response;\n });\n };\n // `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the\n // ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.\n return wrapped as typeof fetch;\n}\n\n/**\n * Run `fn`, logging `<event> done` with its wall-clock duration (and any extra `data`). When\n * instrumentation is off this is a thin pass-through with no logging and no timing overhead beyond the\n * call itself. Returns whatever `fn` returns.\n */\nexport async function timeAsync<T>(event: string, fn: () => Promise<T>, data?: Record<string, unknown>): Promise<T> {\n if (!isEnabled()) return fn();\n const startedAt = now();\n syncDebug(`${event} start`, data);\n try {\n return await fn();\n } finally {\n syncDebug(`${event} done`, { ms: Math.round(now() - startedAt) });\n }\n}\n",
109
+ "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE) —\n// specifically a port of the serializer from electric-sql/pglite PR #1035.\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\n/**\n * Serialization of JavaScript values into a PostgreSQL `COPY ... WITH (FORMAT\n * text)` stream.\n *\n * The Electric client parses the wire values it receives into native JS values\n * before they reach this module: `int2`/`int4`/`float4`/`float8` become\n * `number`, `int8` becomes `bigint`, `bool` becomes `boolean`, `json`/`jsonb`\n * become parsed objects/arrays, array columns become (possibly nested) JS\n * arrays, and every other type is left as its raw Postgres text representation\n * (a `string`). To feed those values back into `COPY` we have to reverse that:\n * turn each value into the exact text Postgres' input functions expect, then\n * apply the COPY framing.\n *\n * Rather than invent an escaping scheme (the previous CSV-based approach broke\n * on arrays, JSON, embedded delimiters, etc.) this is a faithful port of the\n * two relevant PostgreSQL backend routines:\n *\n * - `CopyAttributeOutText` (src/backend/commands/copyto.c) — field escaping\n * - `array_out` (src/backend/utils/adt/arrayfuncs.c) — array literals\n *\n * The TEXT format is used (not CSV) because it is what Postgres itself emits\n * internally, has a single well-defined escaping algorithm, and round-trips\n * every built-in type.\n */\n\n// Defaults for COPY ... WITH (FORMAT text), matching the Postgres backend.\nconst DELIMITER = \"\\t\";\nconst NULL_MARKER = \"\\\\N\";\nconst ROW_SEPARATOR = \"\\n\";\n\n// CopyAttributeOutText escapes the backslash, the field delimiter, and the\n// control characters that have C-style escapes. Every other byte is emitted\n// literally. Our delimiter is a tab, which already has a C-style escape, so the\n// single map below covers all cases.\nconst COPY_TEXT_ESCAPES: Record<string, string> = {\n \"\\\\\": \"\\\\\\\\\",\n \"\\b\": \"\\\\b\",\n \"\\f\": \"\\\\f\",\n \"\\n\": \"\\\\n\",\n \"\\r\": \"\\\\r\",\n \"\\t\": \"\\\\t\",\n \"\\v\": \"\\\\v\",\n};\nconst COPY_TEXT_ESCAPE_RE = /[\\\\\\b\\f\\n\\r\\t\\v]/g;\n\n/** Escape an already-stringified field value per `CopyAttributeOutText`. */\nfunction escapeCopyText(value: string): string {\n return value.replace(COPY_TEXT_ESCAPE_RE, (c) => COPY_TEXT_ESCAPES[c] ?? c);\n}\n\n/**\n * Convert a Uint8Array to Postgres `bytea` hex-format text (`\\xDEADBEEF`).\n * Electric normally delivers `bytea` already as such a string, so this only\n * matters for callers using a custom parser that yields binary.\n */\nfunction byteaToText(bytes: Uint8Array): string {\n let hex = \"\";\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, \"0\");\n }\n return \"\\\\x\" + hex;\n}\n\n/**\n * Render a JS `number` the way Postgres' float/int input accepts it. The only\n * special cases are the non-finite values, which Postgres spells out in words.\n */\nfunction numberToText(value: number): string {\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return String(value);\n}\n\n// array_out quotes an element when it is empty, looks like the literal NULL, or\n// contains a brace, the element delimiter (comma), a double-quote, a backslash,\n// or ASCII whitespace. We mirror `array_isspace`, which is stricter than JS\n// `\\s` (it excludes Unicode whitespace), so the output matches Postgres' own\n// `array_out` TEXT format exactly and re-parses correctly on `COPY FROM`.\nconst ARRAY_NEEDS_QUOTE_RE = /[{}\",\\\\ \\t\\n\\r\\v\\f]/;\n\n/** Quote/escape a single array element's text per `array_out`. */\nfunction quoteArrayElement(text: string): string {\n const needsQuote = text.length === 0 || text.toLowerCase() === \"null\" || ARRAY_NEEDS_QUOTE_RE.test(text);\n if (!needsQuote) return text;\n // Inside quotes only `\"` and `\\` are escaped, each with a single backslash.\n return '\"' + text.replace(/([\"\\\\])/g, \"\\\\$1\") + '\"';\n}\n\n/**\n * Build a Postgres array literal (`{...}`) from a JS array, recursing into\n * nested arrays for multi-dimensional arrays. NULL elements become an unquoted\n * `NULL`; nested arrays are emitted as bare `{...}` (never quoted), exactly as\n * `array_out` does.\n */\nfunction arrayToText(arr: ReadonlyArray<unknown>): string {\n const elements = arr.map((el) => {\n if (el === null || el === undefined) return \"NULL\";\n if (Array.isArray(el)) return arrayToText(el);\n return quoteArrayElement(valueToText(el));\n });\n return \"{\" + elements.join(\",\") + \"}\";\n}\n\n/**\n * Convert a non-null JS value to its bare Postgres text representation (before\n * COPY field escaping is applied). Dispatch is on the runtime type produced by\n * the Electric parser. `json`/`jsonb` columns are handled ahead of this by\n * `serializeCopyValue` when a column type is known; reaching the object branch\n * here is the type-less fallback.\n */\nfunction valueToText(value: unknown): string {\n switch (typeof value) {\n case \"string\":\n return value;\n case \"number\":\n return numberToText(value);\n case \"bigint\":\n return value.toString();\n case \"boolean\":\n return value ? \"t\" : \"f\";\n case \"object\": {\n if (Array.isArray(value)) return arrayToText(value);\n if (value instanceof Date) return value.toISOString();\n if (value instanceof Uint8Array) return byteaToText(value);\n if (value instanceof ArrayBuffer) return byteaToText(new Uint8Array(value));\n if (ArrayBuffer.isView(value)) {\n const view = value as ArrayBufferView;\n return byteaToText(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));\n }\n // json / jsonb arrive already parsed; re-serialize them.\n return JSON.stringify(value);\n }\n default:\n // Should be unreachable for Electric-parsed values; be defensive.\n return String(value);\n }\n}\n\n/**\n * Build a Postgres array literal from a `json[]`/`jsonb[]` value. Each element\n * is JSON text (re-serialized from the parsed value), so we cannot reuse the\n * generic array path: a JSON array element must stay JSON (`[1,2]`), not be\n * turned into a nested SQL array (`{1,2}`).\n */\nfunction jsonArrayToText(arr: ReadonlyArray<unknown>): string {\n const elements = arr.map((el) => (el === null || el === undefined ? \"NULL\" : quoteArrayElement(jsonToText(el))));\n return \"{\" + elements.join(\",\") + \"}\";\n}\n\n/**\n * Re-serialize a parsed `json`/`jsonb` value to its JSON text form. Electric\n * delivers these columns already run through `JSON.parse`, so the value is the\n * decoded JS value (object, array, string, number, boolean or null) and always\n * needs `JSON.stringify` to become valid JSON input again — including scalars\n * (the string `hi` must be written as `\"hi\"`).\n */\nfunction jsonToText(value: unknown): string {\n return JSON.stringify(value);\n}\n\n/**\n * Postgres `udt_name`s that need JSON-aware serialization rather than the\n * generic runtime-type dispatch. Used to resolve the otherwise undecidable\n * \"is this JS array a SQL array or a JSON array?\" ambiguity.\n */\nconst JSON_UDT_NAMES = new Set([\"json\", \"jsonb\"]);\nconst JSON_ARRAY_UDT_NAMES = new Set([\"_json\", \"_jsonb\"]);\n\n/**\n * Serialize a single value into one COPY TEXT field. `null`/`undefined` become\n * the NULL marker (`\\N`); everything else is converted to text and escaped.\n *\n * `udtName` is the column's Postgres `udt_name`. When supplied it disambiguates\n * `json`/`jsonb` columns; when omitted the value's runtime type is used (which\n * cannot tell a `jsonb` array from a SQL array).\n */\nexport function serializeCopyValue(value: unknown, udtName?: string): string {\n if (value === null || value === undefined) return NULL_MARKER;\n if (udtName !== undefined) {\n if (JSON_UDT_NAMES.has(udtName)) return escapeCopyText(jsonToText(value));\n if (JSON_ARRAY_UDT_NAMES.has(udtName) && Array.isArray(value)) return escapeCopyText(jsonArrayToText(value));\n }\n return escapeCopyText(valueToText(value));\n}\n\n/**\n * Serialize a list of row objects into the body of a `COPY ... FROM` request in\n * TEXT format. Columns are emitted in the given order, fields are tab\n * separated, and rows are newline separated.\n *\n * `columnTypes` optionally maps a column name to its Postgres `udt_name`; pass\n * it so `json`/`jsonb` columns serialize correctly.\n */\nexport function generateCopyData(\n rows: ReadonlyArray<Record<string, unknown>>,\n columns: ReadonlyArray<string>,\n columnTypes?: Readonly<Record<string, string | undefined>>,\n): string {\n return rows\n .map((row) => columns.map((column) => serializeCopyValue(row[column], columnTypes?.[column])).join(DELIMITER))\n .join(ROW_SEPARATOR);\n}\n",
110
+ "import type { PGlite, PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\n\n/**\n * A Drizzle handle whose executor is an already-open PGlite connection *or* an open PGlite\n * `Transaction` — the tier-① authoring/execution surface for the sync engine's metadata-store DML\n * (ADR-0028 decision 4).\n *\n * The blocker the old convertibility report cited was \"`drizzle-orm/pglite` wraps only a PGlite\n * instance, not a Transaction\". That is a *type* boundary, not a runtime one: drizzle's pglite session\n * layer only ever calls `client.query(sql, params, { rowMode, parsers })` on the wrapped client (verified\n * against drizzle-orm 1.0.0-rc.4 `pglite/session.js` — the executor touches nothing but `.query`; the\n * only other member it would reach is `.transaction`, and only if someone calls `db.transaction()`).\n * PGlite's `Transaction` exposes a `query` with the identical `(sql, params, options)` shape, so a handle\n * built over a `Transaction` executes every statement **on that transaction** — participating in the\n * engine's commit boundary rather than opening its own.\n *\n * The cast to `PGlite` is the narrowest honest one: at runtime the session only calls `.query`, which\n * both `PGliteInterface` and `Transaction` satisfy; the type just does not express that union. It is the\n * expected single-expression cast for this seam.\n *\n * CONTRACT: `.transaction()` on the returned handle is **forbidden**. The engine owns transaction\n * boundaries itself (`pg.transaction(async (tx) => …)` + explicit `tx.rollback()` on unsubscribe, sync\n * index.ts); calling `db.transaction()` here would (a) require the wrapped client to be a full PGlite,\n * which a `Transaction` is not, and (b) open a nested boundary the engine does not expect. Do not expose\n * or use it.\n *\n * MUST be the `{ client }` config form: drizzle's pglite driver destructures `{ connection, client }`\n * from a bare first argument, so `drizzle(pg)` misdetects the handle as a config object and silently\n * constructs a NEW in-memory PGlite — every statement would then hit an empty, throwaway database.\n */\n\n// One drizzle handle per underlying connection/transaction object. The handle for a given `Transaction`\n// is short-lived (one commit) but reused across the several metadata statements that run within that\n// commit — the tag-store hot path — so memoizing per handle avoids re-wrapping on every statement while\n// never leaking across transactions (a `Transaction` object is a fresh identity each commit, and the\n// WeakMap drops it once the commit's closure is collected).\nconst handles = new WeakMap<PGliteInterface | Transaction, PgliteDatabase<never>>();\n\n/** A (memoized) Drizzle handle over an open PGlite connection or transaction — engine-internal. */\nexport function drizzleOverPg(pg: PGliteInterface | Transaction): PgliteDatabase<never> {\n let db = handles.get(pg);\n if (!db) {\n db = drizzle({ client: pg as unknown as PGlite }) as PgliteDatabase<never>;\n handles.set(pg, db);\n }\n return db;\n}\n",
111
+ "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { ChangeMessage, Row } from \"@electric-sql/client\";\nimport type { PGliteInterface, Transaction } from \"@electric-sql/pglite\";\nimport { and, eq, fillPlaceholders, sql } from \"drizzle-orm\";\nimport { getTableConfig, type PgColumn } from \"drizzle-orm/pg-core\";\n\nimport { quoteIdentifier } from \"@pgxsinkit/contracts\";\n\nimport type { ApplyTarget } from \"../local-tables\";\nimport { generateCopyData } from \"./copy\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport type { InsertChangeMessage } from \"./types\";\n\n/**\n * Re-key an Electric change row (keyed by DB **column name**) to the Drizzle **property keys** the\n * query builder addresses columns by (ADR-0029 D1). A column absent from the local projected table is a\n * config error and surfaces, rather than silently binding to nothing.\n */\nfunction toDriverRow(target: ApplyTarget, data: Row<unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const name of Object.keys(data)) {\n const propertyKey = target.propertyKeyByName[name];\n if (propertyKey === undefined) {\n throw new Error(`sync apply: column ${JSON.stringify(name)} is not present on the local synced table`);\n }\n out[propertyKey] = data[name];\n }\n return out;\n}\n\n/** The `PgColumn` for a DB column name on the target table (for `eq`/conflict-target/COPY clauses). */\nfunction targetColumn(target: ApplyTarget, name: string): PgColumn {\n const column = target.columnByName[name];\n if (!column) {\n throw new Error(`sync apply: column ${JSON.stringify(name)} not found on the local synced table`);\n }\n return column;\n}\n\nexport interface ApplyMessageToTableOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n message: ChangeMessage<Row<unknown>>;\n debug: boolean;\n}\n\nexport async function applyMessageToTable({ pg, target, message, debug }: ApplyMessageToTableOptions) {\n const data = message.value;\n const db = drizzleOverPg(pg);\n\n switch (message.headers.operation) {\n case \"insert\": {\n if (debug) console.log(\"inserting\", data);\n // Apply exactly what Electric sent: an `insert` is a new row (post-truncate or first send), so\n // it is a plain INSERT. A genuine primary-key collision must surface, never be silently upserted.\n return await db.insert(target.table).values(toDriverRow(target, data) as never);\n }\n\n case \"update\": {\n if (debug) console.log(\"updating\", data);\n const setColumns = Object.keys(data).filter((column) => !target.primaryKey.includes(column));\n if (setColumns.length === 0) return;\n const setValues: Record<string, unknown> = {};\n for (const column of setColumns) setValues[target.propertyKeyByName[column]!] = data[column];\n return await db\n .update(target.table)\n .set(setValues as never)\n .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));\n }\n\n case \"delete\": {\n if (debug) console.log(\"deleting\", data);\n return await db\n .delete(target.table)\n .where(and(...target.primaryKey.map((column) => eq(targetColumn(target, column), data[column]))));\n }\n }\n}\n\nexport interface BulkApplyMessagesToTableOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n messages: InsertChangeMessage[];\n debug: boolean;\n}\n\nconst MAX_INSERT_PARAMS = 32_000;\nconst MAX_INSERT_BYTES = 50 * 1024 * 1024;\n\n/**\n * The rendered `{sqlText, params}` for a batched INSERT of `rowCount` rows over `colNames` (ADR-0029\n * D5's render-once remedy). Rendered ONCE per distinct (column-set, row-count) via a placeholder INSERT\n * over the real table, then reused for every batch of that shape — driving the per-row × per-column\n * builder-AST cost to zero. `sql.placeholder` cells make Drizzle emit `$n` markers without applying a\n * codec at render time; the codec is applied per value at execution (see {@link executeInsertBatch}).\n */\nfunction renderInsert(\n db: ReturnType<typeof drizzleOverPg>,\n target: ApplyTarget,\n colNames: string[],\n rowCount: number,\n): { sqlText: string; params: unknown[] } {\n const key = JSON.stringify([rowCount, colNames]);\n const cached = target.insertRenderCache.get(key);\n if (cached) return cached;\n const placeholderRows = Array.from({ length: rowCount }, (_, r) =>\n Object.fromEntries(colNames.map((name, ci) => [target.propertyKeyByName[name]!, sql.placeholder(`${r}_${ci}`)])),\n );\n const rendered = db\n .insert(target.table)\n .values(placeholderRows as never)\n .toSQL();\n const value = { sqlText: rendered.sql, params: rendered.params as unknown[] };\n target.insertRenderCache.set(key, value);\n return value;\n}\n\n/**\n * Execute one rendered batch: fill the render-once placeholders with this batch's values, applying the\n * real per-column codec (`fillPlaceholders` runs each column's `mapToDriverValue`, with a null guard —\n * byte-identical to a plain `.values()` bind), then run the pre-rendered statement on the executor.\n */\nasync function executeInsertBatch(\n pg: PGliteInterface | Transaction,\n db: ReturnType<typeof drizzleOverPg>,\n target: ApplyTarget,\n colNames: string[],\n batch: Row<unknown>[],\n): Promise<void> {\n const rendered = renderInsert(db, target, colNames, batch.length);\n const values: Record<string, unknown> = {};\n for (let r = 0; r < batch.length; r++) {\n const row = batch[r]!;\n for (let ci = 0; ci < colNames.length; ci++) {\n values[`${r}_${ci}`] = row[colNames[ci]!];\n }\n }\n const flat = fillPlaceholders(rendered.params, values);\n await pg.query(rendered.sqlText, flat as unknown[]);\n}\n\nexport async function applyInsertsToTable({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n\n if (debug) console.log(\"inserting\", data);\n const columns = Object.keys(firstRow);\n const db = drizzleOverPg(pg);\n\n const getValueSize = (value: unknown): number => {\n if (value === null) return 0;\n if (value instanceof ArrayBuffer) return value.byteLength;\n if (value instanceof Blob) return value.size;\n if (value instanceof Uint8Array) return value.byteLength;\n if (value instanceof DataView) return value.byteLength;\n if (ArrayBuffer.isView(value)) return value.byteLength;\n\n switch (typeof value) {\n case \"string\":\n return value.length;\n case \"number\":\n return 8;\n case \"boolean\":\n return 1;\n case \"bigint\":\n case \"symbol\":\n return value.toString().length;\n case \"function\":\n case \"undefined\":\n return 0;\n default: {\n // Remaining typeof: object (null was handled above).\n if (value instanceof Date) return 8;\n try {\n return JSON.stringify(value)?.length ?? 0;\n } catch {\n // Non-serialisable nested value (e.g. bigint inside jsonb).\n return 16;\n }\n }\n }\n };\n\n const getRowSize = (row: Row<unknown>): number => {\n return columns.reduce((size, column) => {\n const value = row[column];\n if (value === null) return size;\n\n if (Array.isArray(value)) {\n if (value.length === 0) return size;\n const firstElement = value[0];\n\n switch (typeof firstElement) {\n case \"number\":\n return size + value.length * 8;\n case \"string\":\n return size + value.reduce((arrSize, str) => arrSize + str.length, 0);\n case \"boolean\":\n return size + value.length;\n default:\n if (firstElement instanceof Date) {\n return size + value.length * 8;\n }\n return size + value.reduce((arrSize, item) => arrSize + getValueSize(item), 0);\n }\n }\n\n return size + getValueSize(value);\n }, 0);\n };\n\n let currentBatch: Row<unknown>[] = [];\n let currentBatchSize = 0;\n let currentBatchParams = 0;\n\n for (const row of data) {\n const rowSize = getRowSize(row);\n const rowParams = columns.length;\n\n if (\n currentBatch.length > 0 &&\n (currentBatchSize + rowSize > MAX_INSERT_BYTES || currentBatchParams + rowParams > MAX_INSERT_PARAMS)\n ) {\n if (debug && currentBatchSize + rowSize > MAX_INSERT_BYTES) {\n console.log(\"batch size limit exceeded, executing batch\");\n }\n if (debug && currentBatchParams + rowParams > MAX_INSERT_PARAMS) {\n console.log(\"batch params limit exceeded, executing batch\");\n }\n await executeInsertBatch(pg, db, target, columns, currentBatch);\n currentBatch = [];\n currentBatchSize = 0;\n currentBatchParams = 0;\n }\n\n currentBatch.push(row);\n currentBatchSize += rowSize;\n currentBatchParams += rowParams;\n }\n\n if (currentBatch.length > 0) {\n await executeInsertBatch(pg, db, target, columns, currentBatch);\n }\n\n if (debug) console.log(`Inserted ${messages.length} rows using INSERT`);\n}\n\n/**\n * Bulk **upsert** for tagged-subquery move-in rows (ADR-0024). A move-in is an existing row ENTERING the\n * shape — unlike a CDC `insert` (a brand-new row) it may already be present locally via an independent\n * grant, or be re-delivered on a resume from before the move-in's offset. So it is applied idempotently:\n * `INSERT … ON CONFLICT (pk) DO UPDATE` refreshes to the move-in's authoritative value (or `DO NOTHING`\n * for a pk-only table). The plain-`INSERT` invariant of the CDC path — a genuine PK collision must\n * surface ({@link applyInsertsToTable}) — is intentionally NOT used here, because for a move-in a present\n * row is expected, not a bug. Batched by parameter count (move-in volume is incremental, not a backfill).\n */\nexport async function applyUpsertsToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyUpsertsToTable requires a primary key\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) return;\n\n const columns = Object.keys(firstRow);\n const pkSet = new Set(primaryKey);\n const nonPkColumns = columns.filter((column) => !pkSet.has(column));\n\n const conflictTarget = primaryKey.map((column) => targetColumn(target, column));\n // `DO UPDATE SET col = excluded.col` for every non-pk column; `excluded.<col>` is the standard\n // conflict pseudo-relation reference, authored via `sql.identifier` so the column stays a quoted bare\n // identifier (not table-qualified). A pk-only table has nothing to refresh → `DO NOTHING`.\n const conflictSet: Record<string, unknown> = {};\n for (const column of nonPkColumns) {\n conflictSet[target.propertyKeyByName[column]!] = sql`excluded.${sql.identifier(column)}`;\n }\n\n const perRow = columns.length;\n const rowsPerBatch = Math.max(1, Math.floor(MAX_INSERT_PARAMS / perRow));\n const db = drizzleOverPg(pg);\n\n for (let i = 0; i < data.length; i += rowsPerBatch) {\n const batch = data.slice(i, i + rowsPerBatch).map((row) => toDriverRow(target, row));\n const insert = db.insert(target.table).values(batch as never);\n if (nonPkColumns.length > 0) {\n await insert.onConflictDoUpdate({ target: conflictTarget, set: conflictSet as never });\n } else {\n // Target the PK explicitly so a pk-only conflict is a no-op ONLY on the primary key — a bare\n // `ON CONFLICT DO NOTHING` would swallow conflicts on any unique constraint.\n await insert.onConflictDoNothing({ target: conflictTarget });\n }\n }\n\n if (debug) console.log(`Upserted ${messages.length} move-in rows`);\n}\n\n/** A column's name plus the SQL type to cast it to inside a `json_to_recordset` record definition. */\ninterface JsonRecordsetColumn {\n name: string;\n castType: string;\n}\n\n/**\n * The `json_to_recordset` casts for the rows being applied, narrowed to the columns actually present in\n * the synced row, from the model-derived {@link ApplyTarget.columnTypes} (ADR-0029 D2 — never from a\n * catalog probe: the types are always present, derived from the same Drizzle definitions the local\n * store was rendered from).\n */\nfunction jsonRecordsetColumns(target: ApplyTarget, firstRow: Row<unknown>): JsonRecordsetColumn[] {\n const present = (name: string) => Object.prototype.hasOwnProperty.call(firstRow, name);\n return target.columnTypes\n .filter((column) => present(column.name))\n .map((column) => ({ name: column.name, castType: `${column.sqlType}${column.isArray ? \"[]\" : \"\"}` }));\n}\n\nexport async function applyMessagesToTableWithJson({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n if (debug) console.log(\"applying messages with json_to_recordset\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n const columns = jsonRecordsetColumns(target, firstRow);\n const targetTable = target.table;\n // Tier ② (ADR-0028): the target table is an interpolated table object and the batch is a single bound\n // param (`sql.param` binds the raw JS array unchanged, exactly as the old `[batch]` did — critically,\n // NOT `JSON.stringify`, which would throw on the bigints this path carries). The `x(col type, …)`\n // record definition is raw text: `json_to_recordset`'s grammar requires bare column identifiers and\n // type names there, which no tier-①/② builder expresses.\n const recordDef = columns.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const db = drizzleOverPg(pg);\n\n const max = 10_000;\n for (let i = 0; i < data.length; i += max) {\n const batch = data.slice(i, i + max);\n await db.execute(\n sql`INSERT INTO ${targetTable} SELECT x.* from json_to_recordset(${sql.param(batch)}) as x(${sql.raw(recordDef)})`,\n );\n }\n\n if (debug) {\n console.log(`Inserted ${messages.length} rows using json_to_recordset`);\n }\n}\n\n/**\n * Each column mapped to its Postgres `udt_name` for the COPY serializer, which needs it only to\n * disambiguate `json`/`jsonb` (whose parsed values are indistinguishable from SQL arrays/objects by\n * runtime type alone). Derived from the model ({@link ApplyTarget.columnTypes}), never introspected\n * (ADR-0029 D2).\n */\nfunction copyColumnUdts(target: ApplyTarget): Record<string, string> {\n const map: Record<string, string> = {};\n for (const column of target.columnTypes) {\n const base = column.sqlType\n .replace(/\\(.*\\)/g, \"\")\n .trim()\n .toLowerCase();\n if (base === \"json\" || base === \"jsonb\") {\n map[column.name] = column.isArray ? `_${base}` : base;\n }\n }\n return map;\n}\n\nexport async function applyMessagesToTableWithCopy({ pg, target, messages, debug }: BulkApplyMessagesToTableOptions) {\n if (debug) console.log(\"applying messages with COPY\");\n\n const data: Row<unknown>[] = messages.map((message) => message.value);\n const firstRow = data[0];\n if (!firstRow) {\n return;\n }\n const columns = Object.keys(firstRow);\n\n // Serialize rows using Postgres' own COPY TEXT format — a faithful port of the backend's\n // CopyAttributeOutText / array_out routines (see ./copy) — so arrays (incl. multi-dimensional),\n // json/jsonb, bytea, timestamps and strings with embedded delimiters/newlines all round-trip,\n // unlike the previous hand-rolled CSV encoder.\n const columnUdts = copyColumnUdts(target);\n const copyData = generateCopyData(data, columns, columnUdts);\n const copyBlob = new Blob([copyData], { type: \"text/plain\" });\n\n // TEXT is the default COPY format; its default delimiter is a tab and NULL marker is `\\N`, both of\n // which generateCopyData emits.\n //\n // Tier ③ (ADR-0028 allow-list): `COPY … FROM '/dev/blob'` is PGlite's blob-ingest grammar — it has no\n // Drizzle builder form, so the statement stays a raw string. The table reference is taken from the real\n // synced table object: a bare name (ephemeral → `pg_temp` via search_path) or a schema-qualified one.\n const { name: tableName, schema } = getTableConfig(target.table);\n const copyTarget = schema ? `${quoteIdentifier(schema)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);\n await pg.query(\n `\n COPY ${copyTarget} (${columns.map((column) => quoteIdentifier(column)).join(\", \")})\n FROM '/dev/blob'\n WITH (FORMAT text)\n `,\n [],\n {\n blob: copyBlob,\n },\n );\n\n if (debug) console.log(`Inserted ${messages.length} rows using COPY`);\n}\n\nconst JSON_RECORDSET_BATCH = 10_000;\n\n/**\n * The `json_to_recordset` casts for an **explicit, ordered** column list — the bulk UPDATE/DELETE source\n * relations need the PK columns (plus, for updates, the group's SET columns) in a known order. Derived\n * from the model ({@link ApplyTarget.columnTypes}), never introspected (ADR-0029 D2).\n */\nfunction recordsetColumnCasts(target: ApplyTarget, columnNames: string[]): JsonRecordsetColumn[] {\n const byName = new Map(target.columnTypes.map((column) => [column.name, column]));\n return columnNames.map((name) => {\n const column = byName.get(name);\n if (!column) {\n throw new Error(`recordsetColumnCasts: no registered type for column ${JSON.stringify(name)}`);\n }\n return { name, castType: `${column.sqlType}${column.isArray ? \"[]\" : \"\"}` };\n });\n}\n\nexport interface BulkKeyedApplyOptions {\n pg: PGliteInterface | Transaction;\n target: ApplyTarget;\n /** Folded messages: for deletes the value carries the PK; for updates the PK plus merged columns. */\n messages: ChangeMessage<Row<unknown>>[];\n debug: boolean;\n}\n\n/**\n * Bulk DELETE by primary key via `DELETE … USING json_to_recordset(…)` (ADR-0014 Phase 3). Safe\n * because the read-path fold already left **one row per PK** — no same-PK duplicate in the source.\n */\nexport async function applyBulkDeletesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyBulkDeletesToTable requires a primary key\");\n if (messages.length === 0) return;\n\n const rows = messages.map((message) => {\n const data = message.value;\n return Object.fromEntries(primaryKey.map((column) => [column, data[column]]));\n });\n\n const casts = recordsetColumnCasts(target, primaryKey);\n const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const whereJoin = primaryKey\n .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\" AND \");\n const targetTable = target.table;\n const db = drizzleOverPg(pg);\n\n for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {\n const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);\n // Tier ② (ADR-0028): the target table is an interpolated table object; the pk-projection batch is a\n // single bound param (`sql.param` binds the raw JS array unchanged — as the old `[batch]` did, and\n // NOT `JSON.stringify`, which would throw on bigint pks). No cast is needed — `json_to_recordset`\n // has a single json-typed signature. The `x(col type, …)` record definition and the alias-qualified\n // `t.*`/`x.*` join are raw text: the `USING`/recordset-join grammar requires those bare identifiers.\n await db.execute(\n sql`DELETE FROM ${targetTable} AS t USING json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,\n );\n }\n\n if (debug) console.log(`Deleted ${messages.length} rows using json_to_recordset`);\n}\n\n/**\n * Bulk UPDATE via `UPDATE … FROM json_to_recordset(…)` (ADR-0014 Phase 3), **grouped by the set of\n * non-PK columns** each row carries. Electric's default replica sends only the changed columns, so\n * two rows in one batch can set different columns; one `UPDATE … FROM` per distinct column-set keeps\n * each statement uniform. Safe from the same-PK join hazard because the fold already left one row per\n * PK, so no PK appears twice within a group.\n */\nexport async function applyBulkUpdatesToTable({ pg, target, messages, debug }: BulkKeyedApplyOptions) {\n const primaryKey = target.primaryKey;\n if (primaryKey.length === 0) throw new Error(\"applyBulkUpdatesToTable requires a primary key\");\n if (messages.length === 0) return;\n\n const pkSet = new Set(primaryKey);\n const groups = new Map<string, { setColumns: string[]; rows: Row<unknown>[] }>();\n for (const message of messages) {\n const data = message.value;\n const setColumns = Object.keys(data)\n .filter((column) => !pkSet.has(column))\n .sort();\n // A PK-only update sets nothing — the per-row applyMessageToTable returns early on this too.\n if (setColumns.length === 0) continue;\n const groupKey = setColumns.join(\" \");\n let group = groups.get(groupKey);\n if (!group) {\n group = { setColumns, rows: [] };\n groups.set(groupKey, group);\n }\n group.rows.push(Object.fromEntries([...primaryKey, ...setColumns].map((column) => [column, data[column]])));\n }\n\n const targetTable = target.table;\n const db = drizzleOverPg(pg);\n\n for (const { setColumns, rows } of groups.values()) {\n const casts = recordsetColumnCasts(target, [...primaryKey, ...setColumns]);\n const recordDef = casts.map((column) => `${quoteIdentifier(column.name)} ${column.castType}`).join(\", \");\n const setClause = setColumns\n .map((column) => `${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\", \");\n const whereJoin = primaryKey\n .map((column) => `t.${quoteIdentifier(column)} = x.${quoteIdentifier(column)}`)\n .join(\" AND \");\n\n for (let i = 0; i < rows.length; i += JSON_RECORDSET_BATCH) {\n const batch = rows.slice(i, i + JSON_RECORDSET_BATCH);\n // Tier ② (ADR-0028), as applyBulkDeletesToTable above: interpolated target table + single bound\n // `sql.param` batch (raw array, not `JSON.stringify` — bigint-safe), no cast needed; the `SET` /\n // `x(col type, …)` record def and the alias-qualified `t.*`/`x.*` join stay raw text (grammar).\n await db.execute(\n sql`UPDATE ${targetTable} AS t SET ${sql.raw(setClause)} FROM json_to_recordset(${sql.param(batch)}) AS x(${sql.raw(recordDef)}) WHERE ${sql.raw(whereJoin)}`,\n );\n }\n }\n\n if (debug) console.log(`Updated ${messages.length} rows using json_to_recordset`);\n}\n",
112
+ "import { index, jsonb, pgSchema, primaryKey, text } from \"drizzle-orm/pg-core\";\n\nimport type { ShapeSubscriptionState } from \"./subscription-state\";\n\n/**\n * The two metadata-store relations the sync engine provisions at boot (ADR-0028 decision 4). The\n * metadata schema name is dynamic (per-client config) but fixed at engine construction, so the tables\n * are built per schema string and memoized.\n *\n * ADR-0029 D3: these pgTables are the SINGLE SOURCE for the relations. `migrateSubscriptionMetadataTables`\n * (subscription-state.ts) renders their `CREATE TABLE`/`CREATE INDEX` DDL FROM these definitions via the\n * in-house `renderCreateTableSql` (schema.ts), and the DML paths query them directly — so the DDL and the\n * pgTable can no longer diverge, and the former drift guard in `tests/unit/sync-drizzle-executor.test.ts`\n * is now a plain provisioning round-trip.\n *\n * Property keys are deliberately snake_case to mirror the row shapes the callers already consume\n * (`shape_metadata`, `last_lsn`, `pk_json`, …), so a `select()` returns rows in the existing shape with\n * no alias mapping.\n */\n\nexport interface MetadataTables {\n /** `<schema>.subscriptions_metadata` — one row per subscription key. */\n readonly subscriptionsMetadata: ReturnType<typeof buildSubscriptionsMetadata>;\n /** `<schema>.shape_row_tags` — the tagged-subquery reason-set store (ADR-0023). */\n readonly shapeRowTags: ReturnType<typeof buildShapeRowTags>;\n}\n\nfunction buildSubscriptionsMetadata(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\"subscriptions_metadata\", {\n key: text(\"key\").primaryKey(),\n // JSONB NOT NULL — round-trips as a parsed object (drizzle's jsonb codec), matching the raw path.\n shape_metadata: jsonb(\"shape_metadata\").$type<Record<string, ShapeSubscriptionState>>().notNull(),\n // The LSN is persisted as TEXT (a bigint has no JSON/portable-column form); callers `BigInt(...)` it.\n last_lsn: text(\"last_lsn\").notNull(),\n });\n}\n\nfunction buildShapeRowTags(schema: ReturnType<typeof pgSchema>) {\n return schema.table(\n \"shape_row_tags\",\n {\n shape_table: text(\"shape_table\").notNull(),\n pk_json: text(\"pk_json\").notNull(),\n tag: text(\"tag\").notNull(),\n },\n (t) => [\n primaryKey({ columns: [t.shape_table, t.pk_json, t.tag] }),\n index(\"shape_row_tags_shape_tag_idx\").on(t.shape_table, t.tag),\n ],\n );\n}\n\nconst cache = new Map<string, MetadataTables>();\n\n/** The (memoized) metadata-store `pgTable`s for a given metadata schema name. */\nexport function getMetadataTables(metadataSchema: string): MetadataTables {\n let tables = cache.get(metadataSchema);\n if (!tables) {\n const schema = pgSchema(metadataSchema);\n tables = {\n subscriptionsMetadata: buildSubscriptionsMetadata(schema),\n shapeRowTags: buildShapeRowTags(schema),\n };\n cache.set(metadataSchema, tables);\n }\n return tables;\n}\n",
113
+ "import { getTableConfig, getViewConfig, type AnyPgTable } from \"drizzle-orm/pg-core\";\n\nimport {\n buildOverlayResolutionBarrier,\n buildSyncStateView,\n getLocalSyncPrimaryKeyColumns,\n getSyncRegistrySchema,\n getProjectedColumns,\n maybeQuoteIdentifier,\n quoteIdentifier,\n quoteSqlLiteral as quoteSqlStringLiteral,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { buildClearShapeTagsSql, shapeTableId } from \"./sync/tags\";\n\n/** Internal fully-qualified projection used within schema generation. */\ninterface ResolvedProjection {\n syncedTable: string;\n overlayTable?: string;\n journalTable?: string;\n readModel: string;\n /** The per-table `<table>_sync_state` convergence view (writable tables only — ADR-0011). */\n syncState: string;\n /**\n * The reconcile trigger's function — schema-qualified, because a function is a schema object.\n * Suffix-then-qualify (never `${qualifiedTable}_reconcile_on_sync`, which double-quotes a\n * non-public schema's qualified name into invalid SQL).\n */\n reconcileFunction: string;\n /**\n * The reconcile trigger itself — an UNqualified identifier. A trigger is not a schema object; it\n * is bound to its table via `ON <qualified table>`, so its name must not be schema-qualified.\n */\n reconcileTrigger: string;\n}\n\n/**\n * Local key/value metadata table. Holds the registry fingerprint the local store was\n * provisioned under (ADR-0006), so a registry change is detected on boot and the read\n * cache is rebuilt — rather than relying on a hand-bumped `idb://…-vN` suffix.\n */\nexport const LOCAL_META_TABLE = \"pgxsinkit_local_meta\";\nexport const REGISTRY_FINGERPRINT_KEY = \"registry_fingerprint\";\n\ntype TableColumn = ReturnType<typeof getProjectedColumns<AnyPgTable>>[number][\"column\"];\n\nexport function generateLocalSchemaSql<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const statements: string[] = [];\n const localSchema = getSyncRegistrySchema(registry);\n\n if (localSchema !== \"public\") {\n statements.push(`CREATE SCHEMA IF NOT EXISTS ${quoteIdentifier(localSchema)};`);\n }\n\n statements.push(\n `CREATE TABLE IF NOT EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} (\\n ${[\n \"key TEXT PRIMARY KEY\",\n \"value TEXT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n const enumDefinitions = collectEnumDefinitions(registry, localSchema);\n\n for (const enumDefinition of enumDefinitions) {\n statements.push(buildCreateEnumTypeSql(enumDefinition));\n }\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n // ADR-0021 §3: an `ephemeral` table's whole cluster is emitted as `TEMP` — bare (unqualified) object\n // names that resolve via `pg_temp` / search_path, so read- and write-ephemerality fall out together\n // (no durable trace). Object NAMES go bare+TEMP; column *types* (enums) stay in the persistent schema.\n // For a persistent table `temp` is \"\" and `objectSchema` is the registry schema → byte-identical output.\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const temp = ephemeral ? \"TEMP \" : \"\";\n\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n const syncedTablePrimaryKeyColumns = getLocalSyncPrimaryKeyColumns(entry);\n const baseColumnsSql = buildTableColumnSql(columns, syncedTablePrimaryKeyColumns, localSchema);\n\n statements.push(`CREATE ${temp}TABLE IF NOT EXISTS ${projection.syncedTable} (\\n ${baseColumnsSql}\\n);`);\n\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n if (!projection.overlayTable || !projection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${tableKey}`);\n }\n\n const journalTableName = entry.clientProjection?.journalTable;\n\n if (!journalTableName) {\n throw new Error(`journal table is required for writable table ${tableKey}`);\n }\n\n const primaryKeyColumns = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n\n return column;\n });\n const primaryKeyColumnNames = primaryKeyColumns.map((column) => column.name);\n const journalSequenceName = buildJournalSequenceName(journalTableName);\n const qualifiedJournalSequenceName = qualifyIdentifier(objectSchema, journalSequenceName);\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.overlayTable} (\\n ${[\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumnNames, localSchema)),\n \"overlay_kind VARCHAR(24) NOT NULL\",\n \"local_updated_at_us BIGINT NOT NULL\",\n ...buildCompositePrimaryKeyClauses(primaryKeyColumnNames),\n ].join(\",\\n \")}\\n);`,\n );\n\n statements.push(\n `CREATE ${temp}SEQUENCE IF NOT EXISTS ${qualifiedJournalSequenceName} AS integer START WITH 1 INCREMENT BY 1;`,\n );\n\n statements.push(\n `CREATE ${temp}TABLE IF NOT EXISTS ${projection.journalTable} (\\n ${[\n \"mutation_id UUID PRIMARY KEY\",\n ...primaryKeyColumns.map((column) => `${column.name} ${mapColumnType(column, localSchema)} NOT NULL`),\n \"entity_key_json TEXT NOT NULL\",\n `mutation_seq INTEGER NOT NULL UNIQUE DEFAULT nextval(${quoteSqlStringLiteral(qualifiedJournalSequenceName)})::integer`,\n \"mutation_kind VARCHAR(24) NOT NULL\",\n \"status VARCHAR(24) NOT NULL\",\n // The registry fingerprint (ADR-0004) this mutation was authored under, so a\n // version-boundary crossing is known before sending (ADR-0006 decision 4).\n \"registry_version TEXT\",\n // ADR-0011 reserved hook: the Server version the entity was observed at when this mutation\n // was authored. The slot lives on the journal (per-mutation, like registry_version above);\n // the stale-write conflict policy (ADR-0015) decides its exact semantics and stamps it.\n \"base_server_version BIGINT\",\n // ADR-0022: the dynamic write-unit tag stamped by a `transaction({ mode })` block — the shared\n // unit id grouping co-committed mutations, and the unit's write-mode. NULL for the default path\n // (an untagged mutation), where the flusher derives mode + unit from the table's static group.\n \"write_unit TEXT\",\n \"write_mode VARCHAR(24)\",\n \"payload_json TEXT NOT NULL\",\n \"attempt_count INTEGER NOT NULL DEFAULT 0\",\n \"last_error TEXT\",\n \"last_http_status INTEGER\",\n \"conflict_reason TEXT\",\n \"server_updated_at_us BIGINT\",\n \"enqueued_at_us BIGINT NOT NULL\",\n \"next_retry_at_us BIGINT\",\n \"sent_at_us BIGINT\",\n \"acked_at_us BIGINT\",\n \"updated_at_us BIGINT NOT NULL\",\n ].join(\",\\n \")}\\n);`,\n );\n\n // Journal indexes render through the SAME core the pgTable-driven renderer uses\n // ({@link renderCreateIndexStatement}), so the two index-emitting paths cannot drift in statement\n // shape. These names/columns are registry-derived bare identifiers, passed verbatim (the pgTable\n // path is the one that quotes) — output stays byte-identical to the former hand-built statements.\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_idx`, [\n \"status\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_status_retry_idx`, [\n \"status\",\n \"next_retry_at_us\",\n \"enqueued_at_us\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_pk_seq_idx`, [\n ...entry.primaryKey.columns,\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_seq_idx`, [\n \"entity_key_json\",\n \"mutation_seq\",\n ]),\n );\n statements.push(\n renderCreateIndexStatement(projection.journalTable, `${journalTableName}_entity_status_seq_idx`, [\n \"entity_key_json\",\n \"status\",\n \"mutation_seq\",\n ]),\n );\n\n // Trigger: automatically clear overlay + journal entries when the sync\n // echo arrives. Fires on INSERT/UPDATE (new data from Electric) and DELETE\n // (row removed on server, synced back via Electric).\n const pkMatchSql = (alias: string) =>\n primaryKeyColumns\n .map((col) => `\"${alias}\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n const pkOverlayMatchSql = primaryKeyColumns\n .map((col) => `\"overlay\".\"${col.name}\" = COALESCE(NEW.\"${col.name}\", OLD.\"${col.name}\")`)\n .join(\" AND \");\n\n // ADR-0010: an acked create/update clears only once the synced echo's Server version reaches\n // the write's acked version — never on a bare key-match, which a stale or reordered echo could\n // satisfy and flip the read model to neither the optimistic nor the converged value. A delete\n // stays resolved by synced-row absence (NEW is NULL on the synced DELETE; the barrier reads\n // NULL there, so it never clears a create/update on a delete echo). One predicate, shared with\n // reconcileTable (mutation.ts), so the two sites cannot drift.\n const resolutionBarrier = buildOverlayResolutionBarrier(entry, { syncedAlias: \"NEW\" });\n\n // ADR-0021 §3: an ephemeral cluster's reconcile function lives in `pg_temp` alongside its temp table\n // (a permanent function cannot be a temp trigger's handler cleanly); a persistent one is unchanged.\n const reconcileFunctionRef = ephemeral ? `pg_temp.${projection.reconcileFunction}` : projection.reconcileFunction;\n\n statements.push(\n `CREATE OR REPLACE FUNCTION ${reconcileFunctionRef}() RETURNS TRIGGER AS $$\\n` +\n `BEGIN\\n` +\n ` -- ADR-0015: retire a terminal 'conflicted' row once a LATER write on the same entity has\\n` +\n ` -- been acked — that later write IS the resolution. The acked resolver is cleared by the\\n` +\n ` -- acked-delete below the moment its echo lands; if that echo wins the race against the\\n` +\n ` -- post-flush reconcileTable pass, the resolver is gone before reconcileTable's supersede-\\n` +\n ` -- retire can see it and the conflicted row orphans (its surfaced conflict_state never\\n` +\n ` -- clears). Doing the retire here too — in the trigger that has the echo context, BEFORE the\\n` +\n ` -- acked-clear — closes that race. Mirrors reconcileTable's retire (mutation.ts).\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"conflicted\"\\n` +\n ` USING ${projection.journalTable} AS \"resolver\"\\n` +\n ` WHERE \"conflicted\".status = 'conflicted' AND (${pkMatchSql(\"conflicted\")})\\n` +\n ` AND \"resolver\".entity_key_json = \"conflicted\".entity_key_json\\n` +\n ` AND \"resolver\".mutation_seq > \"conflicted\".mutation_seq\\n` +\n ` AND \"resolver\".status = 'acked';\\n` +\n ` DELETE FROM ${projection.journalTable} AS \"journal\"\\n` +\n ` WHERE status = 'acked' AND (${pkMatchSql(\"journal\")})\\n` +\n ` AND (\\n` +\n ` (TG_OP <> 'DELETE' AND mutation_kind <> 'delete' AND ${resolutionBarrier})\\n` +\n ` OR (TG_OP = 'DELETE' AND mutation_kind = 'delete')\\n` +\n ` );\\n` +\n ` DELETE FROM ${projection.overlayTable} AS \"overlay\"\\n` +\n ` WHERE (${pkOverlayMatchSql})\\n` +\n ` AND NOT EXISTS (\\n` +\n ` SELECT 1 FROM ${projection.journalTable} AS j\\n` +\n ` WHERE (${pkMatchSql(\"j\")})\\n` +\n ` );\\n` +\n ` RETURN COALESCE(NEW, OLD);\\n` +\n `END;\\n` +\n `$$ LANGUAGE plpgsql;`,\n );\n\n statements.push(\n `CREATE OR REPLACE TRIGGER ${projection.reconcileTrigger}\\n` +\n `AFTER INSERT OR UPDATE OR DELETE ON ${projection.syncedTable}\\n` +\n `FOR EACH ROW EXECUTE FUNCTION ${reconcileFunctionRef}();`,\n );\n\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.readModel} AS\\n${buildReadModelViewSql(\n entry,\n projection,\n columns.map((column) => column.name),\n )};`,\n );\n\n // ADR-0011: the per-table convergence view — a derived projection over synced + overlay +\n // journal, distinct from the (lean) read model, whose acked-unobserved status derives from the\n // same barrier predicate the reconcile trigger above uses (decision 4, anti-drift).\n statements.push(\n `CREATE OR REPLACE ${temp}VIEW ${projection.syncState} AS\\n${buildSyncStateView(entry, {\n syncedTable: projection.syncedTable,\n overlayTable: projection.overlayTable,\n journalTable: projection.journalTable,\n })};`,\n );\n }\n\n return `${statements.join(\"\\n\\n\")}\\n`;\n}\n\nfunction buildReadModelViewSql(\n entry: SyncTableEntry<AnyPgTable>,\n projection: ResolvedProjection,\n columnNames: string[],\n) {\n if (!projection.overlayTable) {\n throw new Error(`overlay table is required for writable table ${projection.syncedTable}`);\n }\n\n const pkMatch = buildPrimaryKeyMatch(entry.primaryKey.columns);\n const syncedLocalUpdatedExpression = columnNames.includes(\"updated_at_us\") ? \"t.updated_at_us\" : \"CAST(0 AS BIGINT)\";\n\n return [\n \"SELECT\",\n ` ${columnNames.join(\",\\n \")},`,\n \" overlay_kind,\",\n \" local_updated_at_us\",\n `FROM ${projection.overlayTable}`,\n `WHERE overlay_kind <> 'pending_delete'`,\n \"UNION ALL\",\n \"SELECT\",\n ` ${columnNames.map((name) => `t.${name}`).join(\",\\n \")},`,\n ` 'synced' AS overlay_kind,`,\n ` ${syncedLocalUpdatedExpression} AS local_updated_at_us`,\n `FROM ${projection.syncedTable} AS t`,\n \"WHERE NOT EXISTS (\",\n \" SELECT 1\",\n ` FROM ${projection.overlayTable} AS o`,\n ` WHERE ${pkMatch}`,\n \")\",\n ].join(\"\\n\");\n}\n\nfunction buildTableColumnSql(columns: TableColumn[], primaryKeyColumns: string[], localSchema: string) {\n return [\n ...columns.map((column) => buildColumnDefinition(column, primaryKeyColumns, localSchema)),\n ...buildCompositePrimaryKeyClauses(primaryKeyColumns),\n ].join(\",\\n \");\n}\n\n/**\n * Render `CREATE TABLE IF NOT EXISTS` (plus a `CREATE INDEX IF NOT EXISTS` per declared index) for a\n * Drizzle `pgTable` / `pgSchema.table`, through the SAME column/PK/type machinery\n * ({@link buildTableColumnSql} → {@link buildColumnDefinition} → {@link mapColumnType}) that\n * {@link generateLocalSchemaSql} uses for every other local relation. The table is schema-qualified\n * when it declares a schema and bare otherwise (per the table object). Column types come from each\n * column's `getSQLType()`, NOT NULL and single-column PRIMARY KEY inline, composite PKs as a trailing\n * clause. Enum column types are qualified into the table's own schema — the metadata pgTables carry\n * none, but the path is shared with the local-store generator so it must stay honest.\n *\n * ADR-0029 D3: the metadata-store DDL renders from its `metadata-tables.ts` pgTables through this,\n * making the pgTable the single source. The OUTPUT is tier-③-by-nature runtime DDL (schema/table\n * identifiers assembled at construction), but it is GENERATED from the model, never hand-maintained.\n */\nexport function renderCreateTableSql(table: AnyPgTable): string[] {\n const config = getTableConfig(table);\n const schemaName = config.schema ?? \"public\";\n const qualifiedTableName = qualifyIdentifier(schemaName, config.name);\n const primaryKeyColumns = collectPgTablePrimaryKeyColumns(config);\n const columnSql = buildTableColumnSql(config.columns as unknown as TableColumn[], primaryKeyColumns, schemaName);\n\n const statements = [`CREATE TABLE IF NOT EXISTS ${qualifiedTableName} (\\n ${columnSql}\\n);`];\n\n for (const index of config.indexes) {\n statements.push(renderCreateIndexSql(qualifiedTableName, index));\n }\n\n return statements;\n}\n\n/** The PK column names of a `pgTable` — column-level `.primaryKey()` first, then composite `primaryKey({…})`. */\nfunction collectPgTablePrimaryKeyColumns(config: ReturnType<typeof getTableConfig>): string[] {\n const columnLevel = config.columns.filter((column) => column.primary).map((column) => column.name);\n const composite = config.primaryKeys.flatMap((pk) => pk.columns.map((column) => column.name));\n return [...columnLevel, ...composite];\n}\n\nfunction renderCreateIndexSql(qualifiedTableName: string, index: ReturnType<typeof getTableConfig>[\"indexes\"][number]) {\n const { name, unique, columns, where, method, with: withParams } = index.config;\n if (!name) {\n throw new Error(\"renderCreateIndexSql: anonymous indexes are not supported (declare a name)\");\n }\n // This renderer emits only a plain ascending btree over bare columns. Any modifier it does not\n // render must fail loudly — silently dropping one would produce a local index that differs from the\n // pgTable declaration (the very DDL-vs-model divergence ADR-0029 D3 removes for the metadata store).\n if (where) {\n throw new Error(`renderCreateIndexSql: partial indexes (.where) are not supported (index ${name})`);\n }\n if (method && method.toLowerCase() !== \"btree\") {\n throw new Error(\n `renderCreateIndexSql: non-btree index methods (.using \"${method}\") are not supported (index ${name})`,\n );\n }\n if (withParams && Object.keys(withParams).length > 0) {\n throw new Error(`renderCreateIndexSql: index storage parameters (.with) are not supported (index ${name})`);\n }\n const columnExpressions = columns.map((column) => {\n const columnName = (column as { name?: unknown }).name;\n if (typeof columnName !== \"string\") {\n throw new Error(`renderCreateIndexSql: expression index columns are not supported (index ${name})`);\n }\n const indexConfig = (column as { indexConfig?: { order?: string; nulls?: string; opClass?: string } }).indexConfig;\n if (indexConfig?.order === \"desc\") {\n throw new Error(`renderCreateIndexSql: descending index columns (.desc()) are not supported (index ${name})`);\n }\n // Drizzle fills `nulls` with the ascending-btree default (\"last\") on every column; only an\n // explicit NULLS FIRST diverges from what we render (a plain ascending btree is NULLS LAST).\n if (indexConfig?.nulls === \"first\") {\n throw new Error(`renderCreateIndexSql: NULLS FIRST ordering (.nullsFirst()) is not supported (index ${name})`);\n }\n if (indexConfig?.opClass) {\n throw new Error(`renderCreateIndexSql: index operator classes (.op()) are not supported (index ${name})`);\n }\n return maybeQuoteIdentifier(columnName);\n });\n\n return renderCreateIndexStatement(qualifiedTableName, maybeQuoteIdentifier(name), columnExpressions, { unique });\n}\n\n/**\n * The shared `CREATE INDEX` core: assemble one\n * `CREATE [UNIQUE] INDEX IF NOT EXISTS <name> ON <table> (<cols>)` over a qualified table, an\n * already-rendered index name, and already-rendered plain ascending column expressions. BOTH the\n * pgTable-driven renderer ({@link renderCreateIndexSql}) and the journal-index emitter in\n * {@link generateLocalSchemaSql} go through here, so the two index-emitting paths cannot drift in\n * statement shape. Identifier quoting is the caller's responsibility — the pgTable path quotes via\n * `maybeQuoteIdentifier`; the journal path passes its registry-derived bare names/columns verbatim —\n * this core only fixes the surrounding statement text.\n */\nfunction renderCreateIndexStatement(\n qualifiedTableName: string,\n indexName: string,\n columnExpressions: readonly string[],\n options: { unique?: boolean } = {},\n): string {\n const uniqueSql = options.unique ? \"UNIQUE \" : \"\";\n return `CREATE ${uniqueSql}INDEX IF NOT EXISTS ${indexName} ON ${qualifiedTableName} (${columnExpressions.join(\", \")});`;\n}\n\nfunction buildColumnDefinition(column: TableColumn, primaryKeyColumns: string[], localSchema: string) {\n const typeSql = mapColumnType(column, localSchema);\n const notNullSql = column.notNull ? \" NOT NULL\" : \"\";\n const primaryKeySql = primaryKeyColumns.length === 1 && primaryKeyColumns.includes(column.name) ? \" PRIMARY KEY\" : \"\";\n return `${column.name} ${typeSql}${notNullSql}${primaryKeySql}`;\n}\n\nfunction buildCompositePrimaryKeyClauses(primaryKeyColumns: string[]) {\n if (primaryKeyColumns.length <= 1) {\n return [];\n }\n\n return [`PRIMARY KEY (${primaryKeyColumns.join(\", \")})`];\n}\n\nfunction mapColumnType(column: TableColumn, localSchema: string) {\n const baseTypeSql = readBaseColumnTypeSql(column, localSchema);\n const dimensions = readArrayDimensions(column);\n\n if (dimensions > 0) {\n return `${baseTypeSql}${\"[]\".repeat(dimensions)}`;\n }\n\n return baseTypeSql;\n}\n\nfunction readBaseColumnTypeSql(column: TableColumn, localSchema: string) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (enumDefinition) {\n return qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n }\n\n const sqlType = (column as { getSQLType(): string }).getSQLType();\n\n if (!sqlType) {\n throw new Error(`Unsupported column type for local schema generation: ${column.columnType}`);\n }\n\n return sqlType;\n}\n\ntype EnumDefinition = {\n schemaName: string;\n enumName: string;\n enumValues: string[];\n};\n\nfunction collectEnumDefinitions(registry: SyncTableRegistry, localSchema: string) {\n const enumDefinitionsByName = new Map<string, EnumDefinition>();\n\n for (const entry of Object.values(registry)) {\n const columns = getProjectedColumns(entry).map(({ column }) => column);\n\n for (const column of columns) {\n const enumDefinition = readEnumColumnDefinition(column, localSchema);\n\n if (!enumDefinition) {\n continue;\n }\n\n const existingDefinition = enumDefinitionsByName.get(enumDefinition.enumName);\n\n if (!existingDefinition) {\n enumDefinitionsByName.set(enumDefinition.enumName, enumDefinition);\n continue;\n }\n\n if (!areEnumValuesEqual(existingDefinition.enumValues, enumDefinition.enumValues)) {\n throw new Error(\n `Enum ${enumDefinition.enumName} has conflicting values in sync registry: ${existingDefinition.enumValues.join(\", \")} vs ${enumDefinition.enumValues.join(\", \")}`,\n );\n }\n }\n }\n\n return [...enumDefinitionsByName.values()].sort((left, right) => left.enumName.localeCompare(right.enumName));\n}\n\nfunction buildCreateEnumTypeSql(enumDefinition: EnumDefinition) {\n const typeIdentifier = qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName);\n const enumValuesSql = enumDefinition.enumValues.map((value) => quoteSqlStringLiteral(value)).join(\", \");\n\n return [\n \"DO $$\",\n \"BEGIN\",\n \" IF NOT EXISTS (\",\n \" SELECT 1\",\n \" FROM pg_type AS t\",\n \" INNER JOIN pg_namespace AS n ON n.oid = t.typnamespace\",\n ` WHERE t.typname = ${quoteSqlStringLiteral(enumDefinition.enumName)}`,\n ` AND n.nspname = ${quoteSqlStringLiteral(enumDefinition.schemaName)}`,\n \" ) THEN\",\n ` CREATE TYPE ${typeIdentifier} AS ENUM (${enumValuesSql});`,\n \" END IF;\",\n \"END\",\n \"$$;\",\n ].join(\"\\n\");\n}\n\nfunction areEnumValuesEqual(left: string[], right: string[]) {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let index = 0; index < left.length; index += 1) {\n if (left[index] !== right[index]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction readEnumColumnDefinition(column: TableColumn, localSchema: string): EnumDefinition | undefined {\n const candidate = column as TableColumn & {\n enum?: {\n enumName?: unknown;\n enumValues?: unknown;\n };\n };\n\n if (!candidate.enum || typeof candidate.enum.enumName !== \"string\" || !Array.isArray(candidate.enum.enumValues)) {\n return undefined;\n }\n\n const enumValues = candidate.enum.enumValues.filter((value): value is string => typeof value === \"string\");\n\n if (enumValues.length !== candidate.enum.enumValues.length) {\n throw new Error(\n `Enum ${candidate.enum.enumName} includes non-string values and cannot be emitted in local schema SQL`,\n );\n }\n\n return {\n schemaName: localSchema,\n enumName: candidate.enum.enumName,\n enumValues,\n };\n}\n\nfunction readArrayDimensions(column: TableColumn) {\n const arrayColumn = column as TableColumn & { dimensions?: number };\n return arrayColumn.dimensions ?? 0;\n}\n\nfunction buildPrimaryKeyMatch(primaryKeyColumns: string[]) {\n return primaryKeyColumns.map((column) => `o.${column} = t.${column}`).join(\" AND \");\n}\n\nfunction getClientProjection(entry: SyncTableEntry, tableKey: string, localSchema: string): ResolvedProjection {\n const projection = baseProjection(entry, tableKey);\n const syncedTableName = projection.syncedTable ?? tableKey;\n const readModelName = entry.view != null ? getViewConfig(entry.view).name : syncedTableName;\n\n return {\n syncedTable: qualifyIdentifier(localSchema, syncedTableName),\n ...(projection.overlayTable ? { overlayTable: qualifyIdentifier(localSchema, projection.overlayTable) } : {}),\n ...(projection.journalTable ? { journalTable: qualifyIdentifier(localSchema, projection.journalTable) } : {}),\n readModel: qualifyIdentifier(localSchema, readModelName),\n syncState: qualifyIdentifier(localSchema, `${syncedTableName}_sync_state`),\n reconcileFunction: qualifyIdentifier(localSchema, `${syncedTableName}_reconcile_on_sync`),\n reconcileTrigger: maybeQuoteIdentifier(`${syncedTableName}_reconcile_on_sync`),\n };\n}\n\nfunction baseProjection(entry: SyncTableEntry, tableKey: string) {\n if (!entry.clientProjection) {\n throw new Error(`clientProjection is required for local client table ${tableKey}`);\n }\n\n return entry.clientProjection;\n}\n\nfunction qualifyIdentifier(schemaName: string, objectName: string) {\n if (schemaName === \"public\") {\n // Quote only when required so existing generated SQL stays stable, but a table/view named\n // after a reserved word (e.g. `group`) is a valid Postgres identifier and MUST be quoted or\n // the generated DDL and read queries fail to parse. The row-applier (src/sync) always quotes.\n return maybeQuoteIdentifier(objectName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(objectName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\n/**\n * Drop the reconstructible **read cache** — the synced tables and their read-model views\n * and reconcile triggers/functions — while preserving the authority tables (overlay,\n * journal, the local-meta table). Re-running {@link generateLocalSchemaSql} then rebuilds\n * the synced tables at the current shape, and a re-sync refills them (ADR-0006). This is\n * the named drop primitive a returning-online upgrade uses after a clean drain.\n */\nexport function buildDropReadCacheSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (entry.mode !== \"readonly\") {\n statements.push(`DROP VIEW IF EXISTS ${projection.syncState};`);\n statements.push(`DROP VIEW IF EXISTS ${projection.readModel};`);\n statements.push(`DROP TRIGGER IF EXISTS ${projection.reconcileTrigger} ON ${projection.syncedTable};`);\n statements.push(`DROP FUNCTION IF EXISTS ${projection.reconcileFunction}();`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${projection.syncedTable} CASCADE;`);\n }\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Wipe the **entire** local store provisioned from the registry — the read cache plus the\n * authority tables (overlay, journal, sequences), the enum types, and the local-meta row.\n * This is the full teardown reused by `destroy()` (ADR-0005 decision 5) and by the\n * drain-then-drop upgrade once a clean drain has confirmed nothing is owed (ADR-0006).\n */\nexport function buildWipeLocalStoreSql<TRegistry extends SyncTableRegistry>(registry: TRegistry): string {\n const localSchema = getSyncRegistrySchema(registry);\n const statements: string[] = [buildDropReadCacheSql(registry).trimEnd()];\n\n for (const [tableKey, entry] of Object.entries(registry)) {\n if (entry.mode === \"readonly\") {\n continue;\n }\n\n const projection = getClientProjection(entry, tableKey, localSchema);\n\n if (projection.overlayTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.overlayTable} CASCADE;`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`DROP TABLE IF EXISTS ${projection.journalTable} CASCADE;`);\n statements.push(\n `DROP SEQUENCE IF EXISTS ${qualifyIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable))};`,\n );\n }\n }\n\n for (const enumDefinition of collectEnumDefinitions(registry, localSchema)) {\n statements.push(`DROP TYPE IF EXISTS ${qualifyIdentifier(enumDefinition.schemaName, enumDefinition.enumName)};`);\n }\n\n statements.push(`DROP TABLE IF EXISTS ${qualifyIdentifier(localSchema, LOCAL_META_TABLE)} CASCADE;`);\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n\n/**\n * Clean-truncate a single table's local read cache so a desynced `lazy` relation (ADR-0021 §2) returns\n * to an empty, dormant state: the synced table and — for a writable table — its optimistic overlay and\n * the journal, plus a sequence restart. It does NOT drop the cluster (the table/views/trigger persist),\n * so a later re-reference re-streams into it without a schema rebuild. Ephemeral-aware: bare/`pg_temp`\n * names for an ephemeral cluster, schema-qualified for a persistent one — mirroring\n * {@link generateLocalSchemaSql}. The caller (`desync`) first stops the group's stream (so nothing\n * re-populates mid-truncate) and refuses when the journal owes unsettled writes (so this never drops\n * un-acked local intent).\n */\nexport function buildDesyncTableSql<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string,\n): string {\n const entry = registry[tableKey];\n\n if (!entry) {\n throw new Error(`buildDesyncTableSql: unknown table ${tableKey}`);\n }\n\n const localSchema = getSyncRegistrySchema(registry);\n const ephemeral = entry.retention === \"ephemeral\";\n const objectSchema = ephemeral ? \"public\" : localSchema;\n const projection = getClientProjection(entry, tableKey, objectSchema);\n const statements: string[] = [`TRUNCATE TABLE ${projection.syncedTable};`];\n\n if (entry.mode !== \"readonly\") {\n if (projection.overlayTable) {\n statements.push(`TRUNCATE TABLE ${projection.overlayTable};`);\n }\n\n if (projection.journalTable && entry.clientProjection?.journalTable) {\n statements.push(`TRUNCATE TABLE ${projection.journalTable};`);\n statements.push(\n `ALTER SEQUENCE ${qualifyIdentifier(objectSchema, buildJournalSequenceName(entry.clientProjection.journalTable))} RESTART WITH 1;`,\n );\n }\n }\n\n // ADR-0023 Slice 2: a desync reverts the relation to dormant and deletes its subscription, so the next\n // activation re-streams from scratch — drop this shape's tag-set too, or it would orphan tags for rows\n // that never come back. The key matches what the engine writes (`shapeTableId(shape.schema, table)`):\n // for ephemeral the engine passes no schema (→ `public`), exactly this `objectSchema`.\n const syncedTableNameRaw = baseProjection(entry, tableKey).syncedTable ?? tableKey;\n statements.push(buildClearShapeTagsSql(shapeTableId(objectSchema, syncedTableNameRaw)));\n\n return `${statements.join(\"\\n\")}\\n`;\n}\n",
114
+ "import type { ColumnBuilderBase } from \"drizzle-orm\";\nimport { getColumns } from \"drizzle-orm\";\nimport {\n bigint,\n boolean,\n customType,\n getTableConfig,\n integer,\n pgSchema,\n pgTable,\n pgView,\n text,\n uuid,\n varchar,\n type AnyPgTable,\n type PgColumn,\n type PgTableWithColumns,\n type PgViewWithSelection,\n} from \"drizzle-orm/pg-core\";\n\nimport {\n deriveSyncColumnTypes,\n getLocalSyncedTablePrimaryKeyColumns,\n getSyncRegistrySchema,\n type SyncColumnType,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport { LOCAL_META_TABLE } from \"./schema\";\n\n/**\n * Runtime Drizzle objects for the GENERATED local-store relations (ADR-0004): the per-writable-table\n * overlay (`<t>_overlay`), journal (`<t>_mutations`), sync-state view (`<t>_sync_state`), the projected\n * synced read cache, and the `pgxsinkit_local_meta` key/value table. The schema generator\n * (`schema.ts`) remains the one authority for the DDL — these objects exist so the mutation runtime,\n * consumers, and tests can AUTHOR queries against those relations as tier-① Drizzle objects\n * (rename-safe, type-checked) instead of hand-written SQL strings.\n *\n * They are query-authoring objects only — never feed them to drizzle-kit generation; the generated\n * DDL in `schema.ts` is the source of truth for the physical shape, and `local-tables.test`-level\n * coverage (the existing overlay/journal suites run against generator-provisioned stores) is what\n * keeps the two aligned.\n *\n * Every object is schema-QUALIFIED with the registry's own local schema (via `getSyncRegistrySchema`).\n * `entry.table` / `entry.localTable` are already qualified the same way (`defineSyncTable` builds them\n * with the caller's schema, and `attachSyncRegistrySchema` throws unless they match the registry schema),\n * so for the synced read cache the factory just tracks a `clientProjection.syncedTable` rename. The\n * factories earn their keep where no equally-qualified entry handle exists: `entry.view` is built\n * schema-UNqualified (a bare `pgView`), so a store in a non-public schema must author the read model\n * through `getReadModelView`; and the overlay / journal / sync-state relations have NO entry handle at all\n * — these factories are the only Drizzle objects for them. Each factory MEMOIZES its result per\n * `(registry, tableKey)` (the `pgxsinkit_local_meta` table per local schema), so repeated calls hand back\n * the same object identity.\n *\n * Typing tracks the registry the caller holds: with a concretely-typed registry (built by\n * `defineSyncRegistry`) the synced/overlay/read-model objects carry the entry's real per-column types, so\n * `.select({ x: overlay.col })`, `$inferInsert`, and `.values()` all typecheck by property key; with a\n * bare `SyncTableRegistry` they degrade to an open index-signature shape reached by bracket access.\n * `JournalTable` / `SyncStateView` are ALWAYS conservatively indexed for their entity/PK columns (the PK\n * name set is not recoverable at the type level — see those types).\n */\n\n/**\n * Microsecond/bigint columns the mutation runtime handles as **strings** (the JSON-safe form it has\n * always used): passthrough both ways, `bigint` in DDL position. Reads through the raw `MutationDb`\n * seam bypass drizzle result mapping anyway; this keeps `.values()`/`.set()` accepting the runtime's\n * string values without a lossy JS-number hop.\n */\nconst bigintText = customType<{ data: string; driverData: string }>({\n dataType() {\n return \"bigint\";\n },\n});\n\nfunction buildJournalFixedColumns() {\n return {\n mutationId: uuid(\"mutation_id\").primaryKey(),\n entityKeyJson: text(\"entity_key_json\").notNull(),\n mutationSeq: integer(\"mutation_seq\").notNull(),\n mutationKind: varchar(\"mutation_kind\", { length: 24 }).notNull(),\n status: varchar(\"status\", { length: 24 }).notNull(),\n registryVersion: text(\"registry_version\"),\n baseServerVersion: bigintText(\"base_server_version\"),\n writeUnit: text(\"write_unit\"),\n writeMode: varchar(\"write_mode\", { length: 24 }),\n payloadJson: text(\"payload_json\").notNull(),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastError: text(\"last_error\"),\n lastHttpStatus: integer(\"last_http_status\"),\n conflictReason: text(\"conflict_reason\"),\n serverUpdatedAtUs: bigintText(\"server_updated_at_us\"),\n enqueuedAtUs: bigintText(\"enqueued_at_us\").notNull(),\n nextRetryAtUs: bigintText(\"next_retry_at_us\"),\n sentAtUs: bigintText(\"sent_at_us\"),\n ackedAtUs: bigintText(\"acked_at_us\"),\n updatedAtUs: bigintText(\"updated_at_us\").notNull(),\n };\n}\n\nfunction buildOverlayFixedColumns() {\n return {\n overlayKind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n localUpdatedAtUs: bigintText(\"local_updated_at_us\").notNull(),\n };\n}\n\n/**\n * The two overlay columns the `<t>_read_model` view carries on top of the projected synced columns.\n * Read through real drizzle result mapping (a live query, not the raw `MutationDb` seam), so\n * `local_updated_at_us` is a `mode: \"bigint\"` int8 (PGlite returns it as a string at runtime) rather than\n * the journal/overlay `bigintText` passthrough. Snake-case property keys so consumers reach them the same\n * way the generator names them (`view[\"overlay_kind\"]`).\n */\nfunction buildReadModelFixedColumns() {\n return {\n overlay_kind: varchar(\"overlay_kind\", { length: 24 }).notNull(),\n local_updated_at_us: bigint(\"local_updated_at_us\", { mode: \"bigint\" }).notNull(),\n };\n}\n\nfunction buildSyncStateFixedColumns() {\n return {\n observedServerVersion: bigint(\"observed_server_version\", { mode: \"bigint\" }),\n ackedServerVersion: bigint(\"acked_server_version\", { mode: \"bigint\" }),\n pendingCount: bigint(\"pending_count\", { mode: \"number\" }).notNull(),\n hasAckedUnobservedWrite: boolean(\"has_acked_unobserved_write\").notNull(),\n localDeletePending: boolean(\"local_delete_pending\").notNull(),\n conflictState: text(\"conflict_state\"),\n quarantinedCount: bigint(\"quarantined_count\", { mode: \"number\" }).notNull(),\n quarantineState: text(\"quarantine_state\"),\n };\n}\n\n// Phantom shape tables: never created, never queried — they exist only so the derived relation types\n// carry strong typing on the FIXED column keys. The per-entry ENTITY columns are layered on top from\n// the concrete registry entry (see the `*<TEntry>` types below), so a caller whose registry is\n// concretely typed reaches real, projected `PgColumn`s by property key; only a caller holding a bare\n// `SyncTableRegistry` falls back to the open index-signature form these shapes' generic default gives.\nconst journalShape = pgTable(\"_pgxsinkit_journal_shape\", buildJournalFixedColumns());\nconst overlayShape = pgTable(\"_pgxsinkit_overlay_shape\", buildOverlayFixedColumns());\nconst syncStateShape = pgView(\"_pgxsinkit_sync_state_shape\", buildSyncStateFixedColumns()).existing();\nconst readModelShape = pgView(\"_pgxsinkit_read_model_shape\", buildReadModelFixedColumns()).existing();\nconst localMetaShape = pgTable(LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n});\n\n/**\n * The entry's PROJECTED local table type — its server columns minus `clientProjection.omitColumns`,\n * exactly the shape `defineSyncTable` stamped onto `entry.localTable`. When `TEntry` is a concrete\n * entry (a registry built by `defineSyncRegistry`) this carries the real, typed columns; when it is a\n * bare `SyncTableEntry` (a generic `SyncTableRegistry`) it degrades to `AnyPgTable`, which pushes every\n * derived type below onto the open `Record<string, PgColumn>` index-signature fallback.\n */\ntype EntryLocalTable<TEntry> =\n TEntry extends SyncTableEntry<AnyPgTable, infer TLocal extends AnyPgTable> ? TLocal : AnyPgTable;\n\n/** The entry's projected columns keyed by drizzle property key (or the open `PgColumns` fallback). */\ntype EntryColumns<TEntry> = EntryLocalTable<TEntry>[\"_\"][\"columns\"];\ntype OverlayFixedColumns = (typeof overlayShape)[\"_\"][\"columns\"];\ntype ReadModelFixedColumns = (typeof readModelShape)[\"_\"][\"selectedFields\"];\n\n/**\n * The `<t>_overlay` optimistic-intent table: the entry's PROJECTED columns (same builders the generator\n * and `entry.localTable` carry) merged with the two fixed overlay columns. The entity columns read\n * back through real drizzle result mapping, so their types mirror the projected table exactly (a\n * `mode: \"bigint\"` column is `bigint`, etc.). The two overlay columns are `bigintText` passthrough\n * (`local_updated_at_us` reads as a string). `TEntry` defaults to a bare entry, giving the open\n * index-signature form the mutation runtime (generic over any registry) needs.\n */\nexport type OverlayTable<TEntry = SyncTableEntry> = PgTableWithColumns<{\n name: string;\n schema: string | undefined;\n columns: EntryColumns<TEntry> & OverlayFixedColumns;\n dialect: \"pg\";\n}>;\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004): the entry's PROJECTED columns under their\n * property keys plus the two fixed overlay columns (`overlay_kind`, `local_updated_at_us`). Read\n * through a live query, so `local_updated_at_us` is an int8 `mode: \"bigint\"` column.\n */\nexport type ReadModelView<TEntry = SyncTableEntry> = PgViewWithSelection<\n string,\n true,\n EntryColumns<TEntry> & ReadModelFixedColumns\n>;\n\n/**\n * The projected SYNCED read-cache table — the entry's projected local table (or `AnyPgTable` fallback).\n * Type-level note: the phantom relation name here is the original `tableName` (inherited from\n * `ProjectedLocalTable`), but the runtime object `getSyncedLocalTable` returns honours a\n * `clientProjection.syncedTable` rename — so the rendered SQL uses the runtime name, not this type's name.\n */\nexport type SyncedLocalTable<TEntry = SyncTableEntry> = EntryLocalTable<TEntry>;\n\n/**\n * The `<t>_mutations` journal: fixed runtime columns + the entry's PK columns (index-signature access).\n * Kept conservatively indexed: the journal carries ONLY the PK columns, keyed by DB COLUMN NAME and\n * type-erased to `text`, but neither the PK column-name set nor the \"PK only\" subset is recoverable at\n * the type level from `SyncTableEntry` (its `primaryKey.columns` is an un-narrowed `string[]`), so an\n * honest per-entry type is not representable without a footgun (claiming non-PK columns that do not\n * exist on the journal at runtime). PK/entity columns therefore ride the index signature.\n */\nexport type JournalTable = typeof journalShape & { [columnName: string]: PgColumn };\n/**\n * The `<t>_sync_state` convergence view (ADR-0011): fixed state columns + the entry's PK columns.\n * Conservatively indexed for the same reason as {@link JournalTable} — it projects only the PK columns\n * (a subset not recoverable at the type level), so the PK columns ride the index signature.\n */\nexport type SyncStateView = typeof syncStateShape & { [columnName: string]: PgColumn };\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006). */\nexport type LocalMetaTable = typeof localMetaShape;\n\n/**\n * Build a runtime `pgTable` for a local-store relation. An `ephemeral`-lifecycle entry (ADR-0021 §3)\n * renders **bare** regardless of the registry's local schema: its whole cluster is emitted as `TEMP`\n * with unqualified object names that resolve via `pg_temp`/search_path, exactly as\n * `generateLocalSchemaSql` renders it (a `pgSchema(localSchema).table(...)` reference would target a\n * durable schema the temp table does not live in — the latent qualification bug ADR-0029 records).\n */\nfunction makeTable(\n localSchema: string,\n name: string,\n columns: Record<string, ColumnBuilderBase>,\n ephemeral = false,\n): AnyPgTable {\n return localSchema === \"public\" || ephemeral ? pgTable(name, columns) : pgSchema(localSchema).table(name, columns);\n}\n\nfunction isEphemeral(entry: SyncTableEntry<AnyPgTable>): boolean {\n return entry.retention === \"ephemeral\";\n}\n\nfunction resolveSyncedTableName(entry: SyncTableEntry<AnyPgTable>): string {\n return entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name;\n}\n\n/**\n * The entry's projected column BUILDERS keyed by property key, re-created from the retained\n * `makeColumns` factory (registry.ts keeps it for exactly this kind of reuse) with\n * `clientProjection.omitColumns` applied — the same projection the generator's synced/overlay DDL\n * carries.\n */\nfunction projectedColumnBuilders(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const makeColumns = entry.makeColumns;\n if (!makeColumns) {\n throw new Error(\n `local table objects for ${tableKey} need the entry's makeColumns factory (built by defineSyncTable); ` +\n `hand-assembled entries cannot derive overlay/journal objects`,\n );\n }\n const omitted = new Set(entry.clientProjection?.omitColumns ?? []);\n return Object.fromEntries(Object.entries(makeColumns()).filter(([key]) => !omitted.has(key))) as Record<\n string,\n ColumnBuilderBase\n >;\n}\n\n/** Property-key ↔ column-name pairs for the entry's PK, resolved via the built local table. */\nfunction pkColumnPairs(entry: SyncTableEntry<AnyPgTable>, tableKey: string) {\n const localColumns = getColumns(entry.localTable) as Record<string, PgColumn>;\n return entry.primaryKey.columns.map((columnName) => {\n const pair = Object.entries(localColumns).find(([, column]) => column.name === columnName);\n if (!pair) {\n throw new Error(`Primary key column ${columnName} was not found on table ${tableKey}`);\n }\n return { propertyKey: pair[0], columnName };\n });\n}\n\ninterface EntryLocalTables {\n synced?: AnyPgTable;\n overlay?: OverlayTable;\n journal?: JournalTable;\n syncState?: SyncStateView;\n readModel?: ReadModelView;\n}\n\nconst localTablesCache = new WeakMap<SyncTableRegistry, Map<string, EntryLocalTables>>();\nconst localMetaCache = new Map<string, LocalMetaTable>();\n\nfunction cacheFor(registry: SyncTableRegistry, tableKey: string): EntryLocalTables {\n let byKey = localTablesCache.get(registry);\n if (!byKey) {\n byKey = new Map();\n localTablesCache.set(registry, byKey);\n }\n let slot = byKey.get(tableKey);\n if (!slot) {\n slot = {};\n byKey.set(tableKey, slot);\n }\n return slot;\n}\n\nfunction requireEntry(registry: SyncTableRegistry, tableKey: string): SyncTableEntry<AnyPgTable> {\n const entry = registry[tableKey];\n if (!entry) {\n throw new Error(`Unknown sync table: ${tableKey}`);\n }\n return entry;\n}\n\nfunction requireWritable(entry: SyncTableEntry<AnyPgTable>, tableKey: string, relation: string) {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`${relation} exists only for a writable table; ${tableKey} has no overlay/journal projection`);\n }\n return entry.clientProjection as { overlayTable: string; journalTable: string; syncedTable?: string };\n}\n\n/**\n * The projected SYNCED read-cache table as a runtime Drizzle object, under the resolved local name\n * (`clientProjection.syncedTable` override honoured) and the registry's local schema — the exact\n * relation the generator's `CREATE TABLE` provisions. Prefer `entry.localTable` where its name\n * already matches; this object exists for the runtime/tests that must track the projection rename.\n * Carries the entry's real projected columns under a concretely-typed registry, `AnyPgTable` under a\n * bare `SyncTableRegistry` (see {@link SyncedLocalTable}).\n */\nexport function getSyncedLocalTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): SyncedLocalTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.synced) {\n return slot.synced as SyncedLocalTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n resolveSyncedTableName(entry),\n projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>,\n isEphemeral(entry),\n );\n slot.synced = table;\n return table as SyncedLocalTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_overlay` optimistic-intent table as a runtime Drizzle object (writable tables only — throws\n * for a readonly entry, which has no overlay/journal projection). Its entity columns are typed exactly\n * as {@link OverlayTable} describes — real per-column types under a concretely-typed registry, the open\n * index-signature fallback under a bare `SyncTableRegistry` — plus the two fixed overlay columns.\n */\nexport function getOverlayTable<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): OverlayTable<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.overlay) {\n return slot.overlay as OverlayTable<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the overlay table\");\n const localSchema = getSyncRegistrySchema(registry);\n const table = makeTable(\n localSchema,\n projection.overlayTable,\n {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildOverlayFixedColumns(),\n },\n isEphemeral(entry),\n ) as OverlayTable;\n slot.overlay = table;\n return table as OverlayTable<TRegistry[TKey]>;\n}\n\n/**\n * The `<t>_mutations` journal table as a runtime Drizzle object (writable tables only). The fixed runtime\n * columns are typed; the PK/entity columns ride the index signature and are reached by DB column NAME\n * (`journal[\"id\"]`), because per-entry typing is not representable — see {@link JournalTable}.\n */\nexport function getJournalTable<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): JournalTable {\n const slot = cacheFor(registry, tableKey);\n if (slot.journal) {\n return slot.journal;\n }\n const entry = requireEntry(registry, tableKey);\n const projection = requireWritable(entry, tableKey, \"the journal table\");\n const localSchema = getSyncRegistrySchema(registry);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ columnName }) => [columnName, text(columnName).notNull()]),\n );\n const table = makeTable(\n localSchema,\n projection.journalTable,\n {\n ...pkBuilders,\n ...buildJournalFixedColumns(),\n },\n isEphemeral(entry),\n ) as JournalTable;\n slot.journal = table;\n return table;\n}\n\n/**\n * The `<t>_sync_state` convergence view (ADR-0011) as a runtime Drizzle object (writable tables only) —\n * PK columns under the entry's own property keys plus the fixed state columns, mirroring\n * `buildSyncStateView`'s projection. The fixed state columns are typed; the PK columns ride the index\n * signature (not recoverable at the type level — see {@link SyncStateView}) and are reached by their\n * drizzle PROPERTY key (`view[\"authorId\"]`), unlike the journal, which keys its PK columns by DB column\n * name.\n */\nexport function getSyncStateView<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n tableKey: string & keyof TRegistry,\n): SyncStateView {\n const slot = cacheFor(registry, tableKey);\n if (slot.syncState) {\n return slot.syncState;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the sync-state view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_sync_state`;\n const builders = projectedColumnBuilders(entry, tableKey);\n const pkBuilders = Object.fromEntries(\n pkColumnPairs(entry, tableKey).map(({ propertyKey }) => {\n const builder = builders[propertyKey];\n if (!builder) {\n throw new Error(`Primary key property ${propertyKey} was not found on table ${tableKey}`);\n }\n return [propertyKey, builder];\n }),\n ) as Record<string, ColumnBuilderBase>;\n const columns = {\n ...(pkBuilders as Record<string, ColumnBuilderBase>),\n ...buildSyncStateFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as SyncStateView;\n slot.syncState = view;\n return view;\n}\n\n/**\n * The `<t>_read_model` overlay-merged read view (ADR-0004) as a runtime Drizzle object: every projected\n * synced column under the entry's own property key plus the two overlay columns (`overlay_kind`,\n * `local_updated_at_us`), mirroring the generator's `CREATE VIEW`. The entry's own `entry.view` is\n * schema-UNQUALIFIED (`defineSyncTable` builds it with a bare `pgView`), so a consumer whose local store\n * lives in a non-public schema must author against this qualified object instead of `entry.view`.\n */\nexport function getReadModelView<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ReadModelView<TRegistry[TKey]> {\n const slot = cacheFor(registry, tableKey);\n if (slot.readModel) {\n return slot.readModel as ReadModelView<TRegistry[TKey]>;\n }\n const entry = requireEntry(registry, tableKey);\n requireWritable(entry, tableKey, \"the read-model view\");\n const localSchema = getSyncRegistrySchema(registry);\n const viewName = `${resolveSyncedTableName(entry)}_read_model`;\n const columns = {\n ...(projectedColumnBuilders(entry, tableKey) as Record<string, ColumnBuilderBase>),\n ...buildReadModelFixedColumns(),\n };\n const view = (\n localSchema === \"public\" || isEphemeral(entry)\n ? pgView(viewName, columns).existing()\n : pgSchema(localSchema).view(viewName, columns).existing()\n ) as ReadModelView;\n slot.readModel = view;\n return view as ReadModelView<TRegistry[TKey]>;\n}\n\n/**\n * The read-path applier's resolved per-shape target (ADR-0029 D1/D2). Every table-scoped fact the\n * appliers need is derived once from the registry entry — the real projected synced table object, its\n * columns indexed by DB column name, the primary-key column names, and the model-derived column types —\n * so the appliers author over Drizzle objects (no name/schema strings, no `information_schema` probe).\n * Resolved once per shape at subscribe time; reused for every message. Electric change rows are keyed\n * by DB **column name**, while Drizzle DML keys by **property key**, so both indexes are carried.\n */\nexport interface ApplyTarget {\n /** The real projected synced local table (`getSyncedLocalTable`) — bare for ephemeral lifecycles. */\n table: AnyPgTable;\n /** DB column name → its Drizzle `PgColumn` (for `eq`/conflict-target/COPY clauses). */\n columnByName: Record<string, PgColumn>;\n /** DB column name → its Drizzle property key (to key `.values()`/`.set()` from a name-keyed row). */\n propertyKeyByName: Record<string, string>;\n /** Primary-key column NAMES, in order (from the entry, local-projection override honoured). */\n primaryKey: string[];\n /** Model-derived column types (`deriveSyncColumnTypes`), keyed by DB column name via `.name`. */\n columnTypes: SyncColumnType[];\n /**\n * Per-shape render-once cache for the batched-INSERT family (ADR-0029 D5): a rendered `{sqlText,\n * params}` per distinct (column-set, row-count), reused across batches with per-value codecs applied\n * at execution. Empty at resolution; populated lazily by the applier.\n */\n insertRenderCache: Map<string, { sqlText: string; params: unknown[] }>;\n}\n\n/**\n * Resolve a shape's {@link ApplyTarget} from its registry entry (ADR-0029 D1/D2). Called once per shape\n * at subscribe time — never per message. The single source is the registry item: identity via\n * `getSyncedLocalTable`, PKs via `getLocalSyncedTablePrimaryKeyColumns`, types via `deriveSyncColumnTypes`.\n */\nexport function resolveApplyTarget<TRegistry extends SyncTableRegistry, TKey extends string & keyof TRegistry>(\n registry: TRegistry,\n tableKey: TKey,\n): ApplyTarget {\n const entry = requireEntry(registry, tableKey);\n const table = getSyncedLocalTable(registry, tableKey);\n const columns = getColumns(table as AnyPgTable) as Record<string, PgColumn>;\n const columnByName: Record<string, PgColumn> = {};\n const propertyKeyByName: Record<string, string> = {};\n for (const [propertyKey, column] of Object.entries(columns)) {\n columnByName[column.name] = column;\n propertyKeyByName[column.name] = propertyKey;\n }\n return {\n table: table as AnyPgTable,\n columnByName,\n propertyKeyByName,\n primaryKey: getLocalSyncedTablePrimaryKeyColumns(entry),\n columnTypes: deriveSyncColumnTypes(entry),\n insertRenderCache: new Map(),\n };\n}\n\n/** The `pgxsinkit_local_meta` key/value table (ADR-0006) under the registry's local schema. */\nexport function getLocalMetaTable(registry: SyncTableRegistry): LocalMetaTable {\n const localSchema = getSyncRegistrySchema(registry);\n const cached = localMetaCache.get(localSchema);\n if (cached) {\n return cached;\n }\n const table = makeTable(localSchema, LOCAL_META_TABLE, {\n key: text(\"key\").primaryKey(),\n value: text(\"value\").notNull(),\n }) as LocalMetaTable;\n localMetaCache.set(localSchema, table);\n return table;\n}\n",
115
+ "import { eq, like } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport { type MutationDiagnostics, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { getLocalMetaTable } from \"./local-tables\";\nimport type { MutationDb } from \"./mutation\";\nimport { buildWipeLocalStoreSql, generateLocalSchemaSql, REGISTRY_FINGERPRINT_KEY } from \"./schema\";\n\n// Statements are AUTHORED as Drizzle builders over the meta-table object (rename-safe, typed,\n// schema-qualification handled by the table object) and rendered to text+params here, because they\n// EXECUTE through the caller's raw `MutationDb` seam — the one connection the mutation runtime and\n// its tests own (and mock).\nconst metaQueryBuilder = drizzle.mock();\n\n/**\n * The fingerprint-keyed local store (ADR-0006). The registry fingerprint the local PGlite\n * database was provisioned under is recorded in the local-meta table; comparing it to the\n * current fingerprint on boot is how a registry change is *detected* (rather than a\n * hand-bumped `idb://…-vN` suffix), which drives the drain-then-drop read-cache rebuild.\n */\n\n/** A boot-time registry-version reconciliation outcome (ADR-0006 drain-then-drop). */\nexport interface LocalStoreVersionEvent {\n status: \"rebuilt\" | \"deferred\";\n previousFingerprint: string;\n nextFingerprint: string;\n /** Mutations still owed to the server (pending + sending + failed + quarantined). */\n owedMutations: number;\n}\n\n/** The minimal mutation-runtime surface the version reconciliation needs. */\ninterface VersionReconcileRuntime {\n registryVersion: string;\n readMutationStats: () => Promise<MutationDiagnostics>;\n}\n\n/** The registry fingerprint the local store was last provisioned under, or null if unstamped. */\nexport async function readStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n): Promise<string | null> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ value: meta.value })\n .from(meta)\n .where(eq(meta.key, REGISTRY_FINGERPRINT_KEY))\n .limit(1)\n .toSQL();\n const result = await db.query<{ value: string }>(query.sql, query.params as unknown[]);\n\n return result.rows[0]?.value ?? null;\n}\n\n/** Meta-key prefix for a persisted `lazy + persistent` group activation (ADR-0021 §2). */\nconst LAZY_ACTIVATION_PREFIX = \"lazy_active:\";\n\n/**\n * The consistency-group keys of `lazy + persistent` groups that were activated on a previous boot\n * (ADR-0021 §2). On boot these are promoted into the eager subscription set, so a once-activated durable\n * lazy group resumes permanently with no per-session re-evaluation. (`ephemeral` activation is never\n * persisted, so it never appears here.)\n */\nexport async function readActivatedLazyGroups(db: MutationDb, registry: SyncTableRegistry): Promise<Set<string>> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .select({ key: meta.key })\n .from(meta)\n .where(like(meta.key, `${LAZY_ACTIVATION_PREFIX}%`))\n .toSQL();\n const result = await db.query<{ key: string }>(query.sql, query.params as unknown[]);\n return new Set(result.rows.map((row) => row.key.slice(LAZY_ACTIVATION_PREFIX.length)));\n}\n\n/** Upsert one meta key — the shared write shape for activations and the fingerprint stamp. */\nasync function upsertMetaValue(db: MutationDb, registry: SyncTableRegistry, key: string, value: string): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .insert(meta)\n .values({ key, value })\n .onConflictDoUpdate({ target: meta.key, set: { value } })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Persist a `lazy + persistent` group's activation, so the next boot promotes it to eager (ADR-0021 §2). */\nexport async function writeLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, `${LAZY_ACTIVATION_PREFIX}${groupKey}`, \"1\");\n}\n\n/** Clear a persisted lazy activation — an explicit `desync` reverts the group to dormant next boot (ADR-0021 §2). */\nexport async function clearLazyGroupActivation(\n db: MutationDb,\n registry: SyncTableRegistry,\n groupKey: string,\n): Promise<void> {\n const meta = getLocalMetaTable(registry);\n const query = metaQueryBuilder\n .delete(meta)\n .where(eq(meta.key, `${LAZY_ACTIVATION_PREFIX}${groupKey}`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/** Stamp the local store with the fingerprint it is now provisioned under. */\nexport async function writeStoredRegistryFingerprint(\n db: MutationDb,\n registry: SyncTableRegistry,\n fingerprint: string,\n): Promise<void> {\n await upsertMetaValue(db, registry, REGISTRY_FINGERPRINT_KEY, fingerprint);\n}\n\n/**\n * Reconcile the local store against the current registry fingerprint (ADR-0006). A fresh\n * (unstamped) store is stamped; an unchanged fingerprint is a no-op. On a change, the read\n * cache is dropped and rebuilt at the new shape **only when nothing is owed locally** —\n * otherwise the rebuild is deferred (and retried on a later boot) so un-flushed/quarantined\n * writes are never silently dropped. The drain happens across sessions: pending writes flush\n * and reconcile during normal use, and the rebuild completes once the journal is clear.\n *\n * An unstamped store is always treated as brand-new. There is no pre-fingerprint-store path:\n * the fingerprint mechanism shipped before launch, so every store in existence was\n * provisioned with it (and a stamped store's journal therefore always has `registry_version`).\n */\nexport async function reconcileLocalStoreVersion<TRegistry extends SyncTableRegistry>(args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n}): Promise<LocalStoreVersionEvent | null> {\n const { db, registry, runtime } = args;\n const stored = await readStoredRegistryFingerprint(db, registry);\n const current = runtime.registryVersion;\n\n if (stored === current) {\n return null;\n }\n\n if (stored === null) {\n await writeStoredRegistryFingerprint(db, registry, current);\n return null;\n }\n\n return rebuildReadCacheOrDefer(args, stored);\n}\n\n/**\n * The drain-then-drop core (ADR-0006): rebuild the read cache at the current shape when\n * nothing is owed locally, otherwise defer so un-flushed/quarantined writes are never\n * dropped (the drain completes on a later boot).\n */\nasync function rebuildReadCacheOrDefer<TRegistry extends SyncTableRegistry>(\n args: {\n db: MutationDb;\n registry: TRegistry;\n runtime: VersionReconcileRuntime;\n onSchemaChange?: (event: LocalStoreVersionEvent) => void | Promise<void>;\n },\n previousFingerprint: string,\n): Promise<LocalStoreVersionEvent> {\n const { db, registry, runtime, onSchemaChange } = args;\n const current = runtime.registryVersion;\n const stats = await runtime.readMutationStats();\n const owedMutations = stats.pendingCount + stats.sendingCount + stats.failedCount + stats.quarantinedCount;\n\n if (owedMutations > 0) {\n const event: LocalStoreVersionEvent = {\n status: \"deferred\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations,\n };\n await onSchemaChange?.(event);\n return event;\n }\n\n await db.exec(buildWipeLocalStoreSql(registry));\n await db.exec(generateLocalSchemaSql(registry));\n await writeStoredRegistryFingerprint(db, registry, current);\n const event: LocalStoreVersionEvent = {\n status: \"rebuilt\",\n previousFingerprint,\n nextFingerprint: current,\n owedMutations: 0,\n };\n await onSchemaChange?.(event);\n return event;\n}\n",
116
+ "/**\n * The mutation-journal state machine (ADR-0005, extended by ADR-0006).\n *\n * The runtime is large; previously the legal status transitions were implicit,\n * scattered across SQL writes. This is the one named place that defines them, so the\n * rules are testable and a future change extends a single table. ADR-0006 splits the\n * old single `failed` into transient (retryable `failed`) and permanent (`quarantined`).\n */\n\nexport type MutationStatus = \"pending\" | \"sending\" | \"acked\" | \"failed\" | \"quarantined\" | \"conflicted\" | \"rejected\";\n\n/**\n * Legal transitions. `acked` is terminal at the journal level — it is cleared by\n * reconciliation once the synced echo reaches the acknowledged server timestamp, not\n * by another status transition. `quarantined` is terminal too: the server will never\n * accept the mutation as-is, so it is surfaced (callback + diagnostics), never retried.\n * `conflicted` (ADR-0015) is likewise terminal but a *different* outcome: the write was\n * well-formed but **stale** (an external write interleaved) and the table's `reject-if-stale`\n * policy declined it. The optimistic Overlay is KEPT (the user's edit is not lost) and the\n * conflict is surfaced via `onConflict`; resolution is an ordinary NEW mutation, and `discard`\n * clears the overlay + this entry. It is never retried as-is (the base would still be stale).\n * `rejected` (ADR-0022) is terminal as well, and the inverse of `conflicted` on disposition: the\n * authoritative endpoint declined the whole pessimistic write-**unit** for a business reason (a\n * capacity/quota/uniqueness rule the client could not evaluate locally), so the optimistic Overlay\n * is **auto-discarded** for every member of the unit and the typed reason is surfaced via `onReject`.\n * Never retried (the server's answer is authoritative).\n *\n * - `pending -> sending` a flush claims the row and posts it.\n * - `sending -> acked` the server acknowledged the mutation.\n * - `sending -> failed` transient transport/server error (network, 5xx, …).\n * - `sending -> quarantined` structural 4xx rejection the server will never accept.\n * - `sending -> conflicted` a stale write the reject-if-stale policy declined (ADR-0015).\n * - `sending -> rejected` a business rejection from the authoritative endpoint (ADR-0022).\n * - `sending -> pending` recoverSending re-queues an in-flight row on startup.\n * - `failed -> pending` retryFailed re-queues a failed row.\n * - `failed -> quarantined` the hard max-attempts cap is reached; stop retrying.\n */\nexport const MUTATION_TRANSITIONS = {\n pending: [\"sending\"],\n sending: [\"acked\", \"failed\", \"quarantined\", \"conflicted\", \"rejected\", \"pending\"],\n failed: [\"pending\", \"quarantined\"],\n quarantined: [],\n conflicted: [],\n rejected: [],\n acked: [],\n} as const satisfies Record<MutationStatus, readonly MutationStatus[]>;\n\nexport function isValidMutationTransition(from: MutationStatus, to: MutationStatus): boolean {\n return (MUTATION_TRANSITIONS[from] as readonly MutationStatus[]).includes(to);\n}\n\nexport function assertValidMutationTransition(from: MutationStatus, to: MutationStatus): void {\n if (!isValidMutationTransition(from, to)) {\n throw new Error(`Illegal mutation-journal transition: ${from} -> ${to}`);\n }\n}\n\n/**\n * The hard cap on send attempts (ADR-0005 congestion policy). A mutation that has\n * failed this many times — even with transient-looking errors — is given up on and\n * quarantined, so a permanently-unreachable server never produces an unbounded retry\n * loop. The consumer can raise/lower it via `createSyncClient({ maxMutationAttempts })`.\n */\nexport const DEFAULT_MAX_MUTATION_ATTEMPTS = 10;\n\n/**\n * 4xx statuses that are nonetheless transient: auth (the runtime refreshes the token and\n * retries), request-timeout, too-early, and rate-limit. Everything else in the 4xx range\n * is treated as a structural rejection the server will never accept as-is.\n */\nconst TRANSIENT_CLIENT_ERROR_STATUSES: ReadonlySet<number> = new Set([401, 403, 408, 425, 429]);\n\n/**\n * Classify a flush failure into its durable journal state (ADR-0006 decision 4):\n * - `quarantined` (terminal): a structural 4xx rejection — retrying is pointless, so it\n * is surfaced rather than retry-looped (the silent-data-loss case the runtime *can*\n * catch at send time).\n * - `failed` (retryable): network/transport (no status), any 5xx, or a transient 4xx.\n */\nexport function classifyFailureStatus(httpStatus: number | null | undefined): \"failed\" | \"quarantined\" {\n if (httpStatus == null) {\n return \"failed\";\n }\n\n if (httpStatus >= 400 && httpStatus < 500 && !TRANSIENT_CLIENT_ERROR_STATUSES.has(httpStatus)) {\n return \"quarantined\";\n }\n\n return \"failed\";\n}\n",
117
+ "import {\n and,\n desc,\n eq,\n exists,\n getColumns,\n gt,\n inArray,\n is,\n isNotNull,\n isNull,\n lt,\n ne,\n notExists,\n SQL,\n sql,\n} from \"drizzle-orm\";\nimport {\n alias,\n getTableConfig,\n getViewConfig,\n PgDialect,\n type AnyPgTable,\n type PgColumn,\n type PgInsertValue,\n} from \"drizzle-orm/pg-core\";\nimport { drizzle } from \"drizzle-orm/pglite\";\n\nimport {\n getJournalTable,\n getOverlayTable,\n getSyncedLocalTable,\n type JournalTable,\n type OverlayTable,\n} from \"./local-tables\";\n\n// Statements are AUTHORED as Drizzle builders over the journal/overlay/synced table objects\n// (rename-safe, typed, schema-qualification handled by the table objects) and rendered to\n// text+params here, because they EXECUTE through the caller's raw `MutationDb` seam — the one\n// connection the mutation runtime and its tests own (and mock). `drizzle.mock()` builds queries\n// without a connection; `queryDialect` renders standalone `sql` fragments the builders cannot\n// express (compound CTE shapes, derived-table wrappers).\nconst queryBuilder = drizzle.mock();\nconst queryDialect = new PgDialect();\n\n/**\n * Strip the two internal overlay columns that appear on _read_model views\n * (`overlay_kind`, `local_updated_at_us`) from any user-supplied input or\n * patch object before it is serialised into a mutation payload. Callers\n * that spread a view row directly into a create/update call would otherwise\n * hit `TypeError: Do not know how to serialize a BigInt` because\n * `local_updated_at_us` is stored as a native JS `bigint`.\n */\nfunction stripReadModelOverlayFields<T>(value: T): T {\n if (value === null || typeof value !== \"object\") return value;\n const obj = value as Record<string, unknown>;\n if (!(\"overlay_kind\" in obj) && !(\"local_updated_at_us\" in obj)) return value;\n const { overlay_kind: _ok, local_updated_at_us: _lu, ...rest } = obj;\n return rest as T;\n}\n\n/**\n * JSON replacer that serialises `bigint` values as strings. PostgreSQL\n * accepts string literals for BIGINT columns, and JSON has no native bigint\n * type, so this is the safest cross-boundary representation.\n */\nfunction bigintReplacer(_key: string, value: unknown): unknown {\n return typeof value === \"bigint\" ? String(value) : value;\n}\n\nfunction jsonStringifyPayload(value: unknown): string {\n return JSON.stringify(value, bigintReplacer);\n}\n\nimport type {\n BatchMutationAck,\n MutationAck,\n MutationDiagnostics,\n MutationRejection,\n SyncTableCreateInput,\n SyncTableEntry,\n SyncTableName,\n SyncTableRecord,\n SyncTableRegistry,\n SyncTableUpdateInput,\n WriteMode,\n} from \"@pgxsinkit/contracts\";\nimport {\n batchMutationErrorSchema,\n buildOverlayResolutionBarrier,\n fingerprintRegistry,\n getProjectedColumns as getProjectedTableColumns,\n getSyncRegistrySchema,\n maybeQuoteIdentifier,\n quoteIdentifier,\n resolveServerVersionColumnName,\n} from \"@pgxsinkit/contracts\";\n\nimport { syncDebug } from \"./debug\";\nimport {\n assertValidMutationTransition,\n classifyFailureStatus,\n DEFAULT_MAX_MUTATION_ATTEMPTS,\n type MutationStatus,\n} from \"./mutation-state\";\n\nexport type { MutationStatus } from \"./mutation-state\";\nexport type MutationKind = \"create\" | \"update\" | \"delete\";\n\n/**\n * The dynamic write-unit tag (ADR-0022 §2) a `transaction({ mode })` block stamps onto the mutations\n * authored within it: a shared `id` grouping the co-committed mutations, and the unit's `mode`. Persisted\n * on each journal row (`write_unit` / `write_mode`); absent for the default path, where the flusher derives\n * mode + unit from the table's static consistency group.\n */\nexport interface WriteUnit {\n id: string;\n mode: WriteMode;\n}\n\nexport type MutationBatchItem<TRegistry extends SyncTableRegistry> = {\n [TKey in SyncTableName<TRegistry>]:\n | {\n table: TKey;\n kind: \"create\";\n input: SyncTableCreateInput<TRegistry, TKey>;\n }\n | {\n table: TKey;\n kind: \"update\";\n entityKey: Record<string, string>;\n patch: SyncTableUpdateInput<TRegistry, TKey>;\n /**\n * A **blind** update (ADR-0022 addendum): plan a journal row ONLY — no local base row is required\n * and no optimistic overlay is written. Set exclusively by the transaction handle's `updateBlind`;\n * valid only when the write routes pessimistically (a `pessimistic` unit, or a statically-pessimistic\n * table), and rejected at enqueue otherwise. Absent/false for an ordinary update.\n */\n blind?: boolean;\n }\n | {\n table: TKey;\n kind: \"delete\";\n entityKey: Record<string, string>;\n };\n}[SyncTableName<TRegistry>];\n\nexport const DEFAULT_FLUSH_BATCH_SIZE = 100;\n\nexport interface MutationDetail {\n tableName: string;\n entityKey: Record<string, string>;\n mutationId: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n /** Registry fingerprint (ADR-0004) the mutation was authored under, or null if unstamped. */\n registryVersion: string | null;\n}\n\nexport interface MutationDb {\n exec: (sql: string) => Promise<unknown>;\n query: <TRow extends Record<string, unknown> = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n ) => Promise<{ rows: TRow[] }>;\n}\n\nexport interface CreateMutationRuntimeOptions<TRegistry extends SyncTableRegistry> {\n db: MutationDb;\n registry: TRegistry;\n writeUrl: string;\n getAuthToken?: () => Promise<string | undefined>;\n /** Static headers added to every write request (e.g. a Supabase Cloud `apikey`); see {@link CreateSyncClientOptions.requestHeaders}. */\n requestHeaders?: Record<string, string>;\n /**\n * Registry fingerprint (ADR-0004) stamped onto each enqueued mutation as its\n * `registry_version`, so a version-boundary crossing is known before sending (ADR-0006).\n */\n registryVersion?: string;\n /**\n * Hard cap on send attempts before a still-failing mutation is quarantined\n * (ADR-0005 congestion policy). Defaults to {@link DEFAULT_MAX_MUTATION_ATTEMPTS}.\n */\n maxMutationAttempts?: number;\n /**\n * Max mutations drained per flush HTTP request; a flush loops slices until the journal is empty.\n * Defaults to {@link DEFAULT_FLUSH_BATCH_SIZE}. Primarily a test seam (a small value exercises the\n * multi-slice drain path without enqueueing hundreds of mutations).\n */\n flushBatchSize?: number;\n /**\n * Invoked after a flush whenever mutations transition to `quarantined` (terminal,\n * permanently rejected). Receives the newly-quarantined details so the app can surface\n * them, then either re-author + resubmit or roll back via {@link MutationRuntime.discardQuarantined}\n * (clears the kept overlay + quarantined journal rows, so the entity accepts new mutations again).\n * The library never silently drops these (ADR-0006 decision 4).\n */\n onQuarantine?: (quarantined: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after a flush whenever mutations transition to `conflicted` — a stale write the\n * server declined under the `reject-if-stale` Conflict policy (ADR-0015). Distinct from\n * `onQuarantine` (structural rejection): the optimistic Overlay is KEPT, so the app surfaces a\n * resolution/diff UI and resolves each as a new write (or `discardConflict`s it). Never silent.\n */\n onConflict?: (conflicted: MutationDetail[]) => void | Promise<void>;\n /**\n * Invoked after an authoritative (pessimistic) flush whenever a write-unit was `rejected` (ADR-0022) —\n * a business decline the client could not evaluate locally (capacity/quota/uniqueness). The inverse of\n * `onConflict`: the optimistic Overlay was **auto-discarded** for every member of the unit, so the app\n * surfaces the typed reason (e.g. \"full\") rather than a resolve/diff UI. Never silent.\n */\n onReject?: (rejected: MutationDetail[]) => void | Promise<void>;\n}\n\ninterface TableContext {\n key: string;\n entry: SyncTableEntry<AnyPgTable>;\n readModel: string;\n syncedTable: string;\n overlayTable: string;\n journalTable: string;\n journalSequence: string;\n pkColumnNames: string[];\n pkPropertyKeys: string[];\n /**\n * The Server version (ADR-0010) column name (e.g. `updated_at_us`) and its drizzle property key,\n * resolved from the table's managed fields. Used to capture the Base server version (ADR-0015) at\n * enqueue — the value the user's edit was authored against. `null` would mean no Server version,\n * which registry validation already forbids for a writable table.\n */\n serverVersionColumnName: string | null;\n serverVersionPropertyKey: string | null;\n /**\n * Property keys of the table's `nowMicroseconds` managed fields (governance), resolved generically\n * rather than by the `createdAtUs`/`updatedAtUs` naming convention. The optimistic overlay stamps\n * these client-side so a custom-named managed timestamp (e.g. a Server version not called\n * `updated_at_us`) is materialised correctly — closing the split interpreter between the generic\n * server applier (which reads governance) and the local path (ADR-0004).\n *\n * - `managedNowMicrosecondsPropertyKeys` — every `nowMicroseconds` field, stamped on create.\n * - `updateManagedNowMicrosecondsPropertyKeys` — those that apply on update, re-stamped each update.\n *\n * These augment, and never remove, the convention fill in `createOptimisticRecordFromContext`,\n * which remains the safety net for a `created_at_us`/`updated_at_us` column that carries a SQL\n * `DEFAULT` (unmaterialisable client-side) yet is not declared a managed field.\n */\n managedNowMicrosecondsPropertyKeys: string[];\n updateManagedNowMicrosecondsPropertyKeys: string[];\n /**\n * The table's `authClaim` managed fields that apply on create (governance), each with the JSON\n * claimPath it stamps from. The server stamps these from the verified request claims, so they are\n * stripped from the create input type and never sent in the flushed payload. But the optimistic\n * overlay still needs a value — such a column is typically `NOT NULL` (an owner/author/created_by) —\n * so the runtime fills it client-side from the decoded JWT claim at the same path (the same value the\n * server will stamp), so the local row renders attributed immediately and never flips on convergence.\n * (`auth.uid()` is just `claimPath: [\"sub\"]`, so this one path covers it.)\n */\n managedAuthClaimCreateFields: Array<{ propertyKey: string; claimPath: string[] }>;\n recordIncludesOverlayState: boolean;\n columns: Array<{\n propertyKey: string;\n column: ReturnType<typeof getProjectedTableColumns<AnyPgTable>>[number][\"column\"];\n }>;\n /**\n * The generated local relations as runtime Drizzle table objects (local-tables.ts), so the\n * runtime's statements are AUTHORED as tier-① builders while still EXECUTING through the raw\n * `MutationDb` seam. Journal fixed columns are camelCase-keyed; per-entry PK columns are keyed\n * by DB column name; overlay/synced columns are keyed by drizzle property key.\n */\n tables: {\n synced: AnyPgTable;\n overlay: OverlayTable;\n journal: JournalTable;\n };\n /** Overlay columns keyed by property key (`getColumns` memo — overlay keys are property keys, not DB names). */\n overlayColumnsByPropertyKey: Record<string, PgColumn>;\n /** Synced read-cache columns keyed by property key. */\n syncedColumnsByPropertyKey: Record<string, PgColumn>;\n /** The entry's PK columns ON THE OVERLAY, resolved by DB column name (ordered like `pkColumnNames`). */\n overlayPkColumns: PgColumn[];\n /** The entry's PK columns ON THE SYNCED table, resolved by DB column name (ordered like `pkColumnNames`). */\n syncedPkColumns: PgColumn[];\n /** The Server version column ON THE SYNCED table (ADR-0010), or null when the table declares none. */\n syncedServerVersionColumn: PgColumn | null;\n /**\n * Memoized render of the reconcile idle probe (the per-tick hot statement): built once per\n * context so every convergence tick pays only a plain `db.query` of a cached string.\n */\n reconcileIdleProbe?: { sql: string; params: unknown[] };\n}\n\nexport interface MutationRuntime<TRegistry extends SyncTableRegistry> {\n /** The registry fingerprint (ADR-0004) this runtime stamps onto enqueued mutations. */\n registryVersion: string;\n create: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => Promise<void>;\n update: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n patch: SyncTableUpdateInput<TRegistry, TKey>,\n ) => Promise<void>;\n delete: <TKey extends SyncTableName<TRegistry>>(table: TKey, entityKey: Record<string, string>) => Promise<void>;\n /**\n * Enqueue an atomic batch of mutations. An optional {@link WriteUnit} tags every row of the batch as one\n * dynamic write-unit (ADR-0022 §2) — the `transaction({ mode })` block passes it; the per-table\n * `create`/`update`/`delete` helpers do not (their write-mode comes from the static group at flush).\n */\n batch: (items: ReadonlyArray<MutationBatchItem<TRegistry>>, unit?: WriteUnit) => Promise<void>;\n /**\n * Discard a `conflicted` entity (ADR-0015): clear its conflicted journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value. Use when the user\n * abandons their stale edit instead of resolving it as a new write. No-op for an entity with no\n * conflicted entry.\n */\n discardConflict: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n /**\n * Discard a `quarantined` entity (ADR-0006): clear its quarantined journal entries and the kept\n * optimistic Overlay, so the Read model falls back to the synced (server) value and the entity\n * accepts new mutations again. The rollback path for a permanently-rejected write (e.g. an RLS\n * policy denial routed to quarantine). Symmetric to {@link discardConflict}. No-op for an entity\n * with no quarantined entry; the overlay is kept when another still-owed write depends on it.\n */\n discardQuarantined: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n entityKey: Record<string, string>,\n ) => Promise<void>;\n flush: (table?: SyncTableName<TRegistry>) => Promise<void>;\n /**\n * Flush one pessimistic write-unit (ADR-0022) to the authoritative endpoint and apply its per-mutation\n * result inline: `acked` clears via the synced echo, `conflicted` keeps the overlay (surfaced), and\n * `rejected` auto-discards the overlay for the whole unit (surfaced via `onReject`). A foreground\n * operation — it resolves once the server has decided. Throws on transport failure (the overlay is kept\n * for a retry). Returns the server acks. Used by the client `transaction({ mode: \"pessimistic\" })` block.\n */\n flushUnit: (unitId: string) => Promise<{ acks: MutationAck[] }>;\n reconcile: (table?: SyncTableName<TRegistry>) => Promise<void>;\n retryFailed: (table?: SyncTableName<TRegistry>) => Promise<void>;\n recoverSending: (table?: SyncTableName<TRegistry>) => Promise<void>;\n readMutationStats: (table?: SyncTableName<TRegistry>) => Promise<MutationDiagnostics>;\n readMutationDetails: (table?: SyncTableName<TRegistry>) => Promise<MutationDetail[]>;\n createOptimisticRecord: <TKey extends SyncTableName<TRegistry>>(\n table: TKey,\n input: SyncTableCreateInput<TRegistry, TKey>,\n ) => SyncTableRecord<TRegistry, TKey>;\n}\n\nexport function nowMicroseconds(): string {\n return (BigInt(Date.now()) * 1000n).toString();\n}\n\n/**\n * Best-effort decode of a JWT's claims payload, for stamping `authClaim` managed fields into the\n * optimistic overlay (the value the server will independently stamp from the same claim path). This is\n * **not** a verification — the token is trusted only for a local, optimistic projection that the server\n * re-stamps authoritatively on apply; a forged claim could never make the server attribute the row\n * differently. Returns `undefined` for a malformed token.\n */\nexport function decodeJwtClaims(token: string): Record<string, unknown> | undefined {\n const segments = token.split(\".\");\n if (segments.length < 2 || !segments[1]) {\n return undefined;\n }\n try {\n const normalized = segments[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = normalized.padEnd(normalized.length + ((4 - (normalized.length % 4)) % 4), \"=\");\n const binary = atob(padded);\n const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));\n const payload = JSON.parse(new TextDecoder().decode(bytes)) as unknown;\n return typeof payload === \"object\" && payload !== null ? (payload as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Read a claim at a JSON path out of a decoded claims object, returning it as a string (the form the\n * optimistic overlay column expects, mirroring the server's `jsonb #>>` text extraction). Returns\n * `undefined` if the path is absent or the leaf is not a string/number.\n */\nexport function readJwtClaimPath(claims: Record<string, unknown>, claimPath: string[]): string | undefined {\n let cursor: unknown = claims;\n for (const segment of claimPath) {\n if (typeof cursor !== \"object\" || cursor === null) {\n return undefined;\n }\n cursor = (cursor as Record<string, unknown>)[segment];\n }\n if (typeof cursor === \"string\") {\n return cursor;\n }\n return typeof cursor === \"number\" ? String(cursor) : undefined;\n}\n\nexport function computeBackoffDelayMs(attemptCount: number) {\n const exponent = Math.max(attemptCount - 1, 0);\n return Math.min(1000 * 2 ** exponent, 30_000);\n}\n\n/**\n * Retry delay with equal jitter around the {@link computeBackoffDelayMs} ceiling: half\n * the ceiling plus a random share of the other half. Spreads retries so a fleet of\n * clients does not stampede the server in lockstep after an outage (ADR-0005 congestion\n * policy). `random` is injectable for deterministic tests.\n */\nexport function computeRetryDelayMs(attemptCount: number, random: () => number = Math.random) {\n const ceiling = computeBackoffDelayMs(attemptCount);\n return Math.round(ceiling / 2 + random() * (ceiling / 2));\n}\n\nexport function computeNextRetryAtUs(nowUs: string, attemptCount: number, random: () => number = Math.random) {\n return (BigInt(nowUs) + BigInt(computeRetryDelayMs(attemptCount, random)) * 1000n).toString();\n}\n\nexport function createMutationRuntime<TRegistry extends SyncTableRegistry>(\n options: CreateMutationRuntimeOptions<TRegistry>,\n): MutationRuntime<TRegistry> {\n const resolveAuthToken = async () => {\n if (options.getAuthToken) {\n return await options.getAuthToken();\n }\n\n return undefined;\n };\n\n // The decoded JWT claims for stamping `authClaim` create-managed fields into the optimistic overlay\n // (the same value the server stamps from the same claim path). Resolved only when a create needs it\n // (a table with such a field), so tokenless registries never pay a token lookup.\n const resolveAuthClaims = async (): Promise<Record<string, unknown> | undefined> => {\n const token = await resolveAuthToken();\n return token ? decodeJwtClaims(token) : undefined;\n };\n\n const tableContexts = buildTableContexts(options.registry);\n const maxMutationAttempts = options.maxMutationAttempts ?? DEFAULT_MAX_MUTATION_ATTEMPTS;\n const flushBatchSize = options.flushBatchSize ?? DEFAULT_FLUSH_BATCH_SIZE;\n // The fingerprint (ADR-0004) stamped onto each enqueued mutation (ADR-0006). The runtime\n // owns the registry, so it derives this itself; an explicit override is honoured for tests.\n const registryVersion = options.registryVersion ?? fingerprintRegistry(options.registry);\n let flushQueue = Promise.resolve();\n\n const getTableContext = (table: SyncTableName<TRegistry>) => {\n const context = tableContexts[table];\n\n if (!context) {\n throw new Error(`Unknown mutation table: ${String(table)}`);\n }\n\n return context;\n };\n\n const runInTransaction = async (operation: () => Promise<void>) => {\n await options.db.exec(\"BEGIN\");\n\n try {\n await operation();\n await options.db.exec(\"COMMIT\");\n } catch (error) {\n await options.db.exec(\"ROLLBACK\");\n throw error;\n }\n };\n\n const normalizeBatchItem = (\n item: MutationBatchItem<TRegistry>,\n order: number,\n claims: Record<string, unknown> | undefined,\n ): NormalizedBatchItem => {\n const context = getTableContext(item.table as SyncTableName<TRegistry>);\n const mutationId = globalThis.crypto.randomUUID();\n const nowUs = nowMicroseconds();\n\n switch (item.kind) {\n case \"create\": {\n const strippedInput = stripReadModelOverlayFields(item.input);\n const optimisticRecord = ensureRecord(createOptimisticRecordFromContext(context, strippedInput, claims));\n const entityKey = buildEntityKeyFromRecord(context, optimisticRecord);\n\n return {\n context,\n kind: \"create\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n optimisticRecord,\n input: strippedInput,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"update\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n const patch = ensureRecord(stripReadModelOverlayFields(item.patch));\n\n return {\n context,\n kind: \"update\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n patch,\n blind: item.blind ?? false,\n mutationId,\n nowUs,\n order,\n };\n }\n case \"delete\": {\n const entityKey = normalizeEntityKey(context, item.entityKey);\n\n return {\n context,\n kind: \"delete\",\n entityKey,\n entityKeyJson: serializeEntityKey(entityKey),\n mutationId,\n nowUs,\n order,\n };\n }\n }\n };\n\n const enqueueBatch = async (\n items: ReadonlyArray<MutationBatchItem<TRegistry>>,\n unit?: WriteUnit,\n ): Promise<string[]> => {\n if (items.length === 0) {\n return [];\n }\n\n // The distinct pessimistic write-unit ids this enqueue tagged — returned so the caller can\n // foreground-route them to the authoritative endpoint (ADR-0022). Empty for a purely optimistic batch.\n const pessimisticUnitIds = new Set<string>();\n\n // Resolve the decoded claims once per batch, but only if a create actually needs them (a target\n // table with an `authClaim` create-managed field). Avoids a token lookup for every other write.\n const needsAuthClaims = items.some(\n (item) =>\n item.kind === \"create\" &&\n getTableContext(item.table as SyncTableName<TRegistry>).managedAuthClaimCreateFields.length > 0,\n );\n const claims = needsAuthClaims ? await resolveAuthClaims() : undefined;\n\n const normalizedItems = items.map((item, index) => normalizeBatchItem(item, index, claims));\n const batchGroups = new Map<string, { context: TableContext; items: NormalizedBatchItem[] }>();\n\n for (const item of normalizedItems) {\n const existing = batchGroups.get(item.context.key);\n\n if (existing) {\n existing.items.push(item);\n continue;\n }\n\n batchGroups.set(item.context.key, {\n context: item.context,\n items: [item],\n });\n }\n\n for (const { context, items: groupedItems } of batchGroups.values()) {\n groupedItems.sort((left, right) => left.order - right.order);\n const uniqueEntities = dedupeBatchEntities(groupedItems);\n const latestMutationStates = await readLatestMutationStates(options.db, context, uniqueEntities);\n const currentRecordStates = await readCurrentRecordStates(options.db, context, uniqueEntities);\n const entityStates = new Map<string, BatchEntityState>();\n\n for (const entity of uniqueEntities) {\n const latestState = latestMutationStates.get(entity.entityKeyJson);\n const currentState = currentRecordStates.get(entity.entityKeyJson);\n\n entityStates.set(entity.entityKeyJson, {\n entityKey: entity.entityKey,\n entityKeyJson: entity.entityKeyJson,\n record: currentState ? extractRecordFromState(context, currentState) : null,\n overlayKind: currentState?.overlayKind ?? null,\n localUpdatedAtUs: currentState?.localUpdatedAtUs ?? null,\n latestMutationSeq: latestState?.latestMutationSeq ?? null,\n latestMutationKind: latestState?.latestMutationKind ?? null,\n latestMutationStatus: latestState?.latestMutationStatus ?? null,\n });\n }\n\n const plannedMutations: PlannedMutationInsert[] = [];\n const plannedOverlays = new Map<string, PlannedOverlayUpsert>();\n\n for (const item of groupedItems) {\n const entityState = entityStates.get(item.entityKeyJson);\n\n if (!entityState) {\n throw new Error(`Missing batch state for table ${context.key}`);\n }\n\n switch (item.kind) {\n case \"create\": {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n throw new Error(`${context.key} already has queued mutations`);\n }\n\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"create\",\n payloadJson: jsonStringifyPayload({\n kind: \"create\",\n value: item.input,\n }),\n nowUs: item.nowUs,\n // A create has no Base server version (ADR-0015): its conflict is a PK collision, a\n // separate concern from the stale-write check.\n baseServerVersion: null,\n });\n\n entityState.record = item.optimisticRecord;\n entityState.overlayKind = \"pending_create\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"create\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: item.optimisticRecord,\n overlayKind: \"pending_create\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"update\": {\n if (item.blind) {\n // ADR-0022 addendum — a BLIND update: the write target is excluded from the actor's read\n // shape (its rows never stream here), so there is no local base row to seed and no optimistic\n // state to show. It is meaningful ONLY when the write routes to the authoritative endpoint (the\n // /unit expander is authoritative): an optimistic-routed blind write has nothing to converge, so\n // it is rejected at enqueue. The `unit` fixes the route inside a `transaction` block; a plain\n // enqueue on a statically-pessimistic table earns its own pessimistic unit downstream.\n const routesPessimistic = unit ? unit.mode === \"pessimistic\" : context.entry.writeMode === \"pessimistic\";\n if (!routesPessimistic) {\n throw new Error(\n `${context.key}: updateBlind requires a pessimistic write unit — use transaction({ mode: \"pessimistic\" }) (an optimistic blind write has nothing to show and no base to converge)`,\n );\n }\n\n // KEEP the already-queued-for-deletion guard (journal-derived; needs no local record).\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // Plan a journal row ONLY — no overlay, so nothing enters the read model and nothing can linger\n // there. `baseServerVersion: null`: the /unit expander is authoritative, there is no base to\n // capture. The `pessimistic-blind` marker keeps the row off the optimistic flusher and lets\n // reconcile retire it after ack WITHOUT a synced echo (there is no visible row to converge).\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: null,\n writeMode: \"pessimistic-blind\",\n });\n\n // Advance only the journal-derived tracking (no record/overlay): so a later same-batch item on\n // this entity chains in author order and sees the pending blind write.\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n break;\n }\n\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n // ADR-0015: capture the Base server version BEFORE the record is replaced by the\n // optimistic value below (which overwrites the Server version with the client clock).\n const updateBaseServerVersion = captureChainHeadBase(context, entityState);\n const overlayKind = entityState.overlayKind === \"pending_create\" ? \"pending_create\" : \"pending_update\";\n const optimisticRecord = ensureRecord(\n buildOptimisticRecord(\n context,\n {\n ...entityState.record,\n ...item.patch,\n // Re-stamp the on-update managed timestamp(s) generically (governance-driven) — for a\n // convention table this is exactly `updatedAtUs`, for a custom-named Server version\n // it is that column, so the optimistic row never carries a stale managed value.\n ...buildUpdateManagedNowStamp(context, item.nowUs),\n },\n {\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n },\n ),\n );\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"update\",\n payloadJson: jsonStringifyPayload({\n kind: \"update\",\n patch: item.patch,\n }),\n nowUs: item.nowUs,\n baseServerVersion: updateBaseServerVersion,\n });\n\n entityState.record = optimisticRecord;\n entityState.overlayKind = overlayKind;\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"update\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: optimisticRecord,\n overlayKind,\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n case \"delete\": {\n if (!entityState.record) {\n throw new Error(`${context.key} not found in local read model`);\n }\n\n if (entityState.latestMutationKind === \"delete\" && entityState.latestMutationStatus !== \"acked\") {\n throw new Error(`${context.key} is already queued for deletion`);\n }\n\n const deleteBaseServerVersion = captureChainHeadBase(context, entityState);\n plannedMutations.push({\n mutationId: item.mutationId,\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n mutationKind: \"delete\",\n payloadJson: jsonStringifyPayload({\n kind: \"delete\",\n entityKey: item.entityKey,\n }),\n nowUs: item.nowUs,\n baseServerVersion: deleteBaseServerVersion,\n });\n\n entityState.overlayKind = \"pending_delete\";\n entityState.localUpdatedAtUs = item.nowUs;\n entityState.latestMutationSeq = (entityState.latestMutationSeq ?? 0) + 1;\n entityState.latestMutationKind = \"delete\";\n entityState.latestMutationStatus = \"pending\";\n plannedOverlays.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n record: entityState.record,\n overlayKind: \"pending_delete\",\n localUpdatedAtUs: item.nowUs,\n });\n break;\n }\n }\n }\n\n // ADR-0022: an explicit unit (from a `transaction` block) tags the whole batch; otherwise a\n // statically-`pessimistic` table earns its own per-enqueue unit, so its writes route to the\n // authoritative endpoint too. An optimistic table with no explicit unit stays untagged.\n const effectiveUnit: WriteUnit | undefined =\n unit ??\n (context.entry.writeMode === \"pessimistic\"\n ? { id: globalThis.crypto.randomUUID(), mode: \"pessimistic\" }\n : undefined);\n if (effectiveUnit?.mode === \"pessimistic\") {\n pessimisticUnitIds.add(effectiveUnit.id);\n }\n await insertMutationsBulk(options.db, context, plannedMutations, registryVersion, effectiveUnit);\n await upsertOverlayRecordsBulk(options.db, context, [...plannedOverlays.values()]);\n }\n\n return [...pessimisticUnitIds];\n };\n\n const runFlush = async (table?: SyncTableName<TRegistry>) => {\n const affectedContexts = new Map<string, TableContext>();\n const quarantinedMutationIds = new Set<string>();\n const conflictedMutationIds = new Set<string>();\n let processedCount = 0;\n\n do {\n const batchResult = await flushBatch(\n options.db,\n tableContexts as Record<string, TableContext>,\n options.writeUrl,\n maxMutationAttempts,\n flushBatchSize,\n table,\n resolveAuthToken,\n options.requestHeaders,\n );\n\n processedCount = batchResult.processedCount;\n\n for (const context of batchResult.affectedContexts) {\n affectedContexts.set(context.key, context);\n }\n\n for (const mutationId of batchResult.quarantinedMutationIds) {\n quarantinedMutationIds.add(mutationId);\n }\n\n for (const mutationId of batchResult.conflictedMutationIds) {\n conflictedMutationIds.add(mutationId);\n }\n } while (processedCount > 0);\n\n for (const context of affectedContexts.values()) {\n await reconcileTable(options.db, context);\n }\n\n // Surface newly-quarantined mutations after reconciliation so the app never has to\n // poll for permanently-rejected writes (ADR-0006 decision 4). Never silent loss.\n if (quarantinedMutationIds.size > 0 && options.onQuarantine) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n quarantinedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onQuarantine(details);\n }\n }\n\n // Surface newly-conflicted (stale) writes (ADR-0015). The optimistic Overlay is kept, so the app\n // can show a resolution/diff UI and resolve each as a new write (or discard it). Never silent.\n if (conflictedMutationIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(\n options.db,\n [...affectedContexts.values()],\n conflictedMutationIds,\n );\n\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n };\n\n const runtime: MutationRuntime<TRegistry> = {\n registryVersion,\n create: async (table, input) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"create\", input }]);\n });\n // A statically-`pessimistic` table foreground-routes its write to the authoritative endpoint\n // (ADR-0022) — the write is server-authoritative, so it is sent immediately, not left for the\n // optimistic convergence loop (which skips pessimistic rows).\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n update: async (table, entityKeyInput, patch) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"update\", entityKey: entityKeyInput, patch }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n delete: async (table, entityKeyInput) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch([{ table, kind: \"delete\", entityKey: entityKeyInput }]);\n });\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n },\n batch: async (items, unit) => {\n let unitIds: string[] = [];\n await runInTransaction(async () => {\n unitIds = await enqueueBatch(items, unit);\n });\n // An explicit unit (from a `transaction` block) is flushed by the caller; only foreground-route the\n // units a plain `batch()` generated for statically-pessimistic tables.\n if (!unit) {\n for (const unitId of unitIds) {\n await runtime.flushUnit(unitId);\n }\n }\n },\n discardConflict: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // discardTerminalEntity owns its own transaction (like reconcileTable), so it is not wrapped.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"conflicted\");\n },\n discardQuarantined: async (table, entityKeyInput) => {\n const context = getTableContext(table);\n const entityKey = normalizeEntityKey(context, entityKeyInput);\n const entityKeyJson = serializeEntityKey(entityKey);\n\n // Symmetric to discardConflict — retire the entity's `quarantined` journal rows and clear the\n // kept overlay behind the same owed-guard, so a permanently-rejected write is a real rollback.\n await discardTerminalEntity(options.db, context, entityKey, entityKeyJson, \"quarantined\");\n },\n flush: async (table) => {\n const nextFlush = flushQueue.then(() => runFlush(table));\n flushQueue = nextFlush.catch(() => undefined);\n await nextFlush;\n },\n flushUnit: async (unitId) => {\n const contexts = Object.values(tableContexts).filter((context): context is TableContext => context != null);\n const unitRows = await readUnitPendingRows(options.db, contexts, unitId);\n if (unitRows.length === 0) {\n return { acks: [] };\n }\n\n // Prepare the unit's rows (entity key + envelope payload) and group them by table.\n const prepared: PreparedBatchRow[] = [];\n const byContext = new Map<string, PreparedBatchRow[]>();\n for (const row of unitRows) {\n const context = tableContexts[row.tableKey];\n if (!context) {\n continue;\n }\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n prepared.push(preparedRow);\n const list = byContext.get(context.key);\n if (list) {\n list.push(preparedRow);\n } else {\n byContext.set(context.key, [preparedRow]);\n }\n }\n\n // Mark every member sending (persist the resolved Base server version, like the batch path).\n const sentAtUs = nowMicroseconds();\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = prepared.map((row) => ({\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n }));\n\n const url = resolveAuthoritativeMutationUrl(options.writeUrl);\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]>;\n\n try {\n const authToken = await options.getAuthToken?.();\n let response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n\n if ([401, 403].includes(response.status) && options.getAuthToken) {\n response = await fetch(url, {\n method: \"POST\",\n headers: buildRequestHeaders(await options.getAuthToken(), options.requestHeaders),\n body: jsonStringifyPayload({ writeUnit: unitId, mutations }),\n });\n }\n\n if (!response.ok) {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Authoritative write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n\n const responseJson = (await response.json()) as BatchMutationAck;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n } catch (error) {\n // A pessimistic write is foreground: it never reached the server (transport / non-2xx), so the\n // unit did not happen. Mark it failed — KEEPING the optimistic overlay so a retry can resend — and\n // rethrow so the caller surfaces it. There is no background retry for pessimistic units.\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Authoritative write failed\";\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveBatchFailureOutcome(attemptCount, maxMutationAttempts, failedAtUs);\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n throw error;\n }\n\n // Apply each member's ack.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n const rejectedIds = new Set<string>();\n const conflictedIds = new Set<string>();\n\n for (const rows of byContext.values()) {\n await applyMutationStatusUpdates(\n options.db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack?.status === \"rejected\") {\n // ADR-0022 §4: a business rejection. Terminal `rejected`; the overlay is auto-discarded below.\n rejectedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"rejected\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n lastError: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.rejectionReason ?? \"Rejected by the authoritative endpoint\",\n };\n }\n\n if (ack?.status === \"conflicted\") {\n // ADR-0015: a stale member — terminal `conflicted`, overlay KEPT (resolve as a new write).\n conflictedIds.add(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const outcome = resolveFailureOutcome(\n ack?.httpStatus ?? null,\n attemptCount,\n maxMutationAttempts,\n failedAtUs,\n );\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Authoritative write not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: ack?.httpStatus ?? null,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: row.mutationKind === \"delete\" ? 204 : 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n // ADR-0022 §4: auto-discard the optimistic overlay for every rejected entity (the whole unit was\n // declined). The terminal `rejected` journal row is kept for diagnostics + `onReject`.\n for (const row of prepared) {\n if (rejectedIds.has(row.mutationId)) {\n await discardOverlayForSettledEntity(options.db, row.context, row.entityKey, row.entityKeyJson);\n }\n }\n\n const affectedContexts = [...byContext.keys()]\n .map((key) => tableContexts[key])\n .filter((context): context is TableContext => context != null);\n for (const context of affectedContexts) {\n await reconcileTable(options.db, context);\n }\n\n if (rejectedIds.size > 0 && options.onReject) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, rejectedIds);\n if (details.length > 0) {\n await options.onReject(details);\n }\n }\n if (conflictedIds.size > 0 && options.onConflict) {\n const details = await readMutationDetailsForContexts(options.db, affectedContexts, conflictedIds);\n if (details.length > 0) {\n await options.onConflict(details);\n }\n }\n\n return { acks: [...acksByMutationId.values()] };\n },\n reconcile: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n\n for (const context of contexts) {\n await reconcileTable(options.db, context);\n }\n },\n retryFailed: async (table) => {\n assertValidMutationTransition(\"failed\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({ status: \"pending\", nextRetryAtUs: nowUs, updatedAtUs: nowUs, conflictReason: null })\n .where(eq(journal.status, \"failed\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n recoverSending: async (table) => {\n assertValidMutationTransition(\"sending\", \"pending\");\n const contexts = filterContexts(tableContexts, table);\n const nowUs = nowMicroseconds();\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n const query = queryBuilder\n .update(journal)\n .set({\n status: \"pending\",\n updatedAtUs: nowUs,\n sentAtUs: null,\n nextRetryAtUs: nowUs,\n lastError: null,\n lastHttpStatus: null,\n conflictReason: null,\n })\n .where(eq(journal.status, \"sending\"))\n .toSQL();\n await options.db.query(query.sql, query.params as unknown[]);\n }\n },\n readMutationStats: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n const totals: MutationDiagnostics = {\n pendingCount: 0,\n sendingCount: 0,\n failedCount: 0,\n quarantinedCount: 0,\n conflictedCount: 0,\n ackedCount: 0,\n };\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // Drizzle has no `FILTER` operator (tier ②): each aggregate is a typed `sql` fragment over the\n // journal `status` column object with a bound status literal, aliased to the exact camelCase row\n // key the totals below read (the raw seam returns rows UNMAPPED, so aliases are load-bearing).\n const filteredCount = (status: MutationStatus, columnAlias: string) =>\n sql<number>`count(*) filter (where ${journal.status} = ${status})::int`.as(columnAlias);\n const query = queryBuilder\n .select({\n pendingCount: filteredCount(\"pending\", \"pendingCount\"),\n sendingCount: filteredCount(\"sending\", \"sendingCount\"),\n failedCount: filteredCount(\"failed\", \"failedCount\"),\n quarantinedCount: filteredCount(\"quarantined\", \"quarantinedCount\"),\n conflictedCount: filteredCount(\"conflicted\", \"conflictedCount\"),\n ackedCount: filteredCount(\"acked\", \"ackedCount\"),\n })\n .from(journal)\n .toSQL();\n const result = await options.db.query<MutationDiagnostics & Record<string, unknown>>(\n query.sql,\n query.params as unknown[],\n );\n\n const row = result.rows[0];\n if (!row) {\n continue;\n }\n\n totals.pendingCount += row.pendingCount;\n totals.sendingCount += row.sendingCount;\n totals.failedCount += row.failedCount;\n totals.quarantinedCount += row.quarantinedCount;\n totals.conflictedCount += row.conflictedCount;\n totals.ackedCount += row.ackedCount;\n }\n\n return totals;\n },\n readMutationDetails: async (table) => {\n const contexts = filterContexts(tableContexts, table);\n return readMutationDetailsForContexts(options.db, contexts);\n },\n createOptimisticRecord: (table, input) => {\n const context = getTableContext(table);\n return createOptimisticRecordFromContext(context, input);\n },\n };\n\n return runtime;\n}\n\n/**\n * Read journal entries across the given contexts as {@link MutationDetail}s, newest first.\n * Shared by the public `readMutationDetails` and the flush path's quarantine surfacing,\n * optionally narrowed to a set of mutation ids.\n */\nasync function readMutationDetailsForContexts(\n db: MutationDb,\n contexts: TableContext[],\n mutationIds?: ReadonlySet<string>,\n): Promise<MutationDetail[]> {\n const rows: MutationDetail[] = [];\n\n for (const context of contexts) {\n const journal = context.tables.journal;\n // The raw seam returns rows UNMAPPED (no drizzle result mapping), so every field is aliased\n // explicitly to its camelCase row key, and the `_us` bigints keep their `::text` casts.\n const query = queryBuilder\n .select({\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n updatedAtUs: sql<string>`${journal.updatedAtUs}::text`.as(\"updatedAtUs\"),\n registryVersion: sql<string | null>`${journal.registryVersion}`.as(\"registryVersion\"),\n })\n .from(journal)\n .orderBy(desc(journal.updatedAtUs), desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<MutationDetailRow>(query.sql, query.params as unknown[]);\n\n for (const row of result.rows) {\n if (mutationIds && !mutationIds.has(row.mutationId)) {\n continue;\n }\n\n rows.push({\n tableName: context.key,\n entityKey: JSON.parse(row.entityKeyJson) as Record<string, string>,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n mutationKind: row.mutationKind,\n status: row.status,\n attemptCount: row.attemptCount,\n lastHttpStatus: row.lastHttpStatus,\n lastError: row.lastError,\n conflictReason: row.conflictReason,\n nextRetryAtUs: row.nextRetryAtUs,\n serverUpdatedAtUs: row.serverUpdatedAtUs,\n updatedAtUs: row.updatedAtUs,\n registryVersion: row.registryVersion,\n });\n }\n }\n\n return rows.sort((left, right) => Number(right.updatedAtUs) - Number(left.updatedAtUs));\n}\n\ninterface MutationRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n payloadJson: string;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n registryVersion: string | null;\n}\n\ninterface MutationDetailRow extends Record<string, unknown> {\n mutationId: string;\n entityKeyJson: string;\n mutationSeq: number;\n mutationKind: MutationKind;\n status: MutationStatus;\n attemptCount: number;\n lastHttpStatus: number | null;\n lastError: string | null;\n conflictReason: string | null;\n nextRetryAtUs: string | null;\n serverUpdatedAtUs: string | null;\n updatedAtUs: string;\n registryVersion: string | null;\n}\n\ninterface CurrentRecordStateRow extends Record<string, unknown> {\n overlayKind: string;\n localUpdatedAtUs: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchLatestMutationStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ninterface BatchCurrentRecordStateRow extends Record<string, unknown> {\n entityKeyJson: string;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityRef {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n}\n\ninterface PlannedMutationInsert {\n mutationId: string;\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationKind: MutationKind;\n payloadJson: string;\n nowUs: string;\n /**\n * The Base server version (ADR-0015) stamped at enqueue: the synced Server version the user saw,\n * for a **chain head** (the first staged write on the entity). `null` for a `create` (no base) and\n * for a **chained** write — the latter resolves its base at flush from its acked predecessor\n * (readPendingBatchRows), by Per-entity flush serialization (ADR-0014).\n */\n baseServerVersion: string | null;\n /**\n * A per-row `write_mode` override (ADR-0022 addendum). Left unset for an ordinary row, which inherits the\n * unit's mode at insert. A blind update sets `\"pessimistic-blind\"` so the row is flushed only by its unit's\n * foreground path (never the optimistic batch) and retires from the journal without a synced echo.\n */\n writeMode?: string | null;\n}\n\ninterface PlannedOverlayUpsert {\n entityKey: Record<string, string>;\n record: Record<string, unknown>;\n overlayKind: string;\n localUpdatedAtUs: string;\n}\n\ninterface BatchEntityState {\n entityKey: Record<string, string>;\n entityKeyJson: string;\n record: Record<string, unknown> | null;\n overlayKind: string | null;\n localUpdatedAtUs: string | null;\n latestMutationSeq: number | null;\n latestMutationKind: MutationKind | null;\n latestMutationStatus: MutationStatus | null;\n}\n\ntype NormalizedBatchItem =\n | {\n context: TableContext;\n kind: \"create\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n optimisticRecord: Record<string, unknown>;\n input: unknown;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"update\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n patch: Record<string, unknown>;\n /** A blind update (ADR-0022 addendum): journal-only, no base-row presence check, no overlay. */\n blind: boolean;\n mutationId: string;\n nowUs: string;\n order: number;\n }\n | {\n context: TableContext;\n kind: \"delete\";\n entityKey: Record<string, string>;\n entityKeyJson: string;\n mutationId: string;\n nowUs: string;\n order: number;\n };\n\n/**\n * The Base server version (ADR-0015) to stamp at enqueue for an update/delete. Only a **chain head**\n * — the first staged write on the entity (no earlier unresolved mutation) — captures an enqueue-time\n * base: the synced Server version the user's edit was authored against, so a genuine external write\n * between view and apply is caught. A **chained** write (an earlier same-entity mutation is still\n * owed) returns `null` here; it resolves its base at flush from its acked predecessor, so an entity's\n * own successive edits never self-conflict (decision 2).\n */\nfunction captureChainHeadBase(context: TableContext, entityState: BatchEntityState): string | null {\n if ((entityState.latestMutationSeq ?? 0) !== 0) {\n return null;\n }\n\n if (!context.serverVersionPropertyKey || !entityState.record) {\n return null;\n }\n\n // The Server version is a bigint count of microseconds, surfaced as a string/number/bigint\n // depending on the read path. Anything else (null/object) means no observable base.\n const raw = entityState.record[context.serverVersionPropertyKey];\n if (typeof raw === \"string\" || typeof raw === \"number\" || typeof raw === \"bigint\") {\n return String(raw);\n }\n\n return null;\n}\n\nfunction buildTableContexts<TRegistry extends SyncTableRegistry>(registry: TRegistry) {\n const localSchema = getSyncRegistrySchema(registry);\n\n return Object.fromEntries(\n Object.entries(registry)\n .filter(([, entry]) => entry.mode !== \"readonly\")\n .map(([key, entry]) => [key, buildTableContext(registry, key, entry, localSchema)]),\n ) as Partial<Record<SyncTableName<TRegistry>, TableContext>>;\n}\n\nfunction buildTableContext<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n key: string,\n entry: SyncTableEntry<AnyPgTable>,\n localSchema: string,\n): TableContext {\n if (!entry.clientProjection?.overlayTable || !entry.clientProjection.journalTable) {\n throw new Error(`overlay and journal tables are required for writable table ${key}`);\n }\n\n const columns = getProjectedTableColumns(entry).map(({ propertyKey, column }) => ({\n propertyKey,\n column,\n }));\n\n const pkPropertyKeys = entry.primaryKey.columns.map((columnName) => {\n const column = columns.find((candidate) => candidate.column.name === columnName);\n\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on table ${key}`);\n }\n\n return column.propertyKey;\n });\n\n const serverVersionColumnName = resolveServerVersionColumnName(entry) ?? null;\n const serverVersionPropertyKey = serverVersionColumnName\n ? (columns.find((candidate) => candidate.column.name === serverVersionColumnName)?.propertyKey ?? null)\n : null;\n\n // Resolve the `nowMicroseconds` managed fields generically from governance, not by property name.\n // `field.column` is a drizzle property key, but tolerate a column-name declaration too.\n const resolveManagedPropertyKey = (fieldColumn: string): string | undefined =>\n columns.find((candidate) => candidate.propertyKey === fieldColumn || candidate.column.name === fieldColumn)\n ?.propertyKey;\n const nowMicrosecondsManagedFields = (entry.governance?.managedFields ?? []).filter(\n (field) => field.strategy === \"nowMicroseconds\",\n );\n const managedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n const updateManagedNowMicrosecondsPropertyKeys = nowMicrosecondsManagedFields\n .filter((field) => field.applyOn.includes(\"update\"))\n .map((field) => resolveManagedPropertyKey(field.column as string))\n .filter((propertyKey): propertyKey is string => propertyKey !== undefined);\n\n const managedAuthClaimCreateFields = (entry.governance?.managedFields ?? [])\n .filter((field) => field.strategy === \"authClaim\" && field.applyOn.includes(\"create\"))\n .flatMap((field) => {\n const propertyKey = resolveManagedPropertyKey(field.column as string);\n return propertyKey && field.claimPath ? [{ propertyKey, claimPath: field.claimPath }] : [];\n });\n\n // The generated local relations as runtime Drizzle objects (memoized per registry+key in\n // local-tables.ts), plus name-resolved column handles the statement authors below need:\n // overlay/synced columns are keyed by PROPERTY key, so PK columns (a DB-column-name concept,\n // ADR-0012) are resolved once here by matching `.name`.\n const tables = {\n synced: getSyncedLocalTable(registry, key as string & keyof TRegistry),\n overlay: getOverlayTable(registry, key as string & keyof TRegistry),\n journal: getJournalTable(registry, key as string & keyof TRegistry),\n };\n const overlayColumnsByPropertyKey = getColumns(tables.overlay) as Record<string, PgColumn>;\n const syncedColumnsByPropertyKey = getColumns(tables.synced) as Record<string, PgColumn>;\n const resolvePkColumns = (columnsByKey: Record<string, PgColumn>, relation: string) =>\n entry.primaryKey.columns.map((columnName) => {\n const column = Object.values(columnsByKey).find((candidate) => candidate.name === columnName);\n if (!column) {\n throw new Error(`Primary key column ${columnName} was not found on the ${relation} table for ${key}`);\n }\n return column;\n });\n const syncedServerVersionColumn = serverVersionColumnName\n ? (Object.values(syncedColumnsByPropertyKey).find((candidate) => candidate.name === serverVersionColumnName) ??\n null)\n : null;\n\n return {\n key,\n entry,\n readModel: qualifyLocalIdentifier(\n localSchema,\n entry.view != null\n ? getViewConfig(entry.view).name\n : (entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name),\n ),\n syncedTable: qualifyLocalIdentifier(\n localSchema,\n entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,\n ),\n overlayTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.overlayTable),\n journalTable: qualifyLocalIdentifier(localSchema, entry.clientProjection.journalTable),\n journalSequence: qualifyLocalIdentifier(localSchema, buildJournalSequenceName(entry.clientProjection.journalTable)),\n pkColumnNames: [...entry.primaryKey.columns],\n pkPropertyKeys,\n serverVersionColumnName,\n serverVersionPropertyKey,\n managedNowMicrosecondsPropertyKeys,\n updateManagedNowMicrosecondsPropertyKeys,\n managedAuthClaimCreateFields,\n recordIncludesOverlayState: \"overlayTable\" in (entry.clientProjection ?? {}),\n columns,\n tables,\n overlayColumnsByPropertyKey,\n syncedColumnsByPropertyKey,\n overlayPkColumns: resolvePkColumns(overlayColumnsByPropertyKey, \"overlay\"),\n syncedPkColumns: resolvePkColumns(syncedColumnsByPropertyKey, \"synced\"),\n syncedServerVersionColumn,\n };\n}\n\nfunction filterContexts<TRegistry extends SyncTableRegistry>(\n contexts: Partial<Record<SyncTableName<TRegistry>, TableContext>>,\n table?: SyncTableName<TRegistry>,\n) {\n if (table) {\n const context = contexts[table];\n return context ? [context] : [];\n }\n\n return Object.values(contexts).filter((context): context is TableContext => context !== undefined);\n}\n\n/**\n * Materialise a column's default into a concrete JS value for the optimistic overlay\n * row. The overlay INSERT writes an explicit value for every projected column (an\n * omitted column becomes a literal `NULL`, which overrides any table-level DEFAULT), so\n * a column declared `NOT NULL DEFAULT <x>` that the caller omits would violate the\n * overlay's NOT NULL constraint unless we fill the default here — mirroring what the\n * authoritative server applies on the base table.\n *\n * Only values we can produce client-side are materialised: a value-returning `defaultFn`\n * (e.g. `$defaultFn`) or a literal `.default(value)`. SQL-expression defaults\n * (`.default(sql\\`…\\`)`, `defaultRandom()`, `defaultNow()`) cannot be evaluated without\n * the database, so they are left to the server (the column is then expected to be either\n * caller-supplied or nullable in the optimistic row).\n */\nfunction materializeColumnDefault(column: TableContext[\"columns\"][number][\"column\"]): {\n ok: boolean;\n value?: unknown;\n} {\n if (!column.hasDefault) {\n return { ok: false };\n }\n\n if (typeof column.defaultFn === \"function\") {\n const produced = column.defaultFn();\n return is(produced, SQL) ? { ok: false } : { ok: true, value: produced };\n }\n\n if (column.default !== undefined && !is(column.default, SQL)) {\n return { ok: true, value: column.default };\n }\n\n return { ok: false };\n}\n\nfunction createOptimisticRecordFromContext<TCreate, TRecord>(\n context: TableContext,\n input: TCreate,\n claims?: Record<string, unknown>,\n): TRecord {\n const record = {\n ...(isRecord(input) ? input : {}),\n };\n const nowUs = nowMicroseconds();\n\n // Stamp `authClaim` create-managed fields (owner/author/created_by) from the decoded claim at the\n // field's path, so the optimistic overlay row is attributed locally and satisfies the column's NOT\n // NULL — the server independently stamps the same claim on apply, so the value never flips on\n // convergence. (`auth.uid()` is just `claimPath: [\"sub\"]`.)\n if (claims != null) {\n for (const { propertyKey, claimPath } of context.managedAuthClaimCreateFields) {\n if (record[propertyKey] === undefined) {\n const value = readJwtClaimPath(claims, claimPath);\n if (value !== undefined) {\n record[propertyKey] = value;\n }\n }\n }\n }\n\n if (hasProperty(context, \"createdAtUs\") && record[\"createdAtUs\"] === undefined) {\n record[\"createdAtUs\"] = nowUs;\n }\n\n if (hasProperty(context, \"updatedAtUs\") && record[\"updatedAtUs\"] === undefined) {\n record[\"updatedAtUs\"] = nowUs;\n }\n\n // Generic managed-timestamp fill (governance-driven): stamp any `nowMicroseconds` managed field the\n // convention block above did not — e.g. a Server version column not named `updated_at_us`. Additive\n // and idempotent, so convention tables are unaffected (their fields are already filled).\n for (const propertyKey of context.managedNowMicrosecondsPropertyKeys) {\n if (record[propertyKey] === undefined) {\n record[propertyKey] = nowUs;\n }\n }\n\n for (const { propertyKey, column } of context.columns) {\n if (record[propertyKey] !== undefined) {\n continue;\n }\n\n const materialized = materializeColumnDefault(column);\n if (materialized.ok) {\n record[propertyKey] = materialized.value;\n }\n }\n\n return buildOptimisticRecord(context, record, {\n overlayKind: \"pending_create\",\n localUpdatedAtUs: nowUs,\n }) as TRecord;\n}\n\n/**\n * Stamp every on-update `nowMicroseconds` managed field with `nowUs` (governance-driven, ADR-0004),\n * keyed by drizzle property key. For a convention table this is exactly `{ updatedAtUs: nowUs }`; for\n * a custom-named Server version it targets that column — so the local optimistic path never assumes\n * the demo naming the generic server applier does not.\n */\nfunction buildUpdateManagedNowStamp(context: TableContext, nowUs: string): Record<string, string> {\n return Object.fromEntries(\n context.updateManagedNowMicrosecondsPropertyKeys.map((propertyKey) => [propertyKey, nowUs]),\n );\n}\n\nfunction buildOptimisticRecord(\n context: TableContext,\n record: Record<string, unknown>,\n options: {\n overlayKind: string;\n localUpdatedAtUs: string;\n },\n) {\n if (!context.recordIncludesOverlayState) {\n return record;\n }\n\n return {\n ...record,\n overlayKind: options.overlayKind,\n localUpdatedAtUs: options.localUpdatedAtUs,\n };\n}\n\nfunction buildEntityKeyFromRecord(context: TableContext, record: unknown) {\n const recordObject = ensureRecord(record);\n return normalizeEntityKey(\n context,\n Object.fromEntries(context.pkPropertyKeys.map((propertyKey) => [propertyKey, String(recordObject[propertyKey])])),\n );\n}\n\nfunction normalizeEntityKey(context: TableContext, input: Record<string, string>) {\n // The public API accepts the identity by drizzle property name (ergonomics); past this\n // boundary the canonical Entity identity is column-keyed (ADR-0012), matching the\n // journal/overlay PK columns, entity_key_json, and the applier's `v_entity_key->>'<column>'`.\n // pkPropertyKeys[i] ↔ pkColumnNames[i] by construction (buildTableContext), so we map once here.\n return Object.fromEntries(\n context.pkPropertyKeys.map((propertyKey, index) => {\n const value = input[propertyKey];\n\n if (value === undefined) {\n throw new Error(`Missing entity key property ${propertyKey} for table ${context.key}`);\n }\n\n return [context.pkColumnNames[index]!, String(value)];\n }),\n );\n}\n\nfunction serializeEntityKey(entityKey: Record<string, string>) {\n return JSON.stringify(entityKey);\n}\n\nfunction dedupeBatchEntities(items: ReadonlyArray<NormalizedBatchItem>): BatchEntityRef[] {\n const entities = new Map<string, BatchEntityRef>();\n\n for (const item of items) {\n if (!entities.has(item.entityKeyJson)) {\n entities.set(item.entityKeyJson, {\n entityKey: item.entityKey,\n entityKeyJson: item.entityKeyJson,\n });\n }\n }\n\n return [...entities.values()];\n}\n\nasync function readLatestMutationStates(\n db: MutationDb,\n context: TableContext,\n entities: ReadonlyArray<BatchEntityRef>,\n) {\n if (entities.length === 0) {\n return new Map<string, BatchLatestMutationStateRow>();\n }\n\n // The old VALUES-CTE + LEFT-JOIN-back-to-input existed only to emit null rows for entities with\n // no journal history; the caller reads via `map.get(...) ?? null`, so a missing key is equivalent.\n const journal = context.tables.journal;\n const query = queryBuilder\n .selectDistinctOn([journal.entityKeyJson], {\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n latestMutationSeq: sql<number>`${journal.mutationSeq}`.as(\"latestMutationSeq\"),\n latestMutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"latestMutationKind\"),\n latestMutationStatus: sql<MutationStatus>`${journal.status}`.as(\"latestMutationStatus\"),\n })\n .from(journal)\n .where(\n inArray(\n journal.entityKeyJson,\n entities.map((entity) => entity.entityKeyJson),\n ),\n )\n .orderBy(journal.entityKeyJson, desc(journal.mutationSeq))\n .toSQL();\n const result = await db.query<BatchLatestMutationStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function readCurrentRecordStates(db: MutationDb, context: TableContext, entities: ReadonlyArray<BatchEntityRef>) {\n if (entities.length === 0) {\n return new Map<string, BatchCurrentRecordStateRow>();\n }\n\n // Tier ②: the overlay-∪-synced shape over an input VALUES table. The input CTE carries each\n // entity's `entity_key_json` alongside its PK values (the caller maps rows back by that JSON), so\n // it cannot be a plain builder select; every identifier still comes from the table objects /\n // `sql.identifier`, and every value is a bound (cast-typed) param.\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n const inputCte = buildEntityInputCte(context, entities);\n const overlaySelectColumns = buildProjectedSelectColumns(context, context.overlayColumnsByPropertyKey);\n const syncedSelectColumns = buildProjectedSelectColumns(context, context.syncedColumnsByPropertyKey);\n const inputOverlayJoin = buildEntityInputJoin(context.pkColumnNames, context.overlayPkColumns);\n const inputSyncedJoin = buildEntityInputJoin(context.pkColumnNames, context.syncedPkColumns);\n const syncedUpdatedAtColumn = context.syncedColumnsByPropertyKey[\"updatedAtUs\"];\n const syncedLocalUpdated =\n hasProperty(context, \"updatedAtUs\") && syncedUpdatedAtColumn\n ? sql`${syncedUpdatedAtColumn}::text AS \"localUpdatedAtUs\"`\n : sql`'0' AS \"localUpdatedAtUs\"`;\n\n const query = queryDialect.sqlToQuery(sql`\n WITH ${inputCte},\n overlay_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${overlaySelectColumns},\n ${overlay.overlayKind} AS \"overlayKind\",\n ${overlay.localUpdatedAtUs}::text AS \"localUpdatedAtUs\"\n FROM input_entities AS input\n JOIN ${overlay}\n ON ${inputOverlayJoin}\n ),\n synced_rows AS (\n SELECT\n input.entity_key_json AS \"entityKeyJson\",\n ${syncedSelectColumns},\n ${\"synced\"} AS \"overlayKind\",\n ${syncedLocalUpdated}\n FROM input_entities AS input\n JOIN ${synced}\n ON ${inputSyncedJoin}\n WHERE NOT EXISTS (\n SELECT 1\n FROM ${overlay}\n WHERE ${inputOverlayJoin}\n )\n )\n SELECT *\n FROM overlay_rows\n UNION ALL\n SELECT *\n FROM synced_rows\n `);\n const result = await db.query<BatchCurrentRecordStateRow>(query.sql, query.params as unknown[]);\n\n return new Map(result.rows.map((row) => [row.entityKeyJson, row]));\n}\n\nasync function insertMutationsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedMutationInsert>,\n registryVersion: string | null,\n unit?: WriteUnit,\n) {\n if (rows.length === 0) {\n return;\n }\n\n // ADR-0022: a dynamic write-unit tags every row of the batch with one shared unit id + mode; the\n // default path leaves both NULL (the flusher derives mode/unit from the static group). A blind row\n // carries its own `write_mode` override (`pessimistic-blind`), so the mode is resolved per row.\n const writeUnit = unit?.id ?? null;\n const journal = context.tables.journal;\n // `mutationSeq` is intentionally omitted: the generated journal DDL carries\n // `mutation_seq ... DEFAULT nextval(<journal sequence>)`, so the DB default assigns it — drizzle\n // renders `default` for every column a row does not provide.\n const values = rows.map((row) => ({\n mutationId: row.mutationId,\n ...Object.fromEntries(context.pkColumnNames.map((columnName) => [columnName, row.entityKey[columnName]])),\n entityKeyJson: row.entityKeyJson,\n mutationKind: row.mutationKind,\n status: \"pending\",\n registryVersion,\n baseServerVersion: row.baseServerVersion,\n payloadJson: row.payloadJson,\n enqueuedAtUs: row.nowUs,\n nextRetryAtUs: row.nowUs,\n updatedAtUs: row.nowUs,\n writeUnit,\n writeMode: row.writeMode ?? unit?.mode ?? null,\n }));\n\n const query = queryBuilder\n .insert(journal)\n .values(values as PgInsertValue<JournalTable>[])\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n\n // Lifecycle origin: the moment each mutation is first staged into the journal. Correlates by id with\n // the later \"board-write sending\"/\"board-write acks\" lines (staged → sent → acked, per id).\n for (const row of rows) {\n syncDebug(\"mutation staged\", { mutationId: row.mutationId, table: context.key });\n }\n}\n\nasync function upsertOverlayRecordsBulk(\n db: MutationDb,\n context: TableContext,\n rows: ReadonlyArray<PlannedOverlayUpsert>,\n) {\n if (rows.length === 0) {\n return;\n }\n\n const overlay = context.tables.overlay;\n const values = rows.map((row) => ({\n ...Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, row.record[propertyKey] ?? null])),\n overlayKind: row.overlayKind,\n localUpdatedAtUs: row.localUpdatedAtUs,\n }));\n // Every inserted column (the projection + the two overlay columns) takes its EXCLUDED value on\n // conflict — the fixed alias PostgreSQL defines for the proposed row; its column names are the\n // table's own, so they come from the column objects via `sql.identifier`.\n const excludedSet = Object.fromEntries([\n ...context.columns.map(({ propertyKey, column }) => [propertyKey, sql`excluded.${sql.identifier(column.name)}`]),\n [\"overlayKind\", sql`excluded.${sql.identifier(overlay.overlayKind.name)}`],\n [\"localUpdatedAtUs\", sql`excluded.${sql.identifier(overlay.localUpdatedAtUs.name)}`],\n ]) as Record<string, SQL>;\n\n const query = queryBuilder\n .insert(overlay)\n .values(values as PgInsertValue<OverlayTable>[])\n .onConflictDoUpdate({ target: context.overlayPkColumns, set: excludedSet })\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\n/**\n * The batch-input CTE as a typed fragment: `input_entities (entity_key_json, <pks…>) AS (VALUES …)`\n * with every value a bound param, cast to its PK column's type (an untyped VALUES column would\n * otherwise default to text and break the join against a uuid/int PK).\n */\nfunction buildEntityInputCte(context: TableContext, entities: ReadonlyArray<BatchEntityRef>): SQL {\n const columnNames = [\"entity_key_json\", ...context.pkColumnNames];\n const tuples = entities.map((entity) => {\n const values = [\n sql`${entity.entityKeyJson}`,\n ...context.pkColumnNames.map((columnName) => {\n const columnEntry = context.columns.find(({ column }) => column.name === columnName);\n const castSuffix = columnEntry ? resolveInputCastSuffix(columnEntry.column.columnType) : \"\";\n // The cast keyword is a FIXED type suffix selected from the closed switch below — never\n // derived from user data — so `sql.raw` is safe here; the value itself is a bound param.\n return castSuffix\n ? sql`${entity.entityKey[columnName]}${sql.raw(castSuffix)}`\n : sql`${entity.entityKey[columnName]}`;\n }),\n ];\n return sql`(${sql.join(values, sql`, `)})`;\n });\n\n return sql`input_entities (${sql.join(\n columnNames.map((columnName) => sql.identifier(columnName)),\n sql`, `,\n )}) AS (VALUES ${sql.join(tuples, sql`, `)})`;\n}\n\nfunction resolveInputCastSuffix(columnType: string): string {\n switch (columnType) {\n case \"PgUUID\":\n return \"::uuid\";\n case \"PgBigInt64\":\n case \"PgBigInt53\":\n return \"::bigint\";\n case \"PgInteger\":\n case \"PgSerial\":\n case \"PgSmallInt\":\n return \"::int\";\n case \"PgBoolean\":\n return \"::boolean\";\n case \"PgTimestamp\":\n case \"PgTimestampString\":\n return \"::timestamp\";\n default:\n return \"\";\n }\n}\n\n/**\n * The projected columns of one branch (overlay or synced) as select-list fragments, aliased to\n * their camelCase property keys — the raw seam returns rows unmapped, so the aliases ARE the row\n * keys — with `::text` casts on the bigint columns (matching how the runtime reads them).\n */\nfunction buildProjectedSelectColumns(context: TableContext, columnsByPropertyKey: Record<string, PgColumn>): SQL {\n return sql.join(\n context.columns.map(({ propertyKey, column }) => {\n const target = columnsByPropertyKey[propertyKey];\n if (!target) {\n throw new Error(`Projected column ${propertyKey} was not found on the local tables for ${context.key}`);\n }\n if (column.columnType === \"PgBigInt64\" || column.columnType === \"PgBigInt53\") {\n return sql`${target}::text AS ${sql.identifier(propertyKey)}`;\n }\n return sql`${target} AS ${sql.identifier(propertyKey)}`;\n }),\n sql`, `,\n );\n}\n\n/** PK equality between a branch table's columns and the `input` CTE, as a typed fragment. */\nfunction buildEntityInputJoin(pkColumnNames: string[], pkColumns: PgColumn[]): SQL {\n return sql.join(\n pkColumnNames.map((columnName, index) => sql`${pkColumns[index]!} = input.${sql.identifier(columnName)}`),\n sql` AND `,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Batch flush — sends one send-eligible slice of pending mutations across all\n// target tables in a single POST /api/mutations call. The public flush()\n// wrapper loops until no more eligible rows remain.\n// ---------------------------------------------------------------------------\n\ninterface PendingBatchRow extends MutationRow {\n tableKey: string;\n enqueuedAtUs: string;\n /** The resolved Base server version (ADR-0015), or null when the table predates the policy. */\n baseServerVersion: string | null;\n}\n\ninterface PreparedBatchRow extends PendingBatchRow {\n context: TableContext;\n entityKey: Record<string, string>;\n envelopePayload: Record<string, unknown>;\n sqlTableName: string;\n}\n\ninterface FlushBatchResult {\n processedCount: number;\n affectedContexts: TableContext[];\n /** Mutation ids that transitioned to `quarantined` in this slice (ADR-0006), for surfacing. */\n quarantinedMutationIds: string[];\n /** Mutation ids that transitioned to `conflicted` in this slice (ADR-0015), for surfacing. */\n conflictedMutationIds: string[];\n}\n\ninterface MutationStatusUpdate {\n mutationId: string;\n status: MutationStatus;\n attemptCount: number;\n updatedAtUs: string;\n sentAtUs?: string | null;\n replaceSentAtUs?: boolean;\n ackedAtUs?: string | null;\n replaceAckedAtUs?: boolean;\n serverUpdatedAtUs?: string | null;\n replaceServerUpdatedAtUs?: boolean;\n baseServerVersion?: string | null;\n replaceBaseServerVersion?: boolean;\n lastError?: string | null;\n nextRetryAtUs?: string | null;\n lastHttpStatus?: number | null;\n conflictReason?: string | null;\n}\n\n/**\n * The resolved Base server version (ADR-0015) for a row at flush. A **chain head** already carries\n * `base_server_version` (stamped at enqueue), so COALESCE returns it untouched — keeping the\n * enqueue-time base means a genuine external write between view and apply is still caught. A\n * **chained** write has NULL there; it resolves to its **acked predecessor's** Server version (by\n * Per-entity flush serialization the predecessor is already acked when this row flushes), falling\n * back to the entity's current synced version once that predecessor has been reconciled away. Either\n * fallback yields the entity's own latest server state, so its own chain never self-conflicts.\n */\nfunction buildResolvedBaseServerVersion(context: TableContext): SQL {\n const journal = context.tables.journal;\n const synced = context.tables.synced;\n const pred = alias(journal, \"pred\");\n const predecessor = queryBuilder\n .select({ value: sql`MAX(${pred.serverUpdatedAtUs})` })\n .from(pred)\n .where(\n and(\n eq(pred.entityKeyJson, journal.entityKeyJson),\n lt(pred.mutationSeq, journal.mutationSeq),\n eq(pred.status, \"acked\"),\n ),\n );\n\n if (!context.syncedServerVersionColumn) {\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor})::text`;\n }\n\n const syncedFallback = queryBuilder\n .select({ value: sql`${context.syncedServerVersionColumn}` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) => eq(context.syncedPkColumns[index]!, journal[columnName]!)),\n ),\n );\n\n return sql`COALESCE(${journal.baseServerVersion}, ${predecessor}, ${syncedFallback})::text`;\n}\n\n/**\n * One table's send-eligible journal rows as a builder select with the shared {@link PendingBatchRow}\n * projection — the aliases ARE the row keys (raw seam), `tableKey` rides as a bound param, and the\n * resolved Base server version (ADR-0015) is the typed COALESCE fragment above.\n */\nfunction buildPendingRowsProjection(context: TableContext) {\n const journal = context.tables.journal;\n return {\n tableKey: sql<string>`${context.key}`.as(\"tableKey\"),\n mutationId: sql<string>`${journal.mutationId}`.as(\"mutationId\"),\n entityKeyJson: sql<string>`${journal.entityKeyJson}`.as(\"entityKeyJson\"),\n mutationSeq: sql<number>`${journal.mutationSeq}`.as(\"mutationSeq\"),\n mutationKind: sql<MutationKind>`${journal.mutationKind}`.as(\"mutationKind\"),\n status: journal.status,\n payloadJson: sql<string>`${journal.payloadJson}`.as(\"payloadJson\"),\n attemptCount: sql<number>`${journal.attemptCount}`.as(\"attemptCount\"),\n lastHttpStatus: sql<number | null>`${journal.lastHttpStatus}`.as(\"lastHttpStatus\"),\n lastError: sql<string | null>`${journal.lastError}`.as(\"lastError\"),\n conflictReason: sql<string | null>`${journal.conflictReason}`.as(\"conflictReason\"),\n nextRetryAtUs: sql<string | null>`${journal.nextRetryAtUs}::text`.as(\"nextRetryAtUs\"),\n serverUpdatedAtUs: sql<string | null>`${journal.serverUpdatedAtUs}::text`.as(\"serverUpdatedAtUs\"),\n baseServerVersion: buildResolvedBaseServerVersion(context).as(\"baseServerVersion\"),\n enqueuedAtUs: sql<string>`${journal.enqueuedAtUs}::text`.as(\"enqueuedAtUs\"),\n };\n}\n\nasync function readPendingBatchRows(db: MutationDb, contexts: TableContext[], nowUs: string, batchSize: number) {\n if (contexts.length === 0) {\n return [] as PendingBatchRow[];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n const earlier = alias(journal, \"earlier\");\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(\n and(\n inArray(journal.status, [\"pending\", \"failed\"]),\n // ADR-0022: pessimistic rows are flushed by the authoritative unit path (flushUnit), never the\n // optimistic batch — exclude them here so a tagged write is never optimistically sent. The\n // `NOT LIKE 'pessimistic%'` also excludes a `pessimistic-blind` row (ADR-0022 addendum), which\n // belongs to its unit's foreground flush too.\n sql`COALESCE(${journal.writeMode}, '') NOT LIKE 'pessimistic%'`,\n sql`COALESCE(${journal.nextRetryAtUs}, 0) <= ${nowUs}::bigint`,\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(earlier)\n .where(\n and(\n eq(earlier.entityKeyJson, journal.entityKeyJson),\n lt(earlier.mutationSeq, journal.mutationSeq),\n // A still-unresolved earlier mutation blocks later same-entity ones so the\n // server applies them in author order. The quarantined status is included: a\n // later mutation must not flush past a prerequisite the server permanently\n // rejected (it would itself fail); resolving the quarantine unblocks the queue.\n inArray(earlier.status, [\"pending\", \"failed\", \"sending\", \"quarantined\"]),\n ),\n ),\n ),\n ),\n );\n });\n\n // The union rides inside a derived table because the outer ORDER BY casts the (text) output\n // columns — a set operation's own ORDER BY may only name plain output columns. The `pending`\n // alias and its two quoted output-column names are fixed by the projection above, not data.\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS pending ORDER BY pending.\"enqueuedAtUs\"::bigint ASC, pending.\"mutationSeq\" ASC LIMIT ${batchSize}`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\n/**\n * Read one pessimistic write-unit's send-eligible rows (ADR-0022) across every table, ordered by author\n * sequence. Unlike {@link readPendingBatchRows} it has no per-entity ordering gate: a unit is enqueued and\n * sent atomically, so its members go together.\n */\nasync function readUnitPendingRows(\n db: MutationDb,\n contexts: TableContext[],\n unitId: string,\n): Promise<PendingBatchRow[]> {\n if (contexts.length === 0) {\n return [];\n }\n\n const branches = contexts.map((context) => {\n const journal = context.tables.journal;\n return queryBuilder\n .select(buildPendingRowsProjection(context))\n .from(journal)\n .where(and(eq(journal.writeUnit, unitId), inArray(journal.status, [\"pending\", \"failed\"])));\n });\n\n const query = queryDialect.sqlToQuery(\n sql`SELECT * FROM (${sql.join(branches, sql` UNION ALL `)}) AS unit ORDER BY unit.\"mutationSeq\" ASC`,\n );\n const result = await db.query<PendingBatchRow>(query.sql, query.params as unknown[]);\n\n return result.rows;\n}\n\nasync function flushBatch(\n db: MutationDb,\n tableContexts: Record<string, TableContext>,\n batchWriteUrl: string,\n maxAttempts: number,\n batchSize: number,\n tableFilter?: string,\n getAuthToken?: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): Promise<FlushBatchResult> {\n const contexts = filterContexts(tableContexts, tableFilter);\n const nowUs = nowMicroseconds();\n const quarantinedMutationIds: string[] = [];\n const conflictedMutationIds: string[] = [];\n\n // Collect send-eligible mutations across all target tables.\n const pendingRows = await readPendingBatchRows(db, contexts, nowUs, batchSize);\n const pending: PreparedBatchRow[] = [];\n const pendingByTable = new Map<string, PreparedBatchRow[]>();\n\n for (const row of pendingRows) {\n const context = tableContexts[row.tableKey];\n\n if (!context) {\n continue;\n }\n\n const entityKey = JSON.parse(row.entityKeyJson) as Record<string, string>;\n const rawPayload = JSON.parse(row.payloadJson) as Record<string, unknown>;\n const preparedRow: PreparedBatchRow = {\n ...row,\n context,\n entityKey,\n envelopePayload:\n row.mutationKind === \"delete\"\n ? entityKey\n : toSqlColumnPayload(\n context,\n stripManagedFields(\n context,\n (rawPayload[\"value\"] ?? rawPayload[\"patch\"] ?? rawPayload) as Record<string, unknown>,\n row.mutationKind as \"create\" | \"update\",\n ),\n ),\n sqlTableName: context.entry.shape?.tableName ?? context.key,\n };\n\n pending.push(preparedRow);\n\n const existingTableRows = pendingByTable.get(context.key);\n\n if (existingTableRows) {\n existingTableRows.push(preparedRow);\n } else {\n pendingByTable.set(context.key, [preparedRow]);\n }\n }\n\n if (pending.length === 0) {\n // If a write just enqueued and requested a pass, but this flush sees nothing, the pass raced the\n // journal commit (or everything is already in-flight/backed-off) — the write then waits for a\n // later pass. Worth seeing explicitly when chasing flush latency.\n syncDebug(\"flushBatch: no send-eligible mutations this pass\");\n return {\n processedCount: 0,\n affectedContexts: [],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n syncDebug(\"flushBatch sending to board-write\", { count: pending.length });\n\n // Mark all as sending.\n const sentAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => ({\n mutationId: row.mutationId,\n status: \"sending\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: sentAtUs,\n sentAtUs,\n replaceSentAtUs: true,\n // Persist the resolved Base server version (ADR-0015) so a chained write's flush-resolved\n // base is durable and matches exactly what the envelope carries to the server.\n baseServerVersion: row.baseServerVersion,\n replaceBaseServerVersion: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: null,\n conflictReason: null,\n })),\n );\n }\n\n const mutations = pending.map((row) => {\n return {\n tableName: row.sqlTableName,\n entityKey: row.entityKey,\n mutationId: row.mutationId,\n mutationSeq: row.mutationSeq,\n kind: row.mutationKind as \"create\" | \"update\" | \"delete\",\n payload: row.envelopePayload,\n clientTimestampUs: sentAtUs,\n // ADR-0015: carry the resolved Base server version so the applier can detect a stale write.\n // Omitted for a create / a table that predates the policy (null) — then no stale check runs.\n ...(row.baseServerVersion != null ? { baseServerVersion: row.baseServerVersion } : {}),\n };\n });\n\n let responseOk = false;\n let acksByMutationId: Map<string, BatchMutationAck[\"acks\"][number]> = new Map();\n const batchMutationUrl = resolveBatchMutationUrl(batchWriteUrl);\n\n try {\n // Resolve the auth token and the network round-trip separately: in the board, `getAuthToken` calls\n // `supabase.auth.getSession()` per send, which can itself stall (token refresh) and would otherwise\n // be invisibly folded into \"the write was slow\".\n const authStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n const authToken = await getAuthToken?.();\n const fetchStart = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write auth token resolved\", { ms: Math.round(fetchStart - authStart) });\n\n let response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(authToken, requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n\n if ([401, 403].includes(response.status) && getAuthToken) {\n response = await fetch(batchMutationUrl, {\n method: \"POST\",\n headers: buildRequestHeaders(await getAuthToken(), requestHeaders),\n body: jsonStringifyPayload({ mutations }),\n });\n }\n\n const fetchEnd = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n syncDebug(\"board-write responded\", { status: response.status, ms: Math.round(fetchEnd - fetchStart) });\n\n if (response.ok) {\n const responseJson = (await response.json()) as BatchMutationAck;\n responseOk = true;\n acksByMutationId = new Map(responseJson.acks.map((ack) => [ack.mutationId, ack]));\n syncDebug(\"board-write acks\", {\n acks: responseJson.acks.map((ack) => `${ack.mutationId.slice(0, 8)}:${ack.status}`),\n });\n } else {\n const text = await response.text();\n throw new MutationRequestError(\n text.length > 0 ? text : `Bulk write responded with ${response.status}`,\n response.status,\n parseBatchRejections(text),\n );\n }\n } catch (error) {\n const failedAtUs = nowMicroseconds();\n const httpStatus = error instanceof MutationRequestError ? error.status : null;\n const errorMessage = error instanceof Error ? error.message : \"Unknown batch write failure\";\n // The server attributed the failure to specific mutations (a structural validation\n // rejection of an atomic batch). When present, we quarantine exactly those and leave the\n // innocent siblings immediately retryable; absent (transport / 5xx / auth / malformed\n // envelope), the whole batch stays retryable under the shared attempt cap.\n const rejectionById =\n error instanceof MutationRequestError && error.rejections\n ? new Map(error.rejections.map((rejection) => [rejection.mutationId, rejection]))\n : null;\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const attemptCount = row.attemptCount + 1;\n\n if (rejectionById) {\n const rejection = rejectionById.get(row.mutationId);\n\n if (rejection) {\n // Named as the cause: terminal quarantine (it will never succeed unchanged).\n quarantinedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"quarantined\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: rejection.reason,\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: rejection.reason,\n };\n }\n\n // Innocent sibling: nothing was applied (atomic batch), so make it immediately\n // retryable — no backoff (the fault was the now-quarantined mutation, not\n // congestion) — and the next flush proceeds without the poison.\n return {\n mutationId: row.mutationId,\n status: \"failed\" as const,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: \"Batch rejected due to a sibling mutation; retrying without it\",\n nextRetryAtUs: null,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }\n\n // Unattributed batch-level failure: stays retryable with jittered backoff; only the\n // hard attempt cap escalates to terminal quarantined. A structural 4xx is NOT\n // quarantined here (a stray 404/413/malformed envelope would otherwise permanently\n // kill unrelated valid writes).\n const outcome = resolveBatchFailureOutcome(attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: errorMessage,\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n if (!responseOk) {\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n }\n\n // Apply per-mutation ack results.\n const ackedAtUs = nowMicroseconds();\n const failedAtUs = nowMicroseconds();\n\n for (const rows of pendingByTable.values()) {\n await applyMutationStatusUpdates(\n db,\n rows[0]!.context,\n rows.map((row) => {\n const ack = acksByMutationId.get(row.mutationId);\n\n if (ack && ack.status === \"conflicted\") {\n // ADR-0015: a stale write the reject-if-stale policy declined. Move to the terminal\n // `conflicted` status — NOT a failure (never retried as-is, the base is still stale) — and\n // KEEP the optimistic Overlay (reconcile only clears acked rows, so the user's edit stays\n // visible). The server's current Server version rides on the journal row for the diff UI.\n conflictedMutationIds.push(row.mutationId);\n return {\n mutationId: row.mutationId,\n status: \"conflicted\" as const,\n attemptCount: row.attemptCount + 1,\n updatedAtUs: failedAtUs,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n nextRetryAtUs: null,\n lastHttpStatus: ack.httpStatus ?? 409,\n conflictReason: ack.conflictReason ?? \"Stale write rejected (reject-if-stale)\",\n };\n }\n\n if (!ack || ack.status !== \"acked\") {\n const attemptCount = row.attemptCount + 1;\n const httpStatus = ack?.httpStatus ?? null;\n const outcome = resolveFailureOutcome(httpStatus, attemptCount, maxAttempts, failedAtUs);\n\n if (outcome.status === \"quarantined\") {\n quarantinedMutationIds.push(row.mutationId);\n }\n\n return {\n mutationId: row.mutationId,\n status: outcome.status,\n attemptCount,\n updatedAtUs: failedAtUs,\n lastError: ack?.conflictReason ?? \"Batch mutation not acknowledged\",\n nextRetryAtUs: outcome.nextRetryAtUs,\n lastHttpStatus: httpStatus,\n conflictReason: ack?.conflictReason ?? null,\n };\n }\n\n if (row.mutationKind === \"delete\") {\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 204,\n conflictReason: null,\n };\n }\n\n return {\n mutationId: row.mutationId,\n status: \"acked\",\n attemptCount: row.attemptCount + 1,\n updatedAtUs: ackedAtUs,\n ackedAtUs,\n replaceAckedAtUs: true,\n serverUpdatedAtUs: ack.serverUpdatedAtUs ?? null,\n replaceServerUpdatedAtUs: true,\n lastError: null,\n nextRetryAtUs: null,\n lastHttpStatus: 200,\n conflictReason: null,\n };\n }),\n );\n }\n\n return {\n processedCount: pending.length,\n affectedContexts: [...new Set(pending.map((row) => row.context))],\n quarantinedMutationIds,\n conflictedMutationIds,\n };\n}\n\n/**\n * Resolve a flush failure into the durable journal outcome (ADR-0006). A structural\n * rejection ({@link classifyFailureStatus}) or hitting the hard attempt cap ends the\n * retry loop with a terminal `quarantined` (no `next_retry_at_us`); otherwise the\n * mutation stays `failed` with a jittered backoff (ADR-0005 congestion policy).\n */\nfunction resolveFailureOutcome(\n httpStatus: number | null,\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (classifyFailureStatus(httpStatus) === \"quarantined\" || attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\n/**\n * Resolve a *batch-level* failure — the whole POST failed (transport error, 5xx, auth, or a\n * non-2xx the server did not attribute to a specific mutation). Unlike a per-mutation ack\n * rejection, the fault cannot be pinned on any one mutation, so a structural 4xx must NOT\n * quarantine the batch (a stray 404/413/malformed envelope would permanently kill unrelated\n * valid offline writes). These failures stay retryable `failed` with jittered backoff; only\n * the hard attempt cap escalates to terminal `quarantined`.\n */\nfunction resolveBatchFailureOutcome(\n attemptCount: number,\n maxAttempts: number,\n failedAtUs: string,\n): { status: \"failed\" | \"quarantined\"; nextRetryAtUs: string | null } {\n if (attemptCount >= maxAttempts) {\n return { status: \"quarantined\", nextRetryAtUs: null };\n }\n\n return { status: \"failed\", nextRetryAtUs: computeNextRetryAtUs(failedAtUs, attemptCount) };\n}\n\nfunction resolveBatchMutationUrl(batchWriteUrl: string): string {\n const trimmed = batchWriteUrl.replace(/\\/+$/, \"\");\n\n if (trimmed.endsWith(\"/mutations\")) {\n return trimmed;\n }\n\n return `${trimmed}/mutations`;\n}\n\n/** The authoritative (pessimistic) write endpoint (ADR-0022): the batch URL with `/unit` appended. */\nfunction resolveAuthoritativeMutationUrl(batchWriteUrl: string): string {\n return `${resolveBatchMutationUrl(batchWriteUrl)}/unit`;\n}\n\nfunction stripManagedFields(\n context: TableContext,\n payload: Record<string, unknown>,\n operation: \"create\" | \"update\",\n): Record<string, unknown> {\n const managedColumns = new Set<string>();\n\n for (const mf of context.entry.governance?.managedFields ?? []) {\n if (mf.applyOn.includes(operation)) {\n managedColumns.add(mf.column);\n }\n }\n\n if (managedColumns.size === 0) return payload;\n\n return Object.fromEntries(Object.entries(payload).filter(([key]) => !managedColumns.has(key)));\n}\n\nfunction toSqlColumnPayload(context: TableContext, payload: Record<string, unknown>): Record<string, unknown> {\n const normalized: Record<string, unknown> = {};\n\n for (const { propertyKey, column } of context.columns) {\n const columnName = column.name;\n\n if (Object.prototype.hasOwnProperty.call(payload, columnName)) {\n normalized[columnName] = payload[columnName];\n continue;\n }\n\n if (Object.prototype.hasOwnProperty.call(payload, propertyKey)) {\n normalized[columnName] = payload[propertyKey];\n }\n }\n\n return normalized;\n}\n\n/**\n * Discard a terminal-state entity: clear its journal rows in the given terminal status\n * (`conflicted` — ADR-0015; or `quarantined` — ADR-0006) and its kept optimistic Overlay row, so the\n * Read model falls back to the synced (server) value. The overlay is removed only when no OTHER journal\n * row still owes the entity (a pending/sending/failed/acked write), mirroring reconcileTable's\n * overlay-clear guard — so a discard never strips an overlay another un-resolved write still depends\n * on. Both public discards (`discardConflict`, `discardQuarantined`) are this one body parameterized by\n * the terminal status they retire; owning its own transaction (like reconcileTable), it is not wrapped.\n */\nasync function discardTerminalEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n terminalStatus: \"conflicted\" | \"quarantined\",\n) {\n await db.exec(\"BEGIN\");\n\n try {\n const journal = context.tables.journal;\n const clearQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, terminalStatus), eq(journal.entityKeyJson, entityKeyJson)))\n .toSQL();\n await db.query(clearQuery.sql, clearQuery.params as unknown[]);\n\n // Clear the kept overlay only when no journal row still owes this entity — so a discard never\n // strips an overlay another un-resolved write (e.g. a resolution already enqueued) depends on.\n const overlayQuery = buildOverlayDiscardQuery(context, entityKey, entityKeyJson);\n await db.query(overlayQuery.sql, overlayQuery.params as unknown[]);\n\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\n/**\n * The shared overlay-discard statement: delete the entity's overlay row unless a journal row still\n * owes the entity — `owedStatuses` narrows which journal rows count as \"owed\" (all of them for a\n * conflict discard; only the un-sent pending/sending/failed set for a settled-unit discard).\n */\nfunction buildOverlayDiscardQuery(\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n owedStatuses?: MutationStatus[],\n) {\n const overlay = context.tables.overlay;\n const journal = context.tables.journal;\n const owed = queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n owedStatuses\n ? and(eq(journal.entityKeyJson, entityKeyJson), inArray(journal.status, owedStatuses))\n : eq(journal.entityKeyJson, entityKeyJson),\n );\n\n return queryBuilder\n .delete(overlay)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, entityKey[columnName]),\n ),\n notExists(owed),\n ),\n )\n .toSQL();\n}\n\n/**\n * Auto-discard the optimistic overlay for an entity whose pessimistic write-unit the authoritative endpoint\n * `rejected` (ADR-0022 §4). Unlike {@link discardTerminalEntity} this KEEPS the terminal `rejected` journal\n * row (for diagnostics + `onReject`); it only clears the overlay, and only when no still-owed\n * (`pending`/`sending`/`failed`) journal row depends on it — so a later un-sent write never loses its overlay.\n */\nasync function discardOverlayForSettledEntity(\n db: MutationDb,\n context: TableContext,\n entityKey: Record<string, string>,\n entityKeyJson: string,\n) {\n const query = buildOverlayDiscardQuery(context, entityKey, entityKeyJson, [\"pending\", \"sending\", \"failed\"]);\n await db.query(query.sql, query.params as unknown[]);\n}\n\nasync function reconcileTable(db: MutationDb, context: TableContext) {\n // Idle fast-path. Reconcile only retires/clears journal rows in a terminal-clearable state — 'acked'\n // (clear the overlay once the echo lands) or 'conflicted' (retire once a later write resolved it). When\n // none exist — the steady state of an idle entity set — all three statements below are no-ops, so skip\n // the whole transaction. This matters because the convergence driver runs reconcile for EVERY writable\n // table on its interval (default 1.5s), and each CTE pays full PGlite plan+execute cost even against an\n // empty journal: left unguarded it is the dominant idle-CPU cost. The real-time cleanup path is the\n // <table>_reconcile_on_sync trigger; this bulk pass is a fallback, so skipping it when there is nothing\n // to clear changes no outcome. The guard is a single existence probe over the (small, usually empty)\n // journal.\n const journal = context.tables.journal;\n const overlay = context.tables.overlay;\n const synced = context.tables.synced;\n // This is the idle-CPU hot statement (it runs for every writable table on every convergence\n // tick), so the rendered text+params are memoized per context — each tick pays only a plain\n // `db.query` of a cached string, and it stays OUTSIDE any transaction (no BEGIN on the idle path).\n let idleProbe = context.reconcileIdleProbe;\n if (!idleProbe) {\n const probeQuery = queryDialect.sqlToQuery(\n sql`SELECT ${exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(inArray(journal.status, [\"acked\", \"conflicted\"])),\n )} AS \"hasWork\"`,\n );\n idleProbe = { sql: probeQuery.sql, params: probeQuery.params as unknown[] };\n context.reconcileIdleProbe = idleProbe;\n }\n const work = await db.query<{ hasWork: boolean }>(idleProbe.sql, idleProbe.params);\n if (work.rows[0]?.hasWork !== true) {\n return;\n }\n\n // The Convergence barrier (ADR-0010) gates the acked-row clearing below; the synced-table trigger\n // handles real-time cleanup, and this is the bulk recovery/fallback path that runs after every flush.\n await db.exec(\"BEGIN\");\n\n try {\n // ADR-0015: retire a terminal `conflicted` row once the user has RESOLVED it — i.e. a LATER write\n // on the same entity has been acked (resolution is an ordinary new mutation). Without this, the old\n // conflicted row lingers forever: `<table>_sync_state.conflict_state` keeps surfacing the resolved\n // conflict and `diagnostics().conflictedCount` never drops. Run before the acked-clear below so the\n // resolving row is still present to supersede it. (`discardConflict` is the explicit throw-away path.)\n // Drizzle DELETE has no USING; the resolver leg is the equivalent EXISTS semi-join.\n const resolver = alias(journal, \"resolver\");\n const retireQuery = queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"conflicted\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(resolver)\n .where(\n and(\n eq(resolver.entityKeyJson, journal.entityKeyJson),\n gt(resolver.mutationSeq, journal.mutationSeq),\n eq(resolver.status, \"acked\"),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(retireQuery.sql, retireQuery.params as unknown[]);\n\n // ADR-0022 addendum — retire an acked `pessimistic-blind` row with NO echo barrier. A blind update's\n // write target is excluded from this actor's read shape, so no synced echo will ever land for it and no\n // overlay was ever planned: the standard acked-clear below (gated on a synced row reaching the acked\n // version) would keep it forever. Nothing local converges for these rows, so once the authoritative unit\n // acked them there is nothing left to do but drop the journal row. Crash-safe: any later reconcile tick\n // clears a blind row the foreground flushUnit didn't survive to reconcile.\n const blindRetireQuery = queryBuilder\n .delete(journal)\n .where(and(eq(journal.status, \"acked\"), eq(journal.writeMode, \"pessimistic-blind\")))\n .toSQL();\n await db.query(blindRetireQuery.sql, blindRetireQuery.params as unknown[]);\n\n // Clear acknowledged non-delete mutations + matching overlays. ADR-0010: gated by the\n // Convergence barrier (same predicate as the trigger) — the acked write clears only once the\n // synced echo's Server version has reached its acked version. Joining the synced table makes\n // the comparison possible (and means an un-synced acked write is held until its echo lands).\n // Drizzle authoring: DELETE..USING becomes the equivalent EXISTS semi-join, chained through a\n // data-modifying CTE (both sub-statements see the same statement-start snapshot, exactly like\n // the USING form). The barrier predicate stays the shared contracts helper (single authority\n // with the trigger); it renders against the tables' own names, which is how drizzle references\n // their columns here (no aliases on a DELETE target).\n const barrier = sql.raw(\n buildOverlayResolutionBarrier(context.entry, {\n journalAlias: quoteIdentifier(getTableConfig(journal).name),\n syncedAlias: quoteIdentifier(getTableConfig(synced).name),\n }),\n );\n const clearedJournal = queryBuilder.$with(\"cleared_journal\").as(\n queryBuilder\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n isNotNull(journal.serverUpdatedAtUs),\n ne(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(synced)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n barrier,\n ),\n ),\n ),\n ),\n )\n .returning(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n ),\n );\n const clearedJournalColumns = clearedJournal as unknown as Record<string, PgColumn>;\n const ackedClearQuery = queryBuilder\n .with(clearedJournal)\n .delete(overlay)\n .where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearedJournal)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearedJournalColumns[columnName]!),\n ),\n notExists(\n queryBuilder\n .select({ one: sql`1` })\n .from(journal)\n .where(\n and(\n eq(journal.entityKeyJson, clearedJournalColumns[\"entity_key_json\"]!),\n inArray(journal.status, [\"pending\", \"sending\", \"failed\"]),\n ),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(ackedClearQuery.sql, ackedClearQuery.params as unknown[]);\n\n // Clear acknowledged delete mutations where synced row is absent\n // Single compound CTE — PGlite does not support multi-statement query().\n const clearableEntities = queryBuilder.$with(\"clearable_entities\").as(\n queryBuilder\n .selectDistinct(\n Object.fromEntries([\n [\"entity_key_json\", journal.entityKeyJson],\n ...context.pkColumnNames.map((columnName) => [columnName, journal[columnName]!]),\n ]),\n )\n .from(journal)\n .leftJoin(\n synced,\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.syncedPkColumns[index]!, journal[columnName]!),\n ),\n ),\n )\n .where(\n and(eq(journal.status, \"acked\"), eq(journal.mutationKind, \"delete\"), isNull(context.syncedPkColumns[0]!)),\n ),\n );\n const clearableEntityColumns = clearableEntities as unknown as Record<string, PgColumn>;\n const deletedOverlay = queryBuilder.$with(\"deleted_overlay\").as(\n queryBuilder.delete(overlay).where(\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName, index) =>\n eq(context.overlayPkColumns[index]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n );\n const deleteClearQuery = queryBuilder\n .with(clearableEntities, deletedOverlay)\n .delete(journal)\n .where(\n and(\n eq(journal.status, \"acked\"),\n eq(journal.mutationKind, \"delete\"),\n exists(\n queryBuilder\n .select({ one: sql`1` })\n .from(clearableEntities)\n .where(\n and(\n ...context.pkColumnNames.map((columnName) =>\n eq(journal[columnName]!, clearableEntityColumns[columnName]!),\n ),\n ),\n ),\n ),\n ),\n )\n .toSQL();\n await db.query(deleteClearQuery.sql, deleteClearQuery.params as unknown[]);\n await db.exec(\"COMMIT\");\n } catch (error) {\n await db.exec(\"ROLLBACK\");\n throw error;\n }\n}\n\nfunction buildRequestHeaders(bearerToken?: string, requestHeaders?: Record<string, string>): Record<string, string> {\n // Static headers first so the toolkit-owned Content-Type/Authorization always win.\n return {\n ...(requestHeaders ?? {}),\n \"Content-Type\": \"application/json\",\n ...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),\n };\n}\n\nasync function applyMutationStatusUpdates(db: MutationDb, context: TableContext, updates: MutationStatusUpdate[]) {\n if (updates.length === 0) {\n return;\n }\n\n // Tier ②: `update().from(<VALUES>)`. Every value is a bound param with the same cast as before;\n // the `updates` alias and its column list are fixed by this function (not derived from data), so\n // the alias-qualified references in SET/WHERE are fixed template text, while the journal side of\n // each CASE interpolates the column objects.\n const journal = context.tables.journal;\n const tuples = updates.map(\n (update) =>\n sql`(${update.mutationId}, ${update.status}, ${update.attemptCount}::int, ${update.updatedAtUs}::bigint, ${\n update.sentAtUs ?? null\n }::bigint, ${update.replaceSentAtUs ?? false}::boolean, ${update.ackedAtUs ?? null}::bigint, ${\n update.replaceAckedAtUs ?? false\n }::boolean, ${update.serverUpdatedAtUs ?? null}::bigint, ${update.replaceServerUpdatedAtUs ?? false}::boolean, ${\n update.baseServerVersion ?? null\n }::bigint, ${update.replaceBaseServerVersion ?? false}::boolean, ${update.lastError ?? null}, ${\n update.nextRetryAtUs ?? null\n }::bigint, ${update.lastHttpStatus ?? null}::int, ${update.conflictReason ?? null})`,\n );\n const updatesTable = sql`(VALUES ${sql.join(\n tuples,\n sql`, `,\n )}) AS updates (mutation_id, status, attempt_count, updated_at_us, sent_at_us, replace_sent_at_us, acked_at_us, replace_acked_at_us, server_updated_at_us, replace_server_updated_at_us, base_server_version, replace_base_server_version, last_error, next_retry_at_us, last_http_status, conflict_reason)`;\n\n const query = queryBuilder\n .update(journal)\n .set({\n status: sql`updates.status`,\n attemptCount: sql`updates.attempt_count`,\n updatedAtUs: sql`updates.updated_at_us::bigint`,\n sentAtUs: sql`CASE WHEN updates.replace_sent_at_us THEN updates.sent_at_us::bigint ELSE ${journal.sentAtUs} END`,\n ackedAtUs: sql`CASE WHEN updates.replace_acked_at_us THEN updates.acked_at_us::bigint ELSE ${journal.ackedAtUs} END`,\n serverUpdatedAtUs: sql`CASE WHEN updates.replace_server_updated_at_us THEN updates.server_updated_at_us::bigint ELSE ${journal.serverUpdatedAtUs} END`,\n baseServerVersion: sql`CASE WHEN updates.replace_base_server_version THEN updates.base_server_version::bigint ELSE ${journal.baseServerVersion} END`,\n lastError: sql`updates.last_error`,\n nextRetryAtUs: sql`updates.next_retry_at_us::bigint`,\n lastHttpStatus: sql`updates.last_http_status`,\n conflictReason: sql`updates.conflict_reason`,\n })\n .from(updatesTable)\n .where(eq(journal.mutationId, sql`updates.mutation_id::uuid`))\n .toSQL();\n await db.query(query.sql, query.params as unknown[]);\n}\n\nfunction qualifyLocalIdentifier(schemaName: string, tableName: string) {\n if (schemaName === \"public\") {\n // Quote-when-needed: a reserved-word or mixed-case table name (e.g. `group`)\n // MUST be quoted or the generated SQL fails to parse (ADR-0004). Normal names\n // stay bare, so existing generated SQL is unchanged.\n return maybeQuoteIdentifier(tableName);\n }\n\n return `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}`;\n}\n\nfunction buildJournalSequenceName(journalTable: string) {\n return `${journalTable}_mutation_seq`;\n}\n\nfunction hasProperty(context: TableContext, propertyKey: string) {\n return context.columns.some((column) => column.propertyKey === propertyKey);\n}\n\nfunction ensureRecord(value: unknown) {\n if (!isRecord(value)) {\n throw new Error(\"Mutation runtime expected a record payload\");\n }\n\n return value;\n}\n\nfunction extractRecordFromState(context: TableContext, state: CurrentRecordStateRow | BatchCurrentRecordStateRow) {\n return Object.fromEntries(context.columns.map(({ propertyKey }) => [propertyKey, state[propertyKey] ?? null]));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nclass MutationRequestError extends Error {\n readonly status: number;\n /** Per-mutation attribution the server returned for a structural rejection, or null. */\n readonly rejections: MutationRejection[] | null;\n\n constructor(message: string, status: number, rejections: MutationRejection[] | null = null) {\n super(message);\n this.name = \"MutationRequestError\";\n this.status = status;\n this.rejections = rejections;\n }\n}\n\n/**\n * Extract per-mutation attribution from a non-2xx batch-write body. The server names the\n * offending mutations on a structural (validation) rejection; an absent, non-JSON, or\n * empty-`rejections` body yields null, so the failure is treated as non-attributable\n * (whole batch stays retryable).\n */\nfunction parseBatchRejections(body: string): MutationRejection[] | null {\n if (body.length === 0) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return null;\n }\n\n const result = batchMutationErrorSchema.safeParse(parsed);\n const rejections = result.success ? result.data.rejections : undefined;\n return rejections && rejections.length > 0 ? rejections : null;\n}\n",
118
+ "import type { ExternalHeadersRecord, ShapeStreamOptions } from \"@electric-sql/client\";\n\n/** The per-shape error handler shape Electric expects (`ShapeStreamOptions.onError`). */\ntype ShapeStreamErrorHandler = NonNullable<ShapeStreamOptions[\"onError\"]>;\n\n/**\n * Read-path identity (ADR-0013). The two ingress points must share **one** token lifecycle: the\n * write path already calls `getAuthToken` fresh on every flush, so the read path must too — never\n * freezing a JWT at boot, which wedges a long-lived offline-first session the instant the token\n * expires.\n *\n * `buildAuthShapeHeaders` returns the read-path `Authorization` header as an **async function**.\n * Electric resolves header-value functions on every request *and every retry*\n * (`ExternalHeadersRecord` allows `string | (() => string | Promise<string>)`), so each shape fetch\n * presents a fresh token. This is the client mirror of ADR-0003's server-side one-identity decision.\n *\n * The provider contract (documented in `docs/architecture.md`): `getAuthToken` is now called per\n * request by both paths and **must be refresh-deduping** — return the cached valid token and refresh\n * single-flight, so an N-shape consistency group does not trigger N refreshes.\n */\n/**\n * Build the read-path shape headers: the optional async `Authorization` (per ADR-0013) **plus** any\n * caller-supplied static `requestHeaders`. The static headers are spread first so the toolkit-owned\n * `Authorization` always wins; they exist for deployment-gateway credentials the toolkit is otherwise\n * agnostic about — e.g. a Supabase `apikey` header the platform function gateway expects. Emitted\n * whenever *either* a token provider or static headers are present, so a credential-only consumer\n * (no per-request token) still sends its headers.\n */\nexport function buildShapeHeaders(input: {\n getAuthToken?: () => Promise<string | undefined>;\n requestHeaders?: Record<string, string>;\n}): ExternalHeadersRecord {\n const headers: ExternalHeadersRecord = { ...(input.requestHeaders ?? {}) };\n const getAuthToken = input.getAuthToken;\n if (getAuthToken) {\n // Resolved per request: a fresh token each time, never one captured at boot. An absent token\n // yields an empty value (unauthenticated) rather than the literal string `Bearer undefined`.\n headers[\"Authorization\"] = async () => {\n const token = await getAuthToken();\n return token ? `Bearer ${token}` : \"\";\n };\n }\n return headers;\n}\n\n/** Token-only convenience over {@link buildShapeHeaders}; retained for callers that pass a provider. */\nexport function buildAuthShapeHeaders(\n getAuthToken: () => Promise<string | undefined>,\n requestHeaders?: Record<string, string>,\n): ExternalHeadersRecord {\n return buildShapeHeaders({ getAuthToken, ...(requestHeaders ? { requestHeaders } : {}) });\n}\n\n/** HTTP statuses that mean \"the credential is the problem\" — re-auth, never give up (ADR-0013). */\nconst AUTH_ERROR_STATUSES = new Set([401, 403]);\n\n/** Read the duck-typed numeric `status` off an Electric `FetchError`, or `undefined` for a plain error. */\nfunction readErrorStatus(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || !(\"status\" in error)) {\n return undefined;\n }\n const status = (error as { status: unknown }).status;\n return typeof status === \"number\" ? status : undefined;\n}\n\n/**\n * True when the error is an auth failure (Electric's `FetchError` with a 401/403 `status`). We read\n * the documented `status` field rather than `instanceof FetchError`: the experimental and client\n * packages can resolve to *different* `@electric-sql/client` copies, so an `instanceof` against one\n * copy can miss a `FetchError` thrown from the other. A duck-typed numeric `status` is robust and\n * carries no false positives — a plain network/`Error` has no numeric `status`.\n */\nfunction isAuthError(error: unknown): boolean {\n const status = readErrorStatus(error);\n return status !== undefined && AUTH_ERROR_STATUSES.has(status);\n}\n\n/**\n * Whether a non-auth read-stream error is worth retrying (#4): a transient transport fault — a 5xx,\n * a 429 rate-limit, or a network error with no HTTP status. A genuine non-auth 4xx (400/404/409/…)\n * is structural: retrying re-fails, so we stop. (401/403 are handled separately as auth.)\n */\nfunction isRetryableStreamError(error: unknown): boolean {\n const status = readErrorStatus(error);\n if (status === undefined) {\n return true; // network/transport error — retry with Electric's backoff\n }\n return status >= 500 || status === 429;\n}\n\n/**\n * The per-shape `ShapeStreamOptions.onError` handler for the read path. It is the only place that can\n * request a retry (the `MultiShapeStream.subscribe` `onError` is notification-only), so it owns BOTH\n * read-path identity (ADR-0013) and read-stream error surfacing (#4):\n *\n * - **auth (401/403)** → `onAuthError` + return `{}` (retry): Electric re-issues the request,\n * re-resolving the async Authorization header ({@link buildAuthShapeHeaders}) for a *fresh* token.\n * Never return `void` here — that stops the stream permanently, wrong for offline-first: a dead\n * session must keep retrying (jittered backoff bounds the cost) so sync resumes the instant re-auth\n * makes the token valid again. The optional `onAuthError` surfaces a distinct \"re-login\" status.\n * - **any other error** → `onReadStreamError` (so the runtime can move to a `degraded` status instead\n * of silently believing the read path is live), then retry transient faults ({@link\n * isRetryableStreamError}: 5xx/429/network → `{}`) or stop a structural 4xx (return `undefined`). A\n * later successful fetch (`onSyncActivity`) clears the degraded status back to live.\n */\nexport function createShapeErrorHandler(\n options: { onAuthError?: () => void; onReadStreamError?: (error: Error) => void } = {},\n): ShapeStreamErrorHandler {\n return (error: Error) => {\n if (isAuthError(error)) {\n options.onAuthError?.();\n return {}; // retry → re-resolves the async Authorization header for a fresh token\n }\n options.onReadStreamError?.(error);\n return isRetryableStreamError(error) ? {} : undefined;\n };\n}\n",
119
+ "// Started life as a copy of @electric-sql/pglite-sync (Apache-2.0, © ElectricSQL — see NOTICE).\n// Fully internalized (ADR-0009); upstream compatibility is an explicit anti-goal (ADR-0028) — evolve freely.\nimport type { EventMessage, MovePattern, Row } from \"@electric-sql/client\";\nimport { isChangeMessage, isControlMessage } from \"@electric-sql/client\";\nimport type { ChangeMessage, ShapeStreamOptions } from \"@electric-sql/client\";\nimport { MultiShapeStream } from \"@electric-sql/experimental\";\nimport type { PGliteInterface } from \"@electric-sql/pglite\";\nimport { sql } from \"drizzle-orm\";\nimport { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport { type ApplyStrategy, classifyTableApplyStrategy } from \"@pgxsinkit/contracts\";\n\nimport { instrumentShapeFetch, syncDebug } from \"../debug\";\nimport { type ApplyTarget, resolveApplyTarget } from \"../local-tables\";\nimport { computeRetryDelayMs } from \"../mutation\";\nimport {\n applyBulkDeletesToTable,\n applyBulkUpdatesToTable,\n applyInsertsToTable,\n applyMessagesToTableWithCopy,\n applyMessagesToTableWithJson,\n applyUpsertsToTable,\n} from \"./apply\";\nimport { drizzleOverPg } from \"./drizzle-executor\";\nimport {\n NUDGE_HOLD_GRACE_MS,\n NUDGE_MAX_ROUNDS,\n NUDGE_ROUND_GRACE_MS,\n NUDGE_ROUND_WAIT_MS,\n withNudgeBuster,\n} from \"./nudge\";\nimport { foldChangeBatch, ShapeInbox } from \"./shape-inbox\";\nimport {\n deleteSubscriptionState,\n getSubscriptionState,\n migrateSubscriptionMetadataTables,\n type SubscriptionState,\n updateSubscriptionState,\n} from \"./subscription-state\";\nimport {\n addShapeRowTags,\n applyShapeMoveOut,\n applyShapeTagSync,\n assertValidMetadataSchema,\n clearShapeTags,\n DEFAULT_METADATA_SCHEMA,\n shapeTableId,\n} from \"./tags\";\nimport {\n DEFAULT_MAX_COMMIT_RETRIES,\n type ElectricSyncOptions,\n type InitialInsertMethod,\n type InsertChangeMessage,\n type Lsn,\n type SyncShapesToTablesOptions,\n type SyncShapesToTablesResult,\n type SyncShapeToTableOptions,\n type SyncShapeToTableResult,\n} from \"./types\";\n\nexport * from \"./types\";\n\n/**\n * Replication-stream headers Electric attaches to change messages but does not\n * declare on its `Header` type: `lsn` orders changes within the stream and\n * `last` marks the final change of an LSN. Single choke point for these\n * protocol assumptions.\n */\n/**\n * Maps the statically-resolved {@link ApplyStrategy} (ADR-0009 decision 3) onto the engine's\n * initial-backfill apply path. Undefined (no registry-supplied strategy) defaults to `copy`:\n * the COPY TEXT serializer round-trips every built-in type, so it is the safe no-brainer bootstrap.\n */\nfunction applyStrategyToInsertMethod(strategy: ApplyStrategy | undefined): InitialInsertMethod {\n switch (strategy) {\n case \"json\":\n return \"json\";\n case \"insert\":\n return \"insert\";\n default:\n return \"copy\";\n }\n}\n\nfunction readReplicationHeaders(headers: ChangeMessage[\"headers\"]): { lsn: bigint; isLastOfLsn: boolean } {\n const rawLsn: unknown = headers[\"lsn\"];\n\n return {\n lsn: typeof rawLsn === \"string\" ? BigInt(rawLsn) : BigInt(0),\n isLastOfLsn: headers[\"last\"] === true,\n };\n}\n\n/**\n * Electric's tagged-subquery `EventMessage` (ADR-0023) — `headers.event` is `move-out` | `move-in`,\n * carrying `patterns`. It is neither a change nor a control message, so `@electric-sql/client` exposes\n * no guard; we detect it by the `event` header. `MultiShapeStream` adds `.shape` like every message.\n */\ntype ShapeEventMessage = EventMessage & { shape: string };\n\nfunction isEventMessage(message: unknown): message is ShapeEventMessage {\n return (\n typeof message === \"object\" &&\n message !== null &&\n typeof (message as { headers?: { event?: unknown } }).headers?.event === \"string\"\n );\n}\n\n/**\n * Construct the pgxsinkit sync engine over an ALREADY-created PGlite instance (ADR-0032 S1). The engine\n * is a plain module — not a create-time PGlite extension — so it demands only the minimal surface it\n * actually uses: a {@link PGliteInterface} (it runs its metadata DDL + apply commits through `pg.transaction`\n * / `pg.query` / `pg.exec`; it does NOT touch the `live` extension). It returns the `namespace` object (the\n * local-bookkeeping + shape-sync entry points the client attaches as `pg.electric`) plus an explicit\n * `close()` — the teardown the former extension's `close` hook ran when PGlite closed, now invoked\n * explicitly by the owner at the same moment (see `createSyncClient`'s `stop`/`destroy`).\n */\nexport async function createSyncEngine(pg: PGliteInterface, options?: ElectricSyncOptions) {\n const debug = options?.debug ?? false;\n // pgxsinkit-owned metadata namespace (ADR-0009 decision 6): this is our local bookkeeping (the\n // subscription-state table) and the sync-origin GUC (`<schema>.syncing`), not Electric's — so it\n // lives under our own schema, renamed from the upstream `electric` default.\n const metadataSchema = options?.metadataSchema ?? DEFAULT_METADATA_SCHEMA;\n // The schema name reaches raw GUC + DDL identifier positions below (no quoted-identifier form exists\n // there), so validate it at construction rather than trust caller input in those raw spots.\n assertValidMetadataSchema(metadataSchema);\n const streams: Array<{\n stream: MultiShapeStream<Record<string, Row<unknown>>>;\n aborter: AbortController;\n }> = [];\n\n const getShapeOptions = (shapes: SyncShapesToTablesOptions[\"shapes\"], shapeName: string) => {\n const shape = shapes[shapeName];\n if (!shape) {\n throw new Error(`Missing shape options for ${shapeName}`);\n }\n return shape;\n };\n\n const shapePerTableLock = new Map<string, void>();\n\n // Memoize the metadata DDL as a PROMISE, not a boolean: concurrent eager groups (`shape-sync.ts`\n // starts them with `Promise.all`) both call `initMetadataTables`, and a boolean set BEFORE the async\n // migration completed let the second caller return early and query the metadata tables before the DDL\n // had run. Storing the in-flight promise makes every concurrent caller await the same single migration.\n // Cleared on rejection so a transient DDL failure can be retried by a later start rather than caching a\n // rejected promise forever.\n let initMetadataTablesPromise: Promise<void> | undefined;\n const initMetadataTables = (): Promise<void> => {\n if (!initMetadataTablesPromise) {\n initMetadataTablesPromise = migrateSubscriptionMetadataTables({\n pg,\n metadataSchema,\n }).catch((error: unknown) => {\n initMetadataTablesPromise = undefined;\n throw error;\n });\n }\n return initMetadataTablesPromise;\n };\n\n const syncShapesToTables = async ({\n key,\n registry,\n shapes,\n initialInsertMethod,\n onInitialSync,\n onError,\n onSyncError,\n onSyncActivity,\n dbReady,\n maxCommitRetries = DEFAULT_MAX_COMMIT_RETRIES,\n commitRetryDelayMs = computeRetryDelayMs,\n }: SyncShapesToTablesOptions): Promise<SyncShapesToTablesResult> => {\n let unsubscribed = false;\n // Fresh-store prefetch overlap (ADR-0032 S4): the caller proved the store fresh and handed a `dbReady`\n // gate, so start the streams and buffer their catch-up into the memory inbox NOW — before the local\n // store's schema/journal/reconcile finish — and defer every DB touch (metadata DDL, the first commit)\n // until the gate lifts. Without it, the exact sequential path: init the metadata tables up front.\n const overlap = dbReady != null;\n if (!overlap) {\n await initMetadataTables();\n }\n\n // Resolve each shape's apply target ONCE at subscribe time (ADR-0029 D1/D2): the real projected\n // synced table, its columns, PKs, and model-derived types — the engine's per-message work is then a\n // pure builder over these resolved objects, never a per-message re-derivation or catalog probe.\n const targets = new Map<string, ApplyTarget>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => [\n shapeName,\n resolveApplyTarget(registry, shapeOptions.tableKey),\n ]),\n );\n const getTarget = (shapeName: string): ApplyTarget => {\n const target = targets.get(shapeName);\n if (!target) {\n throw new Error(`Missing apply target for ${shapeName}`);\n }\n return target;\n };\n // The synced table's physical identity — the per-table lock key and the tag-store `shape_table` key.\n const tableIdentity = (target: ApplyTarget) => {\n const { name, schema } = getTableConfig(target.table);\n return shapeTableId(schema, name);\n };\n\n Object.entries(shapes)\n .filter(([, shape]) => !shape.onMustRefetch)\n .forEach(([, shape]) => {\n if (shapePerTableLock.has(shape.tableKey)) {\n throw new Error(\"Already syncing shape for table \" + shape.tableKey);\n }\n shapePerTableLock.set(shape.tableKey);\n });\n\n let subState: SubscriptionState | null = null;\n\n // On the overlap path the store is provably fresh (the `freshStore` gate), so it carries no persisted\n // subscription state — AND its metadata tables do not exist yet (their DDL is deferred to the gate).\n // Skip the read entirely: `subState` stays null, so the group is (correctly) a new subscription.\n if (key !== null && !overlap) {\n subState = await getSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n if (debug && subState) {\n console.log(\"resuming from subscription state\", subState);\n }\n }\n\n const isNewSubscription = subState === null;\n\n // Each shape resolves its own apply method (ADR-0009 decisions 2 + 3 / ADR-0029 D1): an explicit\n // per-shape `initialInsertMethod` override wins, else the group-level default, else the registry's\n // build-time classification of the entry. So a consistency group with mixed column profiles applies\n // each table on its correct path.\n const shapeInsertMethod = new Map<string, InitialInsertMethod>(\n Object.entries(shapes).map(([shapeName, shapeOptions]) => {\n // Strategy precedence (ADR-0009 decisions 2+3 / ADR-0029 D1): an explicit per-shape override,\n // then the group-level default, then the registry's build-time classification of the entry.\n const entry = registry[shapeOptions.tableKey]!;\n const method =\n shapeOptions.initialInsertMethod ??\n initialInsertMethod ??\n applyStrategyToInsertMethod(classifyTableApplyStrategy(entry));\n return [shapeName, method];\n }),\n );\n\n // `useInsert` is per-shape, not shared: in a multi-shape group, one shape finishing its bulk\n // backfill must not flip every other shape onto plain `INSERT`. A shape uses its bulk path only\n // on a fresh subscription with a non-`insert` method; a resume starts already in insert mode.\n const useInsert = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [\n shapeName,\n !isNewSubscription || shapeInsertMethod.get(shapeName) === \"insert\",\n ]),\n );\n let onInitialSyncCalled = false;\n\n const maybeSignalInitialSync = () => {\n if (onInitialSync && !onInitialSyncCalled && multiShapeStream.isUpToDate) {\n onInitialSync();\n onInitialSyncCalled = true;\n }\n };\n\n // The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory buffer + complete-LSN frontier for\n // this group's shapes. The engine keeps the commit queue, the apply, and the truncate set.\n const inbox = new ShapeInbox(Object.keys(shapes));\n\n // Live-tail sibling nudge (ADR-0031): a per-shape one-shot cache-buster token. The watchdog (below)\n // sets a token just before nudging a lagging sibling; `withNudgeBuster` (wrapping each shape's\n // fetchClient) consumes it on the sibling's next non-live catch-up so a CDN HIT cannot return the same\n // stale watermark and defeat the nudge. Empty on the steady path → the wrapper is a straight passthrough.\n const nudgeBusters = new Map<string, string>();\n\n const truncateNeeded = new Set<string>();\n // The committed frontier is a *running* variable, advanced after each successful commit — not\n // the boot-time `const` the upstream engine never advanced (which forced redundant empty\n // re-commits). `degraded` latches once commits exhaust their retries (ADR-0009 decision 5).\n let committedLsn: Lsn = subState?.last_lsn ?? BigInt(-1);\n let degraded = false;\n // Single-flight commit queue: at most one commit runs at a time; messages buffered while one\n // is in flight coalesce into the next run (re-armed via `commitRerun`).\n let commitInFlight: Promise<void> | null = null;\n let commitRerun = false;\n\n const aborter = new AbortController();\n Object.values(shapes)\n .filter((shapeOptions) => !!shapeOptions.shape.signal)\n .forEach((shapeOptions) => {\n shapeOptions.shape.signal!.addEventListener(\"abort\", () => aborter.abort(), {\n once: true,\n });\n });\n\n const multiShapeOptions: Record<string, ShapeStreamOptions<Row<unknown>>> = {};\n for (const [shapeName, shapeOptions] of Object.entries(shapes)) {\n const shapeMetadata = subState?.shape_metadata[shapeName];\n const streamOptions: ShapeStreamOptions<Row<unknown>> = {\n ...shapeOptions.shape,\n signal: aborter.signal,\n // Instrument every ShapeStream HTTP request (the read-path long-poll/catch-up) when debug is on;\n // a passthrough otherwise (see instrumentShapeFetch). Wraps any existing fetchClient rather than\n // replacing it, so auth/header injection on the shape's own fetchClient still runs. `withNudgeBuster`\n // is the OUTER wrapper (ADR-0031 live-tail nudge): it stamps the cache-buster onto the URL BEFORE\n // instrumentation runs, so the debug rail logs the busted URL (`BUSTED`) that actually hits the wire.\n fetchClient: withNudgeBuster(instrumentShapeFetch(shapeOptions.shape.fetchClient), nudgeBusters, shapeName),\n };\n\n if (shapeMetadata) {\n streamOptions.offset = shapeMetadata.offset;\n streamOptions.handle = shapeMetadata.handle;\n }\n\n multiShapeOptions[shapeName] = streamOptions;\n }\n\n const multiShapeStream = new MultiShapeStream<Record<string, Row<unknown>>>({\n shapes: multiShapeOptions,\n });\n\n // The commit gate (ADR-0032 S4). Open immediately on the sequential path; held closed on the overlap\n // path until `dbReady` resolves, so NOTHING writes to PGlite before the local schema exists. The inbox\n // is pure memory, so buffering catch-up behind this closed gate is safe — the only DB-bound work\n // (metadata DDL, then commits) waits for the gate.\n let dbGateOpen = !overlap;\n if (overlap) {\n // The streams' network side is starting now (subscribe below triggers the first fetch), overlapping\n // the caller's local boot phases. Name the shapes so the overlap is measurable on the boot rail.\n syncDebug(\"boot shape prefetch start\", { shapes: Object.keys(shapes) });\n }\n\n const getShapeStream = (shapeName: string) => {\n const stream = multiShapeStream.shapes[shapeName];\n if (!stream) {\n throw new Error(`Missing stream for ${shapeName}`);\n }\n return stream;\n };\n\n const insertMethods = {\n json: applyMessagesToTableWithJson,\n copy: applyMessagesToTableWithCopy,\n insert: applyInsertsToTable,\n } as const;\n\n // Apply everything buffered up to `targetLsn` in a single transaction, retrying with jittered\n // backoff on failure. Returns `true` once applied (and advances the running committed frontier);\n // returns `false` without advancing if the engine unsubscribed mid-flight or the commit\n // exhausted its retries (→ `degraded` + `onSyncError`, ADR-0009 decision 5). The drained\n // messages and the truncate snapshot are held across retries so a transient failure loses\n // nothing; the read cache never advances past an unapplied commit.\n const commitUpToLsn = async (targetLsn: Lsn): Promise<boolean> => {\n // PEEK (not drain) the buffered batch: it stays in the inbox until the transaction below actually\n // succeeds, and is only then ACKed (removed). A commit that exhausts its retries (→ `degraded`)\n // therefore HOLDS the drained batch in the buffer instead of losing it (ADR-0009 decision 5) — and\n // `enqueueCommit` refuses to run any newer commit while degraded, so a later LSN can never apply\n // over this held, unapplied batch. Recovery is a restart/refetch: the persisted offset was not\n // advanced, so the held batch re-streams from the same frontier.\n const messagesToCommit = inbox.peekUpTo(targetLsn);\n\n // Record every shape's reset epoch AT PEEK TIME (synchronously with the peeks, before the async\n // transaction). If a must-refetch + re-snapshot bumps a shape's epoch mid-commit, the acks below\n // skip that shape so its post-reset rebuild survives rather than being deleted/spliced away — see\n // ShapeInbox.ackUpTo / ackMoveOuts / ackMoveIns.\n const epochsAtPeek = inbox.snapshotEpochs();\n\n // Capture, per shape, whether it is still accepting snapshot (LSN-0) rows AT PEEK TIME. A shape in\n // snapshot acceptance (post-reset re-snapshot, or a brand-new shape before its first real lsn) can\n // have the SAME snapshot rows double-delivered by the racing recovery fetch loops — possibly across\n // separate commits — so its inserts are applied idempotently (upsert) rather than as plain\n // collision-surfacing inserts. Once a real lsn re-arms the dedup, this is false and the live-tail\n // plain-INSERT invariant (a genuine PK collision must surface, ADR-0014) is back in force.\n const snapshotModeAtPeek = new Map<string, boolean>(\n Object.keys(shapes).map((shapeName) => [shapeName, inbox.acceptsSnapshotRowsFor(shapeName)]),\n );\n\n // Snapshot the truncate set so a retried transaction still truncates; the per-shape flag is\n // cleared only once the commit has succeeded.\n const shapesToTruncate = new Set(truncateNeeded);\n\n // Peek the buffered tagged-subquery move-outs (ADR-0023) the same way: held in the buffer so a\n // retried/degraded commit still has them, ACKed only on success (by the exact peeked count, so a\n // move-out that arrived during a coalescing commit is not dropped).\n const moveOutsToCommit = new Map<string, MovePattern[][]>();\n // Peek the buffered tagged-subquery move-ins (ADR-0024) identically: a move-in snapshot row carries\n // no LSN; it is applied idempotently in the commit transaction and ACKed only on success.\n const moveInsToCommit = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const shapeName of Object.keys(shapes)) {\n const pendingOut = inbox.peekMoveOuts(shapeName);\n if (pendingOut.length > 0) {\n moveOutsToCommit.set(shapeName, pendingOut);\n }\n const pendingIn = inbox.peekMoveIns(shapeName);\n if (pendingIn.length > 0) {\n moveInsToCommit.set(shapeName, pendingIn);\n }\n }\n\n const runCommit = () =>\n pg.transaction(async (tx) => {\n if (debug) {\n console.time(\"commit\");\n }\n\n // Tier ③ (ADR-0028 allow-list): a `SET LOCAL` GUC — the sync-origin `<schema>.syncing` flag\n // the apply trigger reads to distinguish streamed server truth from local writes. GUCs have\n // no tier-①/② builder form; the schema identifier is fixed at engine construction.\n await tx.exec(`SET LOCAL ${metadataSchema}.syncing = true;`);\n\n for (const [shapeName, initialMessages] of messagesToCommit.entries()) {\n const shape = getShapeOptions(shapes, shapeName);\n const target = getTarget(shapeName);\n const shapeMethod = shapeInsertMethod.get(shapeName)!;\n let messages = initialMessages;\n\n // ADR-0023: the shape's tag store key (synced table, schema-qualified).\n const shapeTable = tableIdentity(target);\n\n if (shapesToTruncate.has(shapeName)) {\n if (debug) {\n console.log(\"truncating table\", shapeTable);\n }\n if (shape.onMustRefetch) {\n await shape.onMustRefetch(drizzleOverPg(tx));\n } else {\n // ADR-0029 D4: a must-refetch wipe is engine cache maintenance, not server truth — so it\n // TRUNCATEs (tier ②; `TRUNCATE` has no Drizzle builder, the table object is interpolated)\n // rather than reacting via the per-row reconcile trigger. Correctness rides the reconcile\n // loop; TRUNCATE is O(1) and the re-snapshot inserts still fire the trigger.\n await drizzleOverPg(tx).execute(sql`TRUNCATE ${target.table}`);\n }\n // The re-snapshot rebuilds tags from scratch, so drop this shape's stale tag-set too\n // (ADR-0023 Slice 2: a must-refetch/​rebuild must not leave orphan tags).\n await clearShapeTags({ pg: tx, metadataSchema, shapeTable });\n }\n\n // ADR-0024: this shape's buffered move-in snapshot rows (a row ENTERING the shape). Their\n // tags are UNIONED first (a move-in adds a reason, it must not clear an independent grant's\n // tag) — and a regular change for the same row in this batch then authoritatively replaces\n // below, so union-then-replace converges either way.\n const moveInMessages = moveInsToCommit.get(shapeName) ?? [];\n if (moveInMessages.length > 0) {\n await addShapeRowTags({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: moveInMessages,\n primaryKey: target.primaryKey,\n });\n }\n\n // Maintain the tag-set from the RAW drained batch (ADR-0023) — before the data apply and\n // the move-out eviction, so an add-then-remove within one commit resolves correctly. Uses\n // `initialMessages` (the full batch) since the insert/​fold split below reduces `messages`.\n await applyShapeTagSync({\n pg: tx,\n metadataSchema,\n shapeTable,\n messages: initialMessages,\n primaryKey: target.primaryKey,\n });\n\n // ADR-0024: apply the move-in rows idempotently BEFORE the change fold, so a same-commit\n // update to a just-moved-in row lands on a present row. Upsert (not plain INSERT) because the\n // row may already be present via another grant or be re-delivered on a resume.\n if (moveInMessages.length > 0) {\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: moveInMessages,\n debug,\n });\n }\n\n if (!useInsert.get(shapeName)) {\n const initialInserts: InsertChangeMessage[] = [];\n const remainingMessages: ChangeMessage<Row<unknown>>[] = [];\n let foundNonInsert = false;\n for (const message of messages) {\n if (!foundNonInsert && message.headers.operation === \"insert\") {\n initialInserts.push(message as InsertChangeMessage);\n } else {\n foundNonInsert = true;\n remainingMessages.push(message);\n }\n }\n if (initialInserts.length > 0 && shapeMethod === \"copy\") {\n remainingMessages.unshift(initialInserts.pop()!);\n }\n messages = remainingMessages;\n\n if (initialInserts.length > 0) {\n await insertMethods[shapeMethod]({\n pg: tx,\n target,\n messages: initialInserts,\n debug,\n });\n\n useInsert.set(shapeName, true);\n }\n }\n\n // ADR-0014 Phase 3: fold this shape's drained batch to one net op per PK, then apply\n // three bulk statements in the order DELETE → INSERT → UPDATE. A re-created PK's delete\n // must precede its insert; every other PK lands in exactly one statement, so the rest of\n // the order is irrelevant within the (atomic) commit. The fold collapses same-PK runs, so\n // no bulk statement ever holds two rows for one PK — closing the `UPDATE … FROM` /\n // `json_to_recordset` join hazard (which would use one arbitrary matching row) by\n // construction. This replaces the previous one-SQL-statement-per-row steady-state loop.\n if (messages.length > 0) {\n const folded = foldChangeBatch(messages);\n\n if (folded.deletes.length > 0) {\n await applyBulkDeletesToTable({\n pg: tx,\n target,\n messages: folded.deletes,\n debug,\n });\n }\n if (folded.inserts.length > 0) {\n if (snapshotModeAtPeek.get(shapeName)) {\n // Snapshot-acceptance mode (post-reset re-snapshot / pre-first-lsn): the racing recovery\n // loops can re-deliver these exact snapshot rows, possibly in a later commit after this\n // shape's TRUNCATE flag has been consumed — so apply them idempotently (upsert), the same\n // posture as a move-in, rather than failing the commit on a PK collision.\n await applyUpsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n } else {\n await applyInsertsToTable({\n pg: tx,\n target,\n messages: folded.inserts,\n debug,\n });\n }\n }\n if (folded.updates.length > 0) {\n await applyBulkUpdatesToTable({\n pg: tx,\n target,\n messages: folded.updates,\n debug,\n });\n }\n }\n\n // ADR-0023: after the data + tag state is current, apply this shape's buffered move-outs —\n // withdraw the revoked tag and evict any row left with no tag (via the bulk-delete path, so\n // the reconcile trigger fires and the read model converges).\n const patternSets = moveOutsToCommit.get(shapeName);\n if (patternSets) {\n await applyShapeMoveOut({\n pg: tx,\n metadataSchema,\n shapeTable,\n target,\n patternSets,\n debug,\n });\n }\n }\n\n if (key) {\n await updateSubscriptionState({\n pg: tx,\n metadataSchema,\n subscriptionKey: key,\n shapeMetadata: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => {\n const stream = getShapeStream(shapeName);\n return [\n shapeName,\n {\n handle: stream.shapeHandle!,\n offset: stream.lastOffset,\n },\n ];\n }),\n ),\n lastLsn: targetLsn,\n debug,\n });\n }\n\n // If we unsubscribed while this commit was in flight, discard it rather than persist\n // work during teardown. PGlite's `transaction()` skips its COMMIT once `tx.rollback()`\n // has closed the tx, so this rolls back both the applied rows and the subscription-state\n // advance; the (un-advanced) persisted offset means a later resume re-streams this batch.\n if (unsubscribed) {\n await tx.rollback();\n }\n });\n\n for (let attempt = 1; ; attempt++) {\n if (unsubscribed) {\n return false;\n }\n try {\n await runCommit();\n if (unsubscribed) {\n // The commit rolled itself back on unsubscribe (see runCommit); do not advance the\n // committed frontier, ACK the peeked buffer, or clear truncate flags for discarded work.\n return false;\n }\n committedLsn = targetLsn;\n // The transaction committed — now (and only now) remove the peeked batch from the inbox, passing\n // the peek-time epochs so a shape reset mid-commit is skipped (its rebuild survives). Move-outs/\n // move-ins are ACKed by the exact peeked count so anything that arrived during a coalescing\n // commit survives for the next run.\n inbox.ackUpTo(targetLsn, epochsAtPeek);\n for (const [shapeName, patternSets] of moveOutsToCommit) {\n inbox.ackMoveOuts(shapeName, patternSets.length, epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName));\n }\n for (const [shapeName, moveInMessages] of moveInsToCommit) {\n inbox.ackMoveIns(\n shapeName,\n moveInMessages.length,\n epochsAtPeek.get(shapeName) ?? inbox.epochFor(shapeName),\n );\n }\n for (const shapeName of shapesToTruncate) {\n truncateNeeded.delete(shapeName);\n }\n if (debug) console.timeEnd(\"commit\");\n maybeSignalInitialSync();\n return true;\n } catch (error) {\n if (unsubscribed) {\n return false;\n }\n if (attempt >= maxCommitRetries) {\n degraded = true;\n onSyncError?.(error instanceof Error ? error : new Error(String(error)));\n return false;\n }\n await new Promise((resolve) => setTimeout(resolve, commitRetryDelayMs(attempt)));\n }\n }\n };\n\n const lowestCompleteLsn = (): Lsn => inbox.lowestCompleteLsn();\n\n // ─── Live-tail sibling nudge (ADR-0031 live-tail completion) ──────────────────────────────────────\n // The catch-up alignment (ADR-0031 in shape-inbox.ts) fixed this class of stall at BOOT: quiet shapes'\n // stale cached watermarks no longer hold a busy shape's backfill. On the LIVE tail the same shape holds\n // recur — a change batch lands on a busy shape at LSN L, but the group commits only at the min effective\n // frontier, so the batch stays buffered until every quiet sibling's PARKED long-poll returns a fresh\n // `global_last_seen_lsn` (~41s on Electric Cloud). This watchdog closes that live-tail gap: when a batch\n // is gated (its `batchMaxLsn > committedLsn`), it nudges each lagging sibling — aborting its parked poll\n // and forcing an immediate NON-live catch-up (`forceDisconnectAndRefresh`), which returns a fresh\n // watermark in ~sub-second. The group frontier then reaches L and the normal commit path (driven by the\n // up-to-date arrivals, NOT by this watchdog) fires. Atomicity is untouched: commits still happen only at\n // the group min frontier. The one-shot cache-buster (`nudgeBusters` + `withNudgeBuster`) defends each\n // nudged catch-up against a CDN HIT that would echo the stale watermark. Bounded to NUDGE_MAX_ROUNDS so a\n // genuinely-dead or still-legitimately-polling sibling degrades to the old wait-out-the-poll behavior\n // rather than a refresh storm.\n const nudgeInFlight = new Map<string, Promise<void>>();\n let nudgeTargetLsn: Lsn = BigInt(-1);\n let nudgeWatchdogRunning = false;\n\n // Void-called from the subscribe callback (never awaited — it must not backpressure the stream). Raises\n // the shared target and, if not already running, runs bounded rounds until the frontier reaches it, the\n // group tears down / degrades / re-closes its gate, or the rounds exhaust. Single-flight: a concurrent\n // gated batch just raises `nudgeTargetLsn` and returns. Wrapped so it can never throw unhandled.\n const runNudgeWatchdog = async (targetLsn: Lsn): Promise<void> => {\n if (targetLsn > nudgeTargetLsn) {\n nudgeTargetLsn = targetLsn;\n }\n if (nudgeWatchdogRunning) {\n return;\n }\n nudgeWatchdogRunning = true;\n try {\n // Pre-alignment (boot catch-up, before ADR-0031 lays the commit floors) the nudge is pure noise:\n // the alignment itself will commit the gated backfill the moment every shape reports, and firing\n // busted catch-ups mid-boot only contends with the boot requests. The floors survive later resets,\n // so this gate closes exactly once — the live tail is always past it.\n if (inbox.alignedFloor() < BigInt(0)) {\n return;\n }\n // Resolved / torn-down / gated-shut → nothing to nudge; the up-to-date arrival itself runs the\n // commit, so the watchdog never commits.\n const resolvedOrStopped = (): boolean =>\n unsubscribed || degraded || !dbGateOpen || lowestCompleteLsn() >= nudgeTargetLsn;\n\n // Hold-persistence grace: a cross-shape transaction's sibling halves arrive milliseconds apart,\n // so EVERY grouped commit passes through a transient held instant — nudging on it would abort\n // the sibling poll that is about to deliver the other half (the sync-e2e regression). Only a\n // hold that survives this grace is a real quiet-sibling park worth nudging.\n for (let waited = 0; waited < NUDGE_HOLD_GRACE_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n\n for (let round = 1; round <= NUDGE_MAX_ROUNDS; round++) {\n if (resolvedOrStopped()) {\n return;\n }\n for (const shapeName of Object.keys(shapes)) {\n // A shape still catching up advances on its own — only nudge one already in its live tail.\n if (!inbox.hasReportedUpToDate(shapeName)) continue;\n if (inbox.effectiveLsnFor(shapeName) >= nudgeTargetLsn) continue;\n if (nudgeInFlight.has(shapeName)) continue;\n // `forceDisconnectAndRefresh` is declared on the real ShapeStream, but a mocked/typed surface may\n // omit it — reach it structurally and skip (with a rail line) when absent.\n const stream = getShapeStream(shapeName) as { forceDisconnectAndRefresh?: () => Promise<void> };\n if (typeof stream.forceDisconnectAndRefresh !== \"function\") {\n syncDebug(\"live-tail sibling nudge unavailable\", { shape: shapeName });\n continue;\n }\n // Arm the one-shot cache-buster BEFORE the refresh so the forced catch-up carries it.\n nudgeBusters.set(shapeName, crypto.randomUUID());\n syncDebug(\"live-tail sibling nudge\", { shape: shapeName, target: String(nudgeTargetLsn), round });\n const refresh = stream\n .forceDisconnectAndRefresh()\n .catch((err: unknown) =>\n syncDebug(\"live-tail sibling nudge failed\", { shape: shapeName, error: String(err) }),\n )\n .finally(() => {\n nudgeInFlight.delete(shapeName);\n });\n nudgeInFlight.set(shapeName, refresh);\n }\n // Nothing to nudge and nothing in flight → exit QUIETLY (no exhaustion line). This is the routine\n // pre-alignment case: a gated batch during catch-up has siblings that have not yet reported\n // up-to-date, and those advance on their own — spinning the remaining rounds would only delay-loop\n // and print a misleading \"exhausted\" line on every boot rail. The \"held by group frontier\" line\n // already told the story.\n if (nudgeInFlight.size === 0) {\n return;\n }\n // Wait for this round's forced catch-ups to actually land and advance the frontier. The refresh\n // promises settle before the refreshed response does (measured), so awaiting them alone would\n // re-nudge into still-in-flight requests — poll the frontier instead, bounded per round, and\n // break out the moment the target is reached.\n await Promise.all([...nudgeInFlight.values()]);\n for (let waited = 0; waited < NUDGE_ROUND_WAIT_MS; waited += NUDGE_ROUND_GRACE_MS) {\n await new Promise((resolve) => setTimeout(resolve, NUDGE_ROUND_GRACE_MS));\n if (resolvedOrStopped()) {\n return;\n }\n }\n }\n // Rounds exhausted and the frontier is still short: a sibling is dead or genuinely mid-poll. Degrade\n // to the old behavior (wait out its live long-poll) rather than nudge forever.\n syncDebug(\"live-tail nudge exhausted; waiting on sibling live polls\", {\n target: String(nudgeTargetLsn),\n frontier: String(lowestCompleteLsn()),\n });\n } catch (err) {\n syncDebug(\"live-tail nudge watchdog error\", { error: String(err) });\n } finally {\n nudgeWatchdogRunning = false;\n }\n };\n\n // Drain buffered changes up to the current complete frontier, one commit at a time, looping\n // while fresh messages keep arriving (so commits coalesce). Returns early on `degraded` — a held\n // commit is not retried here; recovery is a later message/refetch or a restart.\n const runCommitLoop = async (): Promise<void> => {\n do {\n commitRerun = false;\n const target = lowestCompleteLsn();\n const isCommitNeeded = target > committedLsn;\n const isMustRefetchAndCatchingUp = target >= committedLsn && truncateNeeded.size > 0;\n // A buffered move-out (ADR-0023) or move-in (ADR-0024) must be committed even if no change\n // advanced the frontier — the revocation/grant has to land. Their `up-to-date` normally advances\n // `target`, but don't rely on that (move/event messages carry no LSN).\n const hasPendingMoves = target >= committedLsn && (inbox.hasPendingMoveOuts() || inbox.hasPendingMoveIns());\n // ADR-0031: a LATE-arriving change at or below an already-committed target must still commit. The\n // aligned commit floor lets `ingestChange` accept a change below the floor (its dedup frontier is\n // the raw `completeLsns`, unmoved by the floor), so such a change can land AFTER the group frontier\n // has already reached — or passed — its LSN, where no frontier advance would trigger a commit for\n // it. Committing at `target === committedLsn` is safe: it mirrors the moves path, which already\n // calls `commitUpToLsn(target)` with no frontier advance. (At `target > committedLsn` this overlaps\n // `isCommitNeeded` — harmless; the expression stays simple.)\n const hasLateArrivals = target >= committedLsn && inbox.hasBufferedChangesAtOrBelow(target);\n if (isCommitNeeded || isMustRefetchAndCatchingUp || hasPendingMoves || hasLateArrivals) {\n const applied = await commitUpToLsn(target);\n if (!applied) {\n return;\n }\n } else {\n maybeSignalInitialSync();\n }\n } while (commitRerun);\n };\n\n // Single-flight: at most one commit loop runs. A message arriving while one is running buffers\n // synchronously (above) and re-arms the loop via `commitRerun`; `commitInFlight` is cleared\n // inside the same async body — before its promise resolves — so an enqueue can never observe a\n // stale in-flight handle and resolve without committing its messages.\n const enqueueCommit = (): Promise<void> => {\n // ADR-0009 decision 5: once a commit exhausts its retries the engine latches `degraded` and\n // REFUSES to run any further commit. `commitUpToLsn` peeks (never drains) the buffer, so the\n // unapplied batch is still held; refusing later commits guarantees a newer LSN can never apply\n // over that held batch (the divergence the destructive drain allowed). The buffer keeps\n // accumulating incoming messages harmlessly; recovery is a restart/refetch, which re-streams the\n // held frontier because the persisted offset was never advanced. Note the commit-await backpressure\n // is intentionally absent while degraded — the inbox grows at the stream's rate until recovery,\n // which is the accepted cost of ADR-0009's documented \"hold the buffer\" posture.\n if (degraded) {\n return commitInFlight ?? Promise.resolve();\n }\n if (commitInFlight) {\n commitRerun = true;\n return commitInFlight;\n }\n commitInFlight = (async () => {\n try {\n await runCommitLoop();\n } finally {\n commitInFlight = null;\n }\n })();\n return commitInFlight;\n };\n\n multiShapeStream.subscribe(async (messages) => {\n if (unsubscribed) {\n return;\n }\n // A delivered batch means a fetch just succeeded — the read path is alive (ADR-0013 Phase 3),\n // so the runtime can clear an auth-needed status once a fresh token starts working again.\n onSyncActivity?.();\n if (debug) {\n console.log(\"received messages\", messages.length);\n }\n // Receive-path latency probe: a batch carrying real change rows is the moment Electric delivered\n // a write to this subscriber (the writer's own echo, or another browser's edit fanning in). The\n // gap from here to the commit finishing is the local apply cost.\n const changeCount = messages.reduce((n, message) => (isChangeMessage(message) ? n + 1 : n), 0);\n if (changeCount > 0) {\n syncDebug(\"sync received change batch from Electric\", { changes: changeCount });\n }\n const commitStartedAt = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // The max LSN over the change rows this batch COMPLETED (routed to `ingestChange` with `isLastOfLsn`;\n // move-in rows carry no lsn and are excluded). It is what the batch needs the group frontier to reach\n // to actually commit — the truth test for the \"applied\" vs \"held\" rail line below. -1 if none.\n let batchMaxLsn: Lsn = BigInt(-1);\n\n messages.forEach((message) => {\n if (isChangeMessage(message)) {\n // A tagged-subquery MOVE-IN row (ADR-0024): an existing row ENTERING the shape because a grant\n // was added. Electric delivers it as a snapshot insert flagged `is_move_in` with NO `lsn`/`last`\n // (it is not a replication-stream change), so the `ingestChange` dedup — which floors a missing\n // lsn to 0 — would treat it as already-seen and drop it once the frontier passed 0. Route it to\n // its own buffer, applied idempotently at the next commit (the trailing `up-to-date`).\n if (message.headers[\"is_move_in\"] === true) {\n inbox.ingestMoveIn(message.shape, message);\n } else {\n const { lsn, isLastOfLsn } = readReplicationHeaders(message.headers);\n inbox.ingestChange(message.shape, message, lsn, isLastOfLsn);\n if (isLastOfLsn && lsn > batchMaxLsn) {\n batchMaxLsn = lsn;\n }\n }\n } else if (isControlMessage(message)) {\n switch (message.headers.control) {\n case \"up-to-date\": {\n if (debug) {\n console.log(\"received up-to-date\", message);\n }\n if (typeof message.headers.global_last_seen_lsn !== \"string\") {\n throw new Error(\"global_last_seen_lsn is not a string\");\n }\n // ADR-0031: `ingestUpToDate` returns true ONLY on the transition where this control message\n // completed the group (every shape has now reported up-to-date) and the inbox aligned the\n // commit floors. Surface that single moment on the debug rail so a \"stale board at load that\n // rearranges itself\" symptom is diagnosable — the floor it aligned to is the group head.\n if (inbox.ingestUpToDate(message.shape, BigInt(message.headers.global_last_seen_lsn))) {\n syncDebug(\"catch-up watermark aligned\", { floor: String(inbox.alignedFloor()) });\n }\n break;\n }\n case \"must-refetch\": {\n if (debug) {\n console.log(\"received must-refetch\", message);\n }\n // Surface the expired-handle / rewind event on the syncDebug rail too (the legacy `debug`\n // option only console.logs it): must-refetch is the trigger for the truncate + re-snapshot\n // recovery, so it must be visible when diagnosing a convergence loss in a live app.\n syncDebug(\"must-refetch received\", { shape: message.shape });\n inbox.resetShape(message.shape);\n truncateNeeded.add(message.shape);\n break;\n }\n }\n } else if (isEventMessage(message)) {\n // ADR-0023: a tagged-subquery move-out — a grant was revoked, so the rows it kept in the shape\n // must be evicted. Buffer the patterns; the eviction runs in the next commit (decision 3).\n // `MultiShapeStream`'s callback type does not declare `EventMessage` (the prior guards narrow\n // `message` to `never` here), so reach the runtime-present event through an explicit cast.\n const eventMessage = message as unknown as ShapeEventMessage;\n if (eventMessage.headers.event === \"move-out\") {\n if (debug) {\n console.log(\"received move-out\", eventMessage);\n }\n inbox.ingestMoveOut(eventMessage.shape, eventMessage.headers.patterns);\n }\n // A `move-in` EventMessage (ADR-0024) needs no action here: its newly-matched rows arrive in the\n // same batch as snapshot inserts flagged `is_move_in`, which the change branch routes to the\n // move-in buffer. The event's `patterns` are redundant with those inserts' `tags`.\n }\n });\n\n // Buffering above is synchronous. On the overlap path, while the commit gate is still closed the\n // batch stays in the memory inbox (its LSN frontier + catch-up watermarks still advance from the\n // ingest above) and the callback returns WITHOUT awaiting a commit — so the stream keeps fetching\n // catch-up and does not stall behind the local boot phases. Once the gate lifts, the deferred commit\n // train (below) drains everything buffered. On the sequential path the gate is already open, so this\n // is the unchanged path: enqueue the single-flight commit and await it (the natural backpressure that\n // bounds the buffer — replacing the old fire-and-forget commit + `setTimeout(0)` race).\n if (dbGateOpen) {\n await enqueueCommit();\n if (changeCount > 0) {\n // Truthful rail (ADR-0031): the \"applied\" line only fires when this batch's completed changes\n // actually landed (its `batchMaxLsn` is at or below the advanced `committedLsn`). Otherwise the\n // group frontier had not reached them — the batch is BUFFERED behind a quiet sibling's watermark —\n // so say so, and kick the live-tail sibling nudge to shorten that hold (void: never backpressure\n // the stream).\n if (batchMaxLsn <= committedLsn) {\n const elapsed = (typeof performance !== \"undefined\" ? performance.now() : Date.now()) - commitStartedAt;\n syncDebug(\"sync applied change batch to local store\", { changes: changeCount, ms: Math.round(elapsed) });\n } else {\n syncDebug(\"sync change batch held by group frontier\", {\n changes: changeCount,\n heldLsn: String(batchMaxLsn),\n frontier: String(lowestCompleteLsn()),\n });\n void runNudgeWatchdog(batchMaxLsn);\n }\n }\n }\n }, onError);\n\n // Fresh-store prefetch overlap (ADR-0032 S4): the moment the caller signals the local store is ready\n // (schema exec + journal recovery + store-version reconcile done), run the deferred metadata DDL, open\n // the commit gate, and drain everything the streams buffered during the window in one commit train. The\n // ADR-0031 catch-up watermarks were aligned by the ingests above as the up-to-dates arrived, so this\n // drain commits to the aligned floor and `onInitialSync` fires exactly as on the sequential path.\n if (overlap) {\n void dbReady!.then(async () => {\n if (unsubscribed) {\n return;\n }\n // The metadata tables' DDL was deferred past the gate (the store had no schema when the streams\n // started); create them now, before the first commit needs the subscription-state table.\n await initMetadataTables();\n dbGateOpen = true;\n syncDebug(\"boot commits opened\");\n await enqueueCommit();\n });\n }\n\n streams.push({\n stream: multiShapeStream,\n aborter,\n });\n\n const unsubscribe = () => {\n if (debug) {\n console.log(\"unsubscribing\");\n }\n unsubscribed = true;\n multiShapeStream.unsubscribeAll();\n aborter.abort();\n for (const shape of Object.values(shapes)) {\n shapePerTableLock.delete(shape.tableKey);\n }\n };\n\n return {\n unsubscribe,\n get isUpToDate() {\n // Never report up-to-date while a commit is pending or after going degraded (ADR-0009\n // decision 5): the read cache must not claim to match the server on an unapplied commit. Nor while\n // the overlap commit gate is still closed (ADR-0032 S4): the stream may already be `isUpToDate` on\n // the network side while its catch-up is still buffered, unapplied, in the memory inbox.\n return dbGateOpen && !degraded && commitInFlight === null && multiShapeStream.isUpToDate;\n },\n streams: Object.fromEntries(\n Object.keys(shapes).map((shapeName) => [shapeName, getShapeStream(shapeName)]),\n ) as SyncShapesToTablesResult[\"streams\"],\n };\n };\n\n const syncShapeToTable = async (options: SyncShapeToTableOptions): Promise<SyncShapeToTableResult> => {\n // ADR-0029 D6: thin sugar over the group form, forwarding the same entry-based options. The\n // per-shape `initialInsertMethod` (if any) rides through; the group form resolves the backfill\n // strategy from the registry entry when it is absent.\n const multiShapeSub = await syncShapesToTables({\n registry: options.registry,\n shapes: {\n shape: {\n shape: options.shape,\n tableKey: options.tableKey,\n onMustRefetch: options.onMustRefetch,\n ...(options.initialInsertMethod ? { initialInsertMethod: options.initialInsertMethod } : {}),\n },\n },\n key: options.shapeKey,\n onInitialSync: options.onInitialSync,\n onError: options.onError,\n onSyncError: options.onSyncError,\n maxCommitRetries: options.maxCommitRetries,\n commitRetryDelayMs: options.commitRetryDelayMs,\n });\n\n return {\n unsubscribe: multiShapeSub.unsubscribe,\n get isUpToDate() {\n return multiShapeSub.isUpToDate;\n },\n stream: (() => {\n const stream = multiShapeSub.streams[\"shape\"];\n if (!stream) {\n throw new Error(\"Missing stream for shape\");\n }\n return stream;\n })() as SyncShapeToTableResult[\"stream\"],\n };\n };\n\n const deleteSubscription = async (key: string) => {\n await deleteSubscriptionState({\n pg,\n metadataSchema,\n subscriptionKey: key,\n });\n };\n\n const namespaceObj = {\n initMetadataTables,\n syncShapesToTables,\n syncShapeToTable,\n deleteSubscription,\n };\n\n const close = async () => {\n for (const { stream, aborter } of streams) {\n stream.unsubscribeAll();\n aborter.abort();\n }\n };\n\n return {\n namespace: namespaceObj,\n close,\n };\n}\n\n/**\n * The pgxsinkit sync engine handle: the {@link SyncNamespaceObj} the client attaches as `pg.electric`,\n * plus the explicit `close()` teardown. Derived from {@link createSyncEngine}'s real return so the type\n * follows the object.\n */\nexport type SyncEngine = Awaited<ReturnType<typeof createSyncEngine>>;\nexport type SyncNamespaceObj = SyncEngine[\"namespace\"];\n\nexport type PGliteWithSync = PGliteInterface & {\n sync: SyncNamespaceObj;\n};\n",
120
+ "import type { ChangeMessage, MovePattern, Row } from \"@electric-sql/client\";\n\nimport type { InsertChangeMessage, Lsn } from \"./types\";\n\n/**\n * The Shape inbox (ADR-0014 / ISS-06): the pure, in-memory staging buffer between a shape's\n * Electric subscription and the Sync applier. It buffers each shape's change messages keyed by\n * LSN, tracks each shape's complete-LSN frontier, and drains everything up to a target LSN for the\n * applier to write. No database I/O lives here — that is exactly what makes it (and the ADR-0014\n * per-PK fold that will live here) property-testable against an ordered per-row apply oracle.\n *\n * One inbox owns all shapes in a consistency group; the group commits atomically at the lowest\n * complete frontier across its shapes ({@link lowestCompleteLsn}). `must-refetch` truncation stays\n * with the applier (the inbox only drops the affected shape's buffer via {@link resetShape}).\n *\n * COMMIT WATERMARK vs DEDUP FRONTIER (ADR-0031) — the load-bearing separation. Two per-shape LSNs live\n * here and they are deliberately NOT the same number:\n *\n * - {@link completeLsns} — the SOLE dedup threshold. {@link ingestChange} drops any change at or below\n * it as already-seen. Nothing else may narrow what the inbox accepts; a change below a shape's floor\n * (below) but above its raw frontier is still buffered, never dropped.\n * - {@link commitFloors} — a per-shape COMMIT watermark laid down once per catch-up completion (see\n * {@link ingestUpToDate}'s alignment). It only ever RAISES a shape's effective commit frontier in\n * {@link lowestCompleteLsn}; it never gates ingestion.\n *\n * Why the two must be separate: Electric's catch-up (non-live) shape responses are CDN-cacheable\n * (`s-maxage`, `stale-while-revalidate`), and the `up-to-date` control message — with its\n * `global_last_seen_lsn` watermark — rides INSIDE that cached body. So a quiet shape's cached catch-up\n * can assert a STALE watermark (captured before a busy sibling shape's newer writes), which drags the\n * group min-frontier below changes already delivered on the busy shape, holding them buffered until the\n * quiet shape's first LIVE long-poll returns a fresh watermark (~tens of seconds on Electric Cloud). The\n * alignment lifts the commit floors to the freshest ASSERTED global head so those changes commit at\n * catch-up completion — while the dedup frontier stays put, so a late sub-floor change from a shape whose\n * cached catch-up omitted it is still ingested and committed rather than dropped.\n */\nexport class ShapeInbox {\n // Per shape: buffered change messages keyed by their LSN, kept in arrival order within an LSN.\n private readonly changes = new Map<string, Map<Lsn, ChangeMessage<Row<unknown>>[]>>();\n // Per shape: the highest LSN known complete (every change at or below it has been received).\n private readonly completeLsns = new Map<string, Lsn>();\n // Per shape: buffered `move-out` events (ADR-0023), one pattern set per event. The event carries no\n // LSN, so it cannot key `changes`; it is drained and applied at the next commit (the `up-to-date`\n // that follows it), in the same transaction as that frontier's changes.\n private readonly moveOuts = new Map<string, MovePattern[][]>();\n // Per shape: buffered `move-in` snapshot rows (ADR-0024). A move-in row (`is_move_in`) is a row\n // ENTERING the shape; Electric delivers it as a snapshot insert with NO `lsn`/`last`, so it cannot\n // key `changes` either (and the change dedup, which floors a missing lsn to 0, would drop it once the\n // frontier passed 0). Drained and applied — idempotently — at the next commit, like the move-outs.\n private readonly moveIns = new Map<string, ChangeMessage<Row<unknown>>[]>();\n // Per shape: a reset epoch, bumped every time {@link resetShape} rewinds a shape (must-refetch). The\n // commit path records each shape's epoch at PEEK time and passes it back to the acks; an ack no-ops for\n // any shape whose epoch has since changed. This closes the mid-commit-reset hole: if a must-refetch +\n // re-snapshot arrives for shape B WHILE a commit that peeked B is in flight, B's frontier is rewound and\n // its buffers replaced with post-reset content; without the epoch guard the succeeding commit's\n // `ackUpTo`/`ackMove*` would delete/splice that never-peeked post-reset content, leaving B truncated-empty.\n private readonly epochs = new Map<string, number>();\n // Per shape: whether a snapshot (LSN-0) row is currently accepted PAST the dedup frontier. Set on\n // registration and every {@link resetShape} (must-refetch); re-armed (cleared) the first time a change\n // with a REAL lsn (> 0) is ingested for the shape. Invariant: after a reset — and on a brand-new shape\n // before any real replication LSN has been seen — a re-snapshot's rows are floored to LSN 0, yet the\n // frontier may already sit at a large LSN (a racing bare `up-to-date` advanced it before the rows\n // landed). The LSN-0 dedup ({@link ingestChange}) would then drop the whole re-snapshot. So while this\n // flag is set, LSN-0 rows bypass the dedup; the first real lsn (> 0) proves the stream has moved past\n // the snapshot into the live tail, and re-arms the dedup. The re-snapshot's rows reaching the applier\n // is what keeps the reconcile loop — the completeness guarantee (ADR-0029 D4) — whole.\n private readonly snapshotAccepted = new Map<string, boolean>();\n // Per shape: whether this shape has reported `up-to-date` at least once since registration / its last\n // {@link resetShape}. Set true in {@link ingestUpToDate} even when the reported watermark does NOT\n // advance the frontier (a stale cached watermark still means \"this shape has completed a catch-up and\n // asserted a global head\"). The catch-up alignment (ADR-0031) fires only once EVERY shape in the group\n // has reported up-to-date — i.e. once the whole group has a first asserted global head to align to.\n private readonly upToDateSeen = new Map<string, boolean>();\n // Per shape: the watermark (`global_last_seen_lsn`) this shape MOST RECENTLY reported via\n // {@link ingestUpToDate}, recorded unconditionally — even a stale cached watermark that does not\n // advance {@link completeLsns}. This is the input to the group-max alignment: the freshest asserted\n // global head across the group is `max` over these REPORTED watermarks (NOT over the frontiers — a\n // frontier can sit ahead of every reported watermark mid-live-batch; see {@link ingestUpToDate}).\n private readonly lastUpToDateLsn = new Map<string, Lsn>();\n // Per shape: the COMMIT floor (ADR-0031) — a watermark that only ever RAISES this shape's effective\n // commit frontier in {@link lowestCompleteLsn}, never its dedup threshold. Laid down once per catch-up\n // completion by the alignment in {@link ingestUpToDate}. Deliberately NOT reset by {@link resetShape}:\n // floors are monotonic, so a reset shape keeps its old floor (its buffer is empty anyway) until the\n // next group-wide realignment lifts it. Default -1 = no floor.\n private readonly commitFloors = new Map<string, Lsn>();\n // Whether the one-time catch-up commit-floor alignment (ADR-0031) has already run for the current\n // registration/reset generation. False at construction; set true when the alignment lays down floors in\n // {@link ingestUpToDate}; reset to false by {@link resetShape} so a must-refetch re-catch-up realigns\n // the group once every shape has completed again (a reset shape re-streams a fresh — possibly cached —\n // catch-up, so the group needs a fresh asserted global head to align to).\n private aligned = false;\n // The freshest asserted global head the last alignment aligned to (`max` over reported watermarks) —\n // surfaced on the debug rail by the caller as the `floor` of the `catch-up watermark aligned` line.\n private lastAlignedFloor: Lsn = BigInt(-1);\n\n constructor(shapeNames: Iterable<string>) {\n for (const shapeName of shapeNames) {\n this.changes.set(shapeName, new Map());\n this.completeLsns.set(shapeName, BigInt(-1));\n this.moveOuts.set(shapeName, []);\n this.moveIns.set(shapeName, []);\n this.epochs.set(shapeName, 0);\n this.snapshotAccepted.set(shapeName, true);\n this.upToDateSeen.set(shapeName, false);\n this.lastUpToDateLsn.set(shapeName, BigInt(-1));\n this.commitFloors.set(shapeName, BigInt(-1));\n }\n }\n\n /**\n * Whether the shape is still accepting snapshot (LSN-0) rows past the dedup frontier — true from\n * registration / the last {@link resetShape} until the first real-lsn change re-armed the dedup. The\n * commit path reads this to apply such rows idempotently (the racing recovery loops can double-deliver\n * them), consistent with the move-in upsert path, rather than as a plain collision-surfacing insert.\n */\n acceptsSnapshotRowsFor(shapeName: string): boolean {\n return this.snapshotAccepted.get(shapeName) === true;\n }\n\n /** The complete-LSN frontier for one shape (the already-seen dedup threshold). */\n completeLsnFor(shapeName: string): Lsn {\n return this.completeLsns.get(shapeName) ?? BigInt(-1);\n }\n\n /**\n * The shape's current reset epoch. The commit path snapshots this for every peeked shape and passes it\n * back to the acks, which no-op for any shape whose epoch changed (a mid-commit {@link resetShape}) so\n * the reset's own truncate+rebuild path owns that shape's post-reset state.\n */\n epochFor(shapeName: string): number {\n return this.epochs.get(shapeName) ?? 0;\n }\n\n /**\n * Buffer a change message. A message at or below the shape's current complete frontier is\n * already-seen and dropped. `isLastOfLsn` advances the frontier to this LSN.\n */\n ingestChange(shapeName: string, message: ChangeMessage<Row<unknown>>, lsn: Lsn, isLastOfLsn: boolean): void {\n // A real replication lsn (> 0) proves the stream has moved past the snapshot into the live tail:\n // re-arm the LSN-0 dedup for this shape (see {@link snapshotAccepted}).\n if (lsn > BigInt(0)) {\n this.snapshotAccepted.set(shapeName, false);\n }\n // A snapshot (LSN-0) row while snapshot acceptance is open bypasses the dedup even if the frontier\n // has advanced past 0 — otherwise a re-snapshot delivered AFTER a racing `up-to-date` (which pushed\n // the frontier to a large LSN) would be dropped wholesale, truncating the shape to empty. It still\n // buffers at LSN 0 (and does not advance the frontier), so drains/acks/truncate are unchanged.\n const acceptSnapshotRow = lsn === BigInt(0) && this.acceptsSnapshotRowsFor(shapeName);\n if (!acceptSnapshotRow && lsn <= this.completeLsnFor(shapeName)) {\n return;\n }\n\n const shapeChanges = this.changes.get(shapeName);\n if (!shapeChanges) {\n return;\n }\n\n let lsnMessages = shapeChanges.get(lsn);\n if (!lsnMessages) {\n lsnMessages = [];\n shapeChanges.set(lsn, lsnMessages);\n }\n lsnMessages.push(message);\n\n if (isLastOfLsn) {\n this.completeLsns.set(shapeName, lsn);\n }\n }\n\n /** The commit floor (ADR-0031) for one shape — the aligned watermark; -1 when no floor has been laid. */\n commitFloorFor(shapeName: string): Lsn {\n return this.commitFloors.get(shapeName) ?? BigInt(-1);\n }\n\n /**\n * A shape's EFFECTIVE complete frontier (ADR-0031): `max(completeLsnFor(shape), commitFloorFor(shape))` —\n * the raw dedup frontier raised by any aligned commit floor. This is the exact per-shape quantity\n * {@link lowestCompleteLsn} minimizes over (both go through here, so the two definitions cannot drift),\n * and the input the live-tail sibling nudge reads to decide which siblings still lag a target LSN.\n */\n effectiveLsnFor(shapeName: string): Lsn {\n const raw = this.completeLsnFor(shapeName);\n const floor = this.commitFloorFor(shapeName);\n return raw > floor ? raw : floor;\n }\n\n /**\n * Whether this shape has reported `up-to-date` at least once since registration / its last\n * {@link resetShape} — the {@link upToDateSeen} flag. The live-tail sibling nudge (ADR-0031) reads this:\n * a shape still catching up advances on its own, so only a shape already in its live tail is ever nudged.\n */\n hasReportedUpToDate(shapeName: string): boolean {\n return this.upToDateSeen.get(shapeName) === true;\n }\n\n /** The freshest asserted global head the last catch-up alignment aligned to (ADR-0031); -1 if never aligned. */\n alignedFloor(): Lsn {\n return this.lastAlignedFloor;\n }\n\n /**\n * Advance the frontier on an `up-to-date` control message (carries no buffered change) AND run the\n * one-time catch-up commit-floor alignment (ADR-0031) once the whole group has reported up-to-date.\n *\n * Returns `true` iff THIS call performed the alignment (the caller emits a single diagnostic line on\n * that transition); `false` on every other call.\n */\n ingestUpToDate(shapeName: string, globalLastSeenLsn: Lsn): boolean {\n // Record the report unconditionally: this shape has now completed a catch-up and asserted a global\n // head, and this is the watermark to align to — even if it is stale (below the frontier) and so does\n // NOT advance the dedup frontier below. Both facts feed the alignment; neither is the frontier.\n this.upToDateSeen.set(shapeName, true);\n this.lastUpToDateLsn.set(shapeName, globalLastSeenLsn);\n\n // The existing conditional frontier advance is UNCHANGED: a watermark only advances the dedup frontier\n // when it is strictly ahead of it. A stale cached watermark leaves the frontier where it was.\n if (globalLastSeenLsn > this.completeLsnFor(shapeName)) {\n this.completeLsns.set(shapeName, globalLastSeenLsn);\n }\n\n // Catch-up commit-floor alignment (ADR-0031), one-time per registration/reset generation: once EVERY\n // shape in the group has reported up-to-date, lift each shape's commit floor to the freshest asserted\n // global head. That is `max` over the REPORTED watermarks ({@link lastUpToDateLsn}) — deliberately NOT\n // over the frontiers ({@link completeLsns}). A frontier can be ahead of every reported watermark when a\n // live change batch is in flight and its sibling shapes' halves have not arrived yet; aligning floors\n // to such a frontier would commit one shape's half of a cross-shape transaction ahead of the other's\n // (a torn write). The freshest asserted global head is a watermark every shape has been told is\n // complete, so aligning to it can never tear a transaction that is still assembling above it.\n if (!this.aligned) {\n let everySeen = true;\n for (const seen of this.upToDateSeen.values()) {\n if (!seen) {\n everySeen = false;\n break;\n }\n }\n if (everySeen) {\n let groupMax: Lsn = BigInt(-1);\n for (const reported of this.lastUpToDateLsn.values()) {\n if (reported > groupMax) {\n groupMax = reported;\n }\n }\n for (const shape of this.commitFloors.keys()) {\n const existing = this.commitFloorFor(shape);\n this.commitFloors.set(shape, groupMax > existing ? groupMax : existing);\n }\n this.aligned = true;\n this.lastAlignedFloor = groupMax;\n return true;\n }\n }\n return false;\n }\n\n /** Buffer a `move-out` event's patterns for a shape (ADR-0023); applied at the next commit. */\n ingestMoveOut(shapeName: string, patterns: MovePattern[]): void {\n this.moveOuts.get(shapeName)?.push(patterns);\n }\n\n /** Remove and return a shape's buffered `move-out` pattern sets (one per event), in arrival order. */\n drainMoveOuts(shapeName: string): MovePattern[][] {\n const pending = this.moveOuts.get(shapeName) ?? [];\n this.moveOuts.set(shapeName, []);\n return pending;\n }\n\n /**\n * Peek — WITHOUT removing — a shape's buffered `move-out` pattern sets (a copy, arrival order). Pairs\n * with {@link ackMoveOuts}: the commit path peeks, applies inside its transaction, and acks (removes)\n * only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5) leaves the\n * revocations buffered rather than silently losing them.\n */\n peekMoveOuts(shapeName: string): MovePattern[][] {\n return [...(this.moveOuts.get(shapeName) ?? [])];\n }\n\n /**\n * Remove the first `count` buffered `move-out` pattern sets for a shape (call only after the commit\n * that consumed a matching {@link peekMoveOuts} of that many entries succeeded). Removing exactly the\n * peeked count — not clear-all — keeps any move-out that arrived DURING the commit (coalescing path)\n * buffered for the next run. `epochAtPeek` is the shape's {@link epochFor} captured at peek time: if a\n * {@link resetShape} bumped it since, the peeked entries no longer exist (the array was replaced), so\n * this no-ops rather than splicing the post-reset replacement.\n */\n ackMoveOuts(shapeName: string, count: number, epochAtPeek: number): void {\n if (this.epochFor(shapeName) !== epochAtPeek) {\n return;\n }\n this.moveOuts.get(shapeName)?.splice(0, count);\n }\n\n /** Whether any shape has a buffered `move-out` awaiting a commit. */\n hasPendingMoveOuts(): boolean {\n for (const pending of this.moveOuts.values()) {\n if (pending.length > 0) return true;\n }\n return false;\n }\n\n /** Buffer a `move-in` snapshot row for a shape (ADR-0024); applied idempotently at the next commit. */\n ingestMoveIn(shapeName: string, message: ChangeMessage<Row<unknown>>): void {\n this.moveIns.get(shapeName)?.push(message);\n }\n\n /** Remove and return a shape's buffered `move-in` snapshot rows, in arrival order. */\n drainMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {\n const pending = this.moveIns.get(shapeName) ?? [];\n this.moveIns.set(shapeName, []);\n return pending;\n }\n\n /** Peek — WITHOUT removing — a shape's buffered `move-in` snapshot rows (a copy, arrival order). See {@link peekMoveOuts}. */\n peekMoveIns(shapeName: string): ChangeMessage<Row<unknown>>[] {\n return [...(this.moveIns.get(shapeName) ?? [])];\n }\n\n /**\n * Remove the first `count` buffered `move-in` snapshot rows for a shape (post-commit ack; see\n * {@link ackMoveOuts}). No-ops if `epochAtPeek` no longer matches the shape's current epoch (a\n * mid-commit {@link resetShape}), so the post-reset replacement rows survive.\n */\n ackMoveIns(shapeName: string, count: number, epochAtPeek: number): void {\n if (this.epochFor(shapeName) !== epochAtPeek) {\n return;\n }\n this.moveIns.get(shapeName)?.splice(0, count);\n }\n\n /** Whether any shape has a buffered `move-in` awaiting a commit. */\n hasPendingMoveIns(): boolean {\n for (const pending of this.moveIns.values()) {\n if (pending.length > 0) return true;\n }\n return false;\n }\n\n /** Reset a shape on `must-refetch`: drop its buffer and rewind its frontier (the applier truncates). */\n resetShape(shapeName: string): void {\n this.changes.get(shapeName)?.clear();\n this.completeLsns.set(shapeName, BigInt(-1));\n this.moveOuts.set(shapeName, []);\n this.moveIns.set(shapeName, []);\n // Re-open snapshot acceptance: the re-snapshot's LSN-0 rows must survive the dedup even if a racing\n // `up-to-date` advances the rewound frontier again before they arrive (see {@link snapshotAccepted}).\n this.snapshotAccepted.set(shapeName, true);\n // ADR-0031: this shape must re-report up-to-date before it counts toward the group again, and its\n // last reported watermark is void (it re-streams a fresh — possibly cached — catch-up). Clear the\n // group's aligned flag so the whole group realigns once every shape has completed again. The commit\n // floor is NOT cleared: floors are monotonic (the buffer is empty post-reset anyway), so the shape\n // keeps its old floor until realignment lifts it.\n this.upToDateSeen.set(shapeName, false);\n this.lastUpToDateLsn.set(shapeName, BigInt(-1));\n this.aligned = false;\n // Bump the epoch so any in-flight commit that peeked this shape BEFORE the reset skips its acks — the\n // post-reset buffers just installed above must survive to be committed on the follow-up pass.\n this.epochs.set(shapeName, this.epochFor(shapeName) + 1);\n }\n\n /**\n * The lowest EFFECTIVE complete frontier across all shapes — the atomic group commit target. A shape's\n * effective frontier is `max(completeLsnFor(shape), commitFloorFor(shape))` (ADR-0031): the raw dedup\n * frontier, raised by any aligned commit floor. Aligning the floors up to the freshest asserted global\n * head lets a group whose quiet shapes reported a STALE cached catch-up watermark still commit a busy\n * shape's delivered changes at catch-up completion, instead of holding them until the quiet shapes'\n * first live long-poll. The floor never narrows what {@link ingestChange} accepts (that remains the raw\n * {@link completeLsns}), so a late sub-floor change is still ingested and then committed.\n */\n lowestCompleteLsn(): Lsn {\n let minimum: Lsn | null = null;\n for (const shapeName of this.completeLsns.keys()) {\n const effective = this.effectiveLsnFor(shapeName);\n if (minimum === null || effective < minimum) {\n minimum = effective;\n }\n }\n return minimum ?? BigInt(-1);\n }\n\n /**\n * Whether any shape has a buffered change entry at an LSN at or below `targetLsn` (ADR-0031). The commit\n * loop uses this to fire a commit for a LATE-arriving change that lands at or below an already-committed\n * target — possible exactly because the aligned commit floor lets {@link ingestChange} accept a change\n * below the floor while the group frontier already sits at (or above) it, so no new frontier advance\n * would otherwise trigger a commit for it.\n */\n hasBufferedChangesAtOrBelow(targetLsn: Lsn): boolean {\n for (const shapeChanges of this.changes.values()) {\n for (const lsn of shapeChanges.keys()) {\n if (lsn <= targetLsn) {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Peek — WITHOUT removing — every buffered change at or below `targetLsn`, per shape, in buffered-LSN\n * order. The returned map has an entry for every shape (an empty array where nothing peeked). Pairs\n * with {@link ackUpTo}: the commit path peeks, writes the batch inside its transaction, and acks\n * (removes) only after the transaction succeeds — so a failed/degraded commit (ADR-0009 decision 5)\n * holds the batch in the buffer rather than dropping it, and a newer LSN can never land over it.\n */\n peekUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {\n const peeked = new Map<string, ChangeMessage<Row<unknown>>[]>();\n\n for (const [shapeName, shapeChanges] of this.changes.entries()) {\n const messages: ChangeMessage<Row<unknown>>[] = [];\n for (const lsn of [...shapeChanges.keys()]) {\n if (lsn <= targetLsn) {\n for (const message of shapeChanges.get(lsn)!) {\n messages.push(message);\n }\n }\n }\n peeked.set(shapeName, messages);\n }\n\n return peeked;\n }\n\n /**\n * Remove every buffered change at or below `targetLsn` (call only after the commit that consumed a\n * matching {@link peekUpTo} succeeded). `epochsAtPeek` maps each shape to its {@link epochFor} captured\n * at peek time; a shape whose epoch has since changed is **skipped entirely**.\n *\n * The epoch guard is load-bearing under a frontier REWIND. In the steady state, the frontier only\n * advances, so nothing new at or below `targetLsn` can be buffered between peek and ack. But a mid-commit\n * {@link resetShape} (must-refetch) rewinds a shape's frontier to -1 and lets its re-snapshot buffer at\n * LSN 0 — content that was NOT in this commit's peek. Deleting it here (LSN 0 ≤ `targetLsn`) would drop\n * the rebuild; the epoch bump makes this no-op for that shape so the reset's own rebuild path owns it.\n */\n ackUpTo(targetLsn: Lsn, epochsAtPeek: Map<string, number>): void {\n for (const [shapeName, shapeChanges] of this.changes.entries()) {\n const peekEpoch = epochsAtPeek.get(shapeName);\n if (peekEpoch !== undefined && this.epochFor(shapeName) !== peekEpoch) {\n continue;\n }\n for (const lsn of [...shapeChanges.keys()]) {\n if (lsn <= targetLsn) {\n shapeChanges.delete(lsn);\n }\n }\n }\n }\n\n /** Snapshot every shape's current {@link epochFor} — captured at peek time and passed to the acks. */\n snapshotEpochs(): Map<string, number> {\n return new Map([...this.epochs.keys()].map((shapeName) => [shapeName, this.epochFor(shapeName)]));\n }\n\n /**\n * Remove and return every buffered change at or below `targetLsn`, per shape, in buffered-LSN order\n * ({@link peekUpTo} then {@link ackUpTo}). The returned map has an entry for every shape (an empty\n * array where nothing drained).\n */\n drainUpTo(targetLsn: Lsn): Map<string, ChangeMessage<Row<unknown>>[]> {\n const epochsAtPeek = this.snapshotEpochs();\n const drained = this.peekUpTo(targetLsn);\n this.ackUpTo(targetLsn, epochsAtPeek);\n return drained;\n }\n}\n\ntype Operation = \"insert\" | \"update\" | \"delete\";\n\n/**\n * A drained shape batch folded to **one net operation per primary key** (ADR-0014 decision 1).\n * Each PK appears in at most one of `inserts`/`updates`, and at most once in `deletes` — except a\n * *re-created* PK (`[delete, insert]`), which appears in both `deletes` and `inserts` so the bulk\n * apply clears the pre-existing row before inserting the new one. The Sync applier therefore runs\n * three bulk statements **in the order `deletes → inserts → updates`** (Phase 3): that ordering is\n * what makes a re-create safe, and every other PK is touched by exactly one statement, so the rest\n * of the order is irrelevant within the atomic commit.\n */\nexport interface FoldedShapeBatch {\n /** PKs to delete — net-`delete` keys, plus the clearing delete of each re-created key. */\n deletes: ChangeMessage<Row<unknown>>[];\n /** Full rows to insert — net-`insert` keys, plus each re-created key's new row (merged values). */\n inserts: InsertChangeMessage[];\n /** Merged partial updates — net-`update` keys (carry the PK plus the union of updated columns). */\n updates: ChangeMessage<Row<unknown>>[];\n}\n\n/** Clone a representative message, overriding its row value and operation (headers like LSN are kept). */\nfunction withValue(\n template: ChangeMessage<Row<unknown>>,\n value: Row<unknown>,\n operation: Operation,\n): ChangeMessage<Row<unknown>> {\n return { ...template, value, headers: { ...template.headers, operation } };\n}\n\n/** Shallow-merge the row values of an ordered op segment, last-write-wins per column. */\nfunction mergeValues(segment: ChangeMessage<Row<unknown>>[]): Row<unknown> {\n return Object.assign({}, ...segment.map((message) => message.value)) as Row<unknown>;\n}\n\n/**\n * Fold a drained shape batch (ordered by LSN, one shape) to one net operation per primary key\n * (ADR-0014 decision 1), so the read path can bulk-apply without the `UPDATE … FROM` / `INSERT …\n * SELECT json_to_recordset(…)` same-PK join hazard (those use **one arbitrary** matching row when\n * the source holds duplicate PKs). Each PK's ops are replayed in LSN order down to:\n *\n * - **trailing `delete`** ⇒ a single DELETE;\n * - **`insert` with no preceding delete**, then any updates ⇒ a single INSERT with merged values\n * (a *plain* insert — a genuine PK collision still surfaces, never a silent upsert, commit `de12bb6`);\n * - **only `update`s** ⇒ a single UPDATE with merged values;\n * - **re-created** (`[delete, … , insert, …]`, no trailing delete) ⇒ DELETE **and** INSERT, so the\n * pre-existing row is cleared first (faithful to the per-row `DELETE`-then-`INSERT`; a plain INSERT\n * would collide with the row the dropped delete was meant to remove);\n * - **`update` after a delete** (`[delete, update]` and kin) is malformed for a faithful stream\n * (an update asserts the row exists) ⇒ throw, surfacing stream corruption rather than silently\n * dropping it.\n *\n * Pure and dependency-free by design (ADR-0014 / ISS-06): property-tested against the oracle\n * *fold-then-bulk ≡ ordered per-row apply* over random same-PK sequences and random initial state.\n */\nexport function foldChangeBatch(messages: ChangeMessage<Row<unknown>>[]): FoldedShapeBatch {\n const groups = new Map<string, ChangeMessage<Row<unknown>>[]>();\n for (const message of messages) {\n let group = groups.get(message.key);\n if (!group) {\n group = [];\n groups.set(message.key, group);\n }\n group.push(message);\n }\n\n const folded: FoldedShapeBatch = { deletes: [], inserts: [], updates: [] };\n for (const [key, ops] of groups) {\n foldKey(key, ops, folded);\n }\n return folded;\n}\n\nfunction foldKey(key: string, ops: ChangeMessage<Row<unknown>>[], folded: FoldedShapeBatch): void {\n const lastDeleteIndex = ops.findLastIndex((message) => message.headers.operation === \"delete\");\n\n // A trailing delete is the net effect regardless of anything before it; emit one DELETE.\n if (lastDeleteIndex === ops.length - 1) {\n folded.deletes.push(ops[lastDeleteIndex]!);\n return;\n }\n\n // The net is decided by the segment after the last delete (or the whole sequence if none).\n const segment = ops.slice(lastDeleteIndex + 1);\n const merged = mergeValues(segment);\n const template = segment[segment.length - 1]!;\n const startsWithInsert = segment[0]!.headers.operation === \"insert\";\n const hadDelete = lastDeleteIndex >= 0;\n\n if (startsWithInsert) {\n if (hadDelete) {\n // Re-created: clear the pre-existing row, then insert the new one (DELETE before INSERT).\n folded.deletes.push(ops[lastDeleteIndex]!);\n }\n folded.inserts.push(withValue(template, merged, \"insert\") as InsertChangeMessage);\n return;\n }\n\n if (hadDelete) {\n throw new Error(`foldChangeBatch: malformed batch — update after delete for key ${JSON.stringify(key)}`);\n }\n folded.updates.push(withValue(template, merged, \"update\"));\n}\n",
121
+ "// The live-query DIFF machinery (ADR-0032 S2 §4). Two pure pieces sit either side of the bridge:\n// - {@link computeLiveDiff} (worker-side): turn a fresh ordered result-set into a {added, changed, removed}\n// diff against the previously-sent one, keyed by the query's PK — so only deltas cross the wire.\n// - {@link LiveRowsMaterializer} (tab-side): fold each diff back into an ordered array while preserving\n// row-object identity for unchanged rows (React memo bails on `===`).\n// Both are transport-free and worker-free, so they unit-test directly.\n\nimport type { LiveDiffPayload } from \"./protocol\";\n\n// A NUL separator — never a legitimate character inside a PK text value, so composite keys can't collide.\nconst KEY_SEP = String.fromCharCode(0);\n\n/**\n * The stable key for a result row (§4). With `pkColumns`, join their values (composite-safe) — this is the\n * diff-keying identity, so a row whose PK is unchanged is the SAME logical row even if other columns moved.\n * Without `pkColumns` (a keyless query) fall back to the whole-row JSON value: still diff-shaped (never a\n * full resend), but an update surfaces as remove+add rather than a `changed` — the documented keyless\n * fallback. Duplicate identical keyless rows collapse under this scheme (accepted for the fallback).\n */\nexport function rowKey(row: Record<string, unknown>, pkColumns: readonly string[] | undefined): string {\n if (pkColumns && pkColumns.length > 0) {\n return pkColumns.map((col) => String(row[col])).join(KEY_SEP);\n }\n return JSON.stringify(row);\n}\n\n/** A shallow value-equality over a row's own enumerable keys — decides `changed` vs unchanged in a diff. */\nfunction rowsEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.is(a[key], b[key])) return false;\n }\n return true;\n}\n\n/** The worker's per-subscription memory: the last delivered rows keyed by {@link rowKey}, in delivered order. */\nexport interface LiveDiffState {\n pkColumns?: readonly string[];\n /** key → the exact row body last sent, so the next diff can detect `changed` and skip unchanged rows. */\n previous: Map<string, Record<string, unknown>>;\n}\n\n/** Seed the diff state from the initial snapshot (which the worker sends verbatim, not as a diff). */\nexport function seedLiveDiffState(\n rows: readonly Record<string, unknown>[],\n pkColumns: readonly string[] | undefined,\n): LiveDiffState {\n const previous = new Map<string, Record<string, unknown>>();\n for (const row of rows) previous.set(rowKey(row, pkColumns), row);\n return { ...(pkColumns ? { pkColumns } : {}), previous };\n}\n\n/**\n * Diff a fresh ordered result set against the state's previous set, MUTATING the state to the new set and\n * returning the wire diff (§4). `order` is every key in the new ORDER BY order (keys only — cheap); `added`/\n * `changed` carry the delta row BODIES; `removed` carries dropped keys. Never emits the full result set: a\n * single-row change yields one `changed` and the (key-only) `order`.\n */\nexport function computeLiveDiff(\n state: LiveDiffState,\n nextRows: readonly Record<string, unknown>[],\n): Omit<LiveDiffPayload, \"queryId\"> {\n const order: string[] = [];\n const added: { key: string; row: Record<string, unknown> }[] = [];\n const changed: { key: string; row: Record<string, unknown> }[] = [];\n const nextKeys = new Set<string>();\n const nextMap = new Map<string, Record<string, unknown>>();\n\n for (const row of nextRows) {\n const key = rowKey(row, state.pkColumns);\n // A duplicate key within one result set (composite PK not actually unique, or a keyless collision):\n // keep the first, so `order`/diff stay a faithful set. Rare; the read projections are PK-unique.\n if (nextKeys.has(key)) continue;\n nextKeys.add(key);\n nextMap.set(key, row);\n order.push(key);\n\n const prior = state.previous.get(key);\n if (prior === undefined) {\n added.push({ key, row });\n } else if (!rowsEqual(prior, row)) {\n changed.push({ key, row });\n }\n }\n\n const removed: string[] = [];\n for (const key of state.previous.keys()) {\n if (!nextKeys.has(key)) removed.push(key);\n }\n\n state.previous = nextMap;\n return { order, added, changed, removed };\n}\n\n/**\n * The tab-side fold of live diffs into an ordered row array with STABLE object identity (§4). The initial\n * snapshot seeds the cache; each diff rebuilds the array from `diff.order`, reusing the cached object for\n * any key not in `added`/`changed` (so an unchanged row keeps `===` and a memoized React row skips its\n * re-render), and installing a fresh object for added/changed keys. Order is exactly `diff.order` — the\n * query's ORDER BY as delivered by the worker.\n */\nexport class LiveRowsMaterializer<TRow extends Record<string, unknown> = Record<string, unknown>> {\n private byKey = new Map<string, TRow>();\n private rows: TRow[] = [];\n private readonly pkColumns: readonly string[] | undefined;\n\n constructor(pkColumns: readonly string[] | undefined) {\n this.pkColumns = pkColumns;\n }\n\n /** Seed from the initial snapshot; returns the initial ordered rows (each a distinct cached object). */\n seed(initialRows: readonly TRow[]): TRow[] {\n this.byKey = new Map();\n this.rows = [];\n for (const row of initialRows) {\n const key = rowKey(row, this.pkColumns);\n this.byKey.set(key, row);\n this.rows.push(row);\n }\n return this.rows;\n }\n\n /** Apply a diff; returns the new ordered array (a fresh array, but unchanged rows keep their object identity). */\n apply(diff: Omit<LiveDiffPayload, \"queryId\">): TRow[] {\n for (const key of diff.removed) this.byKey.delete(key);\n for (const { key, row } of diff.added) this.byKey.set(key, row as TRow);\n for (const { key, row } of diff.changed) this.byKey.set(key, row as TRow);\n // Rebuild strictly from the delivered order, reusing whatever object each key now maps to. Added/changed\n // keys already point at fresh objects (set above); every other key keeps its prior object (=== holds).\n this.rows = diff.order.map((key) => this.byKey.get(key)!).filter((row): row is TRow => row !== undefined);\n return this.rows;\n }\n\n /** The current ordered rows (identity-stable across `apply` calls for unchanged rows). */\n current(): TRow[] {\n return this.rows;\n }\n}\n",
122
+ "import { Column, is, SQL } from \"drizzle-orm\";\n\n/** The `{ fieldKey: Column | SQL | nested }` map carried on a Drizzle select at `query._.selectedFields`. */\nexport type SelectedFields = Record<string, unknown>;\n\n/**\n * Map a raw PGlite live-query row onto a Drizzle select's field keys.\n *\n * `useLiveDrizzleRows` feeds the builder's `.toSQL()` straight into PGlite's `live.query`, which\n * returns rows keyed by the **underlying column names** (snake_case) — `select({ assigneeId })`\n * produces SQL `select \"assignee_id\"`, so the raw row is `{ assignee_id }`, not `{ assigneeId }`.\n * Drizzle's own execution would remap these by position; the live query bypasses that, so this does it\n * by name using the select's field metadata:\n *\n * - a {@link Column} carries its DB `name`, so the value is read from `row[column.name]`;\n * - an {@link SQL} / aliased expression is aliased to its key in the generated SQL, so read `row[key]`;\n * - a nested selection object recurses;\n * - with no field map (a raw query) the row is returned unchanged.\n */\nexport function remapLiveRow(\n selectedFields: SelectedFields | undefined,\n row: Record<string, unknown>,\n): Record<string, unknown> {\n if (selectedFields == null) return row;\n const out: Record<string, unknown> = {};\n for (const [key, field] of Object.entries(selectedFields)) {\n if (is(field, Column)) {\n out[key] = row[field.name];\n } else if (is(field, SQL) || is(field, SQL.Aliased)) {\n out[key] = row[key];\n } else if (field != null && typeof field === \"object\") {\n out[key] = remapLiveRow(field as SelectedFields, row);\n } else {\n out[key] = row[key];\n }\n }\n return out;\n}\n"
6
123
  ],
7
- "mappings": ";;AACA;AAAA;AAuBO,SAAS,qBAA0D,GAAG;AAAA,EAC3E,MAAM,oBAAoB,cAA4C,IAAI;AAAA,EAI1E,SAAS,kBAAkB,GAAG,QAAQ,YAA2E;AAAA,IAC/G,uBAAO,OAAuD,kBAAkB,UAAzE;AAAA,MAA4B,OAAO;AAAA,MAAnC;AAAA,wCAAuD;AAAA;AAAA,EAGhE,SAAS,aAAa,GAA0B;AAAA,IAC9C,MAAM,SAAS,WAAW,iBAAiB;AAAA,IAC3C,IAAI,UAAU,MAAM;AAAA,MAClB,MAAM,IAAI,MAAM,sEAAsE;AAAA,IACxF;AAAA,IACA,OAAO;AAAA;AAAA,EAKT,SAAS,WAA2E,CAClF,OACA,SAMyD;AAAA,IACzD,MAAM,gBAAgB,WAAW,iBAAiB;AAAA,IAClD,MAAM,SAAS,SAAS,UAAU,eAAe;AAAA,IACjD,MAAM,QAAQ,SAAS,SAAS;AAAA,IAEhC,MAAM,YAAY,KAAK,UAAU,SAAS,UAAU,CAAC,CAAC;AAAA,IACtD,MAAM,eAAe,QAAmB,MAAM,KAAK,MAAM,SAAS,GAAgB,CAAC,SAAS,CAAC;AAAA,IAE7F,OAAO,OAAO,YAAY,SAAkE;AAAA,MAC1F,MAAM,CAAC;AAAA,MACP,SAAS;AAAA,MACT,OAAO;AAAA,IACT,CAAC;AA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