@forinda/kickjs-db 5.2.2 → 5.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/snapshot/extract.ts","../src/snapshot/render.ts","../src/diff/engine.ts","../src/diff/invert.ts","../src/errors.ts","../src/migrate/errors.ts","../src/migrate/journal.ts","../src/migrate/schema.ts","../src/migrate/memory-adapter.ts","../src/migrate/introspect-pg.ts","../src/migrate/drift.ts","../src/migrate/runner.ts","../src/adapter.ts","../src/tokens.ts","../src/client/events.ts","../src/custom-type.ts","../src/client/codec-plugin.ts","../src/extend/result-plugin.ts","../src/extend/apply.ts","../src/client/wrap.ts","../src/client/create.ts","../src/emit/identifiers.ts","../src/emit/pg.ts","../src/cli/config.ts","../src/cli/generate.ts","../src/dsl/columns/builders.ts","../src/dsl/table.ts","../src/dsl/constraints.ts","../src/dsl/relations.ts"],"sourcesContent":["import type { ColumnBuilder } from '../dsl/columns/types'\nimport type { TableDecl } from '../dsl/table'\nimport type {\n Dialect,\n EnumSnapshot,\n ForeignKeySnapshot,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n} from './types'\n\ninterface MaybeTable {\n __isTable?: boolean\n __name?: string\n __columns?: Record<string, ColumnBuilder>\n __indexes?: IndexSnapshot[]\n}\n\nfunction isTable(v: unknown): v is TableDecl<string, Record<string, ColumnBuilder>> {\n return Boolean(v && typeof v === 'object' && (v as MaybeTable).__isTable === true)\n}\n\n/**\n * pgEnum() returns a function with `enumName` + `values` attached.\n * Detect via duck-typing rather than `instanceof` so the snapshot\n * code stays decoupled from the PG-specific module — the snapshot\n * pipeline runs for every dialect.\n */\ninterface MaybePgEnum {\n enumName?: unknown\n values?: unknown\n}\n\nfunction isPgEnum(v: unknown): v is { enumName: string; values: readonly string[] } {\n if (typeof v !== 'function') return false\n const f = v as MaybePgEnum\n return typeof f.enumName === 'string' && Array.isArray(f.values)\n}\n\nexport function extractSnapshot(schema: Record<string, unknown>, dialect: Dialect): SchemaSnapshot {\n const tables: Record<string, TableSnapshot> = {}\n const enums: Record<string, EnumSnapshot> = {}\n\n for (const value of Object.values(schema)) {\n if (isTable(value)) {\n tables[value.__name] = extractTable(value)\n } else if (isPgEnum(value)) {\n enums[value.enumName] = { name: value.enumName, values: [...value.values] }\n }\n }\n\n // Only carry `enums` on PG snapshots — other dialects don't define\n // them and an empty record would just bloat the diff output.\n if (dialect === 'postgres' && Object.keys(enums).length > 0) {\n return { version: 1, dialect, tables, enums }\n }\n return { version: 1, dialect, tables }\n}\n\nfunction extractTable(t: TableDecl<string, Record<string, ColumnBuilder>>): TableSnapshot {\n const columns: TableSnapshot['columns'] = {}\n const indexes: IndexSnapshot[] = [...t.__indexes]\n const foreignKeys: ForeignKeySnapshot[] = []\n\n for (const [colKey, builder] of Object.entries(t.__columns)) {\n columns[colKey] = builder.toJSON(colKey)\n const state = builder.__state()\n if (state.unique) {\n indexes.push({\n name: `${t.__name}_${colKey}_unique`,\n columns: [colKey],\n unique: true,\n })\n }\n if (state.references) {\n // Resolve the FK thunk lazily — by extract time the table const has\n // been bound, so self-references (`() => self.id`) work.\n const ref = state.references.thunk()\n foreignKeys.push({\n name: `${t.__name}_${colKey}_fk`,\n columns: [colKey],\n refTable: ref.__tableName,\n refColumns: [ref.__name],\n onDelete: state.references.onDelete,\n onUpdate: state.references.onUpdate,\n })\n }\n }\n\n return { name: t.__name, columns, indexes, foreignKeys, checks: [] }\n}\n","import type {\n ColumnSnapshot,\n ForeignKeySnapshot,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n} from './types'\n\n/**\n * Render a SchemaSnapshot to TypeScript source matching the kickjs-db DSL.\n * Inverse of extractSnapshot().\n *\n * Naming: tables become exported `const`s with the same name. Constants\n * starting with digits get an underscore prefix to stay JS-valid.\n *\n * Limits (M1 — refined in M2/M3):\n * - No relations() emission. Adopter adds them manually post-introspect.\n * - No checks (M1 doesn't model CHECK constraints in the snapshot).\n * - Default values pass through as-is. The DSL accepts string defaults,\n * so 'true' / 'CURRENT_TIMESTAMP' / \"'foo'\" all round-trip.\n * - Auto-derived constraint names (`<table>_<col>_unique`, `<table>_<col>_fk`)\n * are detected and rendered as the chained .unique() / .references() form.\n * Custom-named constraints fall back to the third-arg callback / FK helper.\n */\nexport function renderSchemaSource(snapshot: SchemaSnapshot): string {\n const usedColumnHelpers = new Set<string>()\n const tableSources: string[] = []\n\n // First pass: render every table, accumulating which column helpers we used.\n for (const table of Object.values(snapshot.tables)) {\n tableSources.push(renderTable(table, usedColumnHelpers))\n }\n\n const helpers = ['table', ...Array.from(usedColumnHelpers).toSorted()]\n // Common constraint helpers used by tables with secondary objects.\n const needsIndex = Object.values(snapshot.tables).some((t) =>\n t.indexes.some((i) => !isAutoUniqueName(t.name, i)),\n )\n if (needsIndex) helpers.push('index')\n const needsUnique = Object.values(snapshot.tables).some((t) =>\n t.indexes.some((i) => i.unique && !isAutoUniqueName(t.name, i)),\n )\n if (needsUnique && !helpers.includes('unique')) helpers.push('unique')\n\n const importLine = `import { ${helpers.join(', ')} } from '@forinda/kickjs-db'`\n return [importLine, '', ...tableSources].join('\\n').trimEnd() + '\\n'\n}\n\nfunction renderTable(table: TableSnapshot, helpers: Set<string>): string {\n const ident = jsIdent(table.name)\n const columns: string[] = []\n for (const col of Object.values(table.columns)) {\n const fk = table.foreignKeys.find(\n (f) =>\n f.columns.length === 1 &&\n f.columns[0] === col.name &&\n f.name === `${table.name}_${col.name}_fk`,\n )\n const inlineUnique =\n table.indexes.find(\n (i) =>\n i.unique &&\n i.columns.length === 1 &&\n i.columns[0] === col.name &&\n isAutoUniqueName(table.name, i),\n ) !== undefined\n columns.push(` ${jsKey(col.name)}: ${renderColumn(col, helpers, fk, inlineUnique)},`)\n }\n\n // Constraints that don't fit on a column chain.\n const explicitIndexes = table.indexes.filter((i) => !isAutoUniqueName(table.name, i))\n const explicitFks = table.foreignKeys.filter(\n (f) => f.name !== `${table.name}_${f.columns[0]}_fk` || f.columns.length !== 1,\n )\n\n const hasThirdArg = explicitIndexes.length > 0\n const tableArgs: string[] = [`'${table.name}'`, `{\\n${columns.join('\\n')}\\n}`]\n\n if (hasThirdArg) {\n const callbacks = explicitIndexes\n .map((i) => ` ${jsKey(i.name)}: ${renderIndexCall(i)}`)\n .join(',\\n')\n tableArgs.push(`(t) => ({\\n${callbacks},\\n })`)\n }\n\n let src = `export const ${ident} = table(${tableArgs.join(', ')})`\n\n // Explicit FKs that don't fit the auto-derived <table>_<col>_fk pattern get\n // logged as TODO comments — adopter handles them manually. M3 may upgrade\n // this to emit a separate ALTER snippet.\n if (explicitFks.length > 0) {\n src +=\n '\\n// TODO: kick db introspect — composite or custom-named foreign keys not auto-rendered:\\n'\n for (const f of explicitFks) {\n src += `// ${f.name}: (${f.columns.join(', ')}) → ${f.refTable}(${f.refColumns.join(', ')})\\n`\n }\n }\n\n return src\n}\n\nfunction renderColumn(\n col: ColumnSnapshot,\n helpers: Set<string>,\n fk: ForeignKeySnapshot | undefined,\n inlineUnique: boolean,\n): string {\n const { helperName, args } = pickColumnHelper(col)\n helpers.add(helperName)\n\n let chain = `${helperName}(${args})`\n if (col.primaryKey) chain += '.primaryKey()'\n if (!col.primaryKey && !col.nullable) chain += '.notNull()'\n if (col.default !== null) chain += `.default(${JSON.stringify(col.default)})`\n if (inlineUnique) chain += '.unique()'\n if (fk) {\n const ref = `${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`\n const onDelete = fk.onDelete === 'no_action' ? '' : `, { onDelete: '${fk.onDelete}' }`\n chain += `.references(() => ${ref}${onDelete})`\n }\n return chain\n}\n\nfunction pickColumnHelper(col: ColumnSnapshot): { helperName: string; args: string } {\n // Strip array suffix; render as base type + .array() chain in renderColumn\n // (M2 — for now arrays land as a literal `<T>[]` type which the DSL doesn't\n // round-trip). For M1, just pick the closest helper.\n const t = col.type\n\n if (t === 'serial') return { helperName: 'serial', args: '' }\n if (t === 'bigserial') return { helperName: 'bigSerial', args: '' }\n if (t === 'smallserial') return { helperName: 'serial', args: '' }\n if (t === 'integer') return { helperName: 'integer', args: '' }\n if (t === 'bigint') return { helperName: 'bigint', args: '' }\n if (t === 'smallint') return { helperName: 'smallint', args: '' }\n if (t === 'real') return { helperName: 'real', args: '' }\n if (t === 'double precision') return { helperName: 'doublePrecision', args: '' }\n if (/^numeric(\\(.+\\))?$/.test(t)) return { helperName: 'numeric', args: extractParens(t) }\n if (/^varchar(\\(\\d+\\))?$/.test(t)) return { helperName: 'varchar', args: extractParens(t) }\n if (/^char(\\(\\d+\\))?$/.test(t)) return { helperName: 'char', args: extractParens(t) }\n if (t === 'text') return { helperName: 'text', args: '' }\n if (t === 'boolean') return { helperName: 'boolean', args: '' }\n if (t === 'timestamp') return { helperName: 'timestamp', args: '' }\n if (t === 'timestamptz') return { helperName: 'timestamptz', args: '' }\n if (t === 'date') return { helperName: 'date', args: '' }\n if (t === 'time') return { helperName: 'time', args: '' }\n if (t === 'interval') return { helperName: 'interval', args: '' }\n if (t === 'uuid') return { helperName: 'uuid', args: '' }\n if (t === 'jsonb') return { helperName: 'jsonb', args: '' }\n if (t === 'json') return { helperName: 'json', args: '' }\n if (t === 'bytea') return { helperName: 'bytea', args: '' }\n\n // Fallback: emit as a comment + placeholder text() so the file still\n // parses. Adopter edits to the right helper.\n return { helperName: 'text', args: `/* TODO: ${t} */` }\n}\n\nfunction extractParens(t: string): string {\n const m = t.match(/\\(([^)]+)\\)/)\n return m ? m[1] : ''\n}\n\nfunction renderIndexCall(idx: IndexSnapshot): string {\n const helper = idx.unique ? 'unique' : 'index'\n const cols = idx.columns.map((c) => `t.${jsIdent(c)}`).join(', ')\n return `${helper}('${idx.name}').on(${cols})`\n}\n\nfunction isAutoUniqueName(tableName: string, idx: IndexSnapshot): boolean {\n return (\n idx.unique && idx.columns.length === 1 && idx.name === `${tableName}_${idx.columns[0]}_unique`\n )\n}\n\n/** Make a JS-safe identifier from a snake_case column/table name. */\nfunction jsIdent(raw: string): string {\n if (/^[A-Za-z_$][\\w$]*$/.test(raw)) return raw\n // Prefix digits-leading names with underscore.\n return `_${raw.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Render a record key — quoted if not a valid identifier. */\nfunction jsKey(raw: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(raw) ? raw : JSON.stringify(raw)\n}\n","import type { SchemaSnapshot, TableSnapshot } from '../snapshot/types'\nimport type { Change, ChangeSet } from './types'\n\nexport function diff(prev: SchemaSnapshot, next: SchemaSnapshot): ChangeSet {\n const changes: Change[] = []\n\n const prevTables = new Set(Object.keys(prev.tables))\n const nextTables = new Set(Object.keys(next.tables))\n\n // Enum diffs run BEFORE table operations on the create side (so a new\n // table referencing a new enum sees the type already exist) and AFTER\n // table operations on the drop side (so a dropped enum can't have\n // dangling column references). Order: createEnum → addEnumValue →\n // table changes → dropEnum (appended at the end).\n diffEnumsCreatePhase(prev, next, changes)\n\n // Drops first (so FKs that depend on dropped tables are handled before drops below)\n for (const name of prevTables) {\n if (!nextTables.has(name)) {\n changes.push({ kind: 'dropTable', table: prev.tables[name] })\n }\n }\n\n // Creates — three passes so secondary objects only land after every new\n // table exists. Pass 1: every CREATE TABLE. Pass 2: every CREATE INDEX.\n // Pass 3: every ADD FOREIGN KEY. This keeps the order safe regardless of\n // ESM namespace iteration (which is alphabetical, not declaration order)\n // and lets each change kind map 1:1 to a SQL statement.\n const newTableNames = [...nextTables].filter((n) => !prevTables.has(n))\n for (const name of newTableNames) {\n changes.push({ kind: 'createTable', table: next.tables[name] })\n }\n for (const name of newTableNames) {\n for (const i of next.tables[name].indexes) {\n changes.push({ kind: 'addIndex', table: name, index: i })\n }\n }\n for (const name of newTableNames) {\n for (const f of next.tables[name].foreignKeys) {\n changes.push({ kind: 'addForeignKey', table: name, fk: f })\n }\n }\n\n // Common tables — column/index/fk diff comes in Tasks 10-12\n for (const name of nextTables) {\n if (!prevTables.has(name)) continue\n diffTable(prev.tables[name], next.tables[name], changes)\n }\n\n // Drop enums after every dependent table change has been emitted.\n diffEnumsDropPhase(prev, next, changes)\n\n return changes\n}\n\nfunction diffEnumsCreatePhase(prev: SchemaSnapshot, next: SchemaSnapshot, changes: Change[]) {\n const prevEnums = prev.enums ?? {}\n const nextEnums = next.enums ?? {}\n\n // New enums first.\n for (const [name, e] of Object.entries(nextEnums)) {\n if (prevEnums[name]) continue\n changes.push({ kind: 'createEnum', enum: e })\n }\n\n // ALTER TYPE ADD VALUE for non-destructive value additions on\n // existing enums. Removed values are NOT round-trippable without\n // dropping every column that references the type — those surface\n // as a `removeEnumValue` advisory the emitter turns into a SQL\n // comment with explicit operator guidance.\n for (const [name, e] of Object.entries(nextEnums)) {\n const prior = prevEnums[name]\n if (!prior) continue\n const priorValues = new Set(prior.values)\n const nextValues = new Set(e.values)\n const nextValueList = e.values\n\n let lastInsertedAt = -1\n for (let i = 0; i < nextValueList.length; i++) {\n const value = nextValueList[i]\n if (priorValues.has(value)) {\n lastInsertedAt = i\n continue\n }\n // New value — emit ADD VALUE. PG honours the BEFORE clause so\n // we preserve the declaration order on existing values.\n const before = nextValueList[i + 1]\n const beforeIsExisting = before != null && priorValues.has(before)\n changes.push({\n kind: 'addEnumValue',\n enum: name,\n value,\n ...(beforeIsExisting ? { before } : {}),\n })\n void lastInsertedAt\n }\n\n // Removed values — collect in declaration order from the prior\n // snapshot so the emitter list matches the order the operator\n // originally wrote.\n const removed = prior.values.filter((v) => !nextValues.has(v))\n if (removed.length > 0) {\n changes.push({ kind: 'removeEnumValue', enum: name, removed })\n }\n }\n}\n\nfunction diffEnumsDropPhase(prev: SchemaSnapshot, next: SchemaSnapshot, changes: Change[]) {\n const prevEnums = prev.enums ?? {}\n const nextEnums = next.enums ?? {}\n for (const [name, e] of Object.entries(prevEnums)) {\n if (nextEnums[name]) continue\n changes.push({ kind: 'dropEnum', enum: e })\n }\n}\n\nfunction diffTable(prev: TableSnapshot, next: TableSnapshot, changes: Change[]) {\n const prevCols = new Map(Object.entries(prev.columns))\n const nextCols = new Map(Object.entries(next.columns))\n\n const drops: string[] = []\n const adds: string[] = []\n for (const c of prevCols.keys()) if (!nextCols.has(c)) drops.push(c)\n for (const c of nextCols.keys()) if (!prevCols.has(c)) adds.push(c)\n\n // Rename heuristic — pair only if exactly one drop + one add with identical attrs.\n if (drops.length === 1 && adds.length === 1) {\n const before = prevCols.get(drops[0])!\n const after = nextCols.get(adds[0])!\n if (columnAttrsEqual(before, after)) {\n changes.push({ kind: 'renameColumn', table: next.name, from: drops[0], to: adds[0] })\n drops.length = 0\n adds.length = 0\n }\n }\n\n for (const c of drops) {\n changes.push({ kind: 'dropColumn', table: next.name, column: prevCols.get(c)! })\n }\n for (const c of adds) {\n changes.push({ kind: 'addColumn', table: next.name, column: nextCols.get(c)! })\n }\n\n // Common columns — alter detection\n for (const c of nextCols.keys()) {\n if (!prevCols.has(c)) continue\n const before = prevCols.get(c)!\n const after = nextCols.get(c)!\n if (!columnsEqual(before, after)) {\n changes.push({ kind: 'alterColumn', table: next.name, column: c, before, after })\n }\n }\n\n diffByName(\n prev.indexes,\n next.indexes,\n (i) => changes.push({ kind: 'dropIndex', table: next.name, index: i }),\n (i) => changes.push({ kind: 'addIndex', table: next.name, index: i }),\n )\n\n diffByName(\n prev.foreignKeys,\n next.foreignKeys,\n (f) => changes.push({ kind: 'dropForeignKey', table: next.name, fk: f }),\n (f) => changes.push({ kind: 'addForeignKey', table: next.name, fk: f }),\n )\n}\n\nfunction diffByName<T extends { name: string }>(\n prev: T[],\n next: T[],\n onDrop: (item: T) => void,\n onAdd: (item: T) => void,\n) {\n const prevByName = new Map(prev.map((p) => [p.name, p]))\n const nextByName = new Map(next.map((n) => [n.name, n]))\n for (const [n, p] of prevByName) if (!nextByName.has(n)) onDrop(p)\n for (const [n, x] of nextByName) if (!prevByName.has(n)) onAdd(x)\n}\n\nfunction columnsEqual(\n a: import('../snapshot/types').ColumnSnapshot,\n b: import('../snapshot/types').ColumnSnapshot,\n): boolean {\n return (\n a.type === b.type &&\n a.nullable === b.nullable &&\n a.default === b.default &&\n a.primaryKey === b.primaryKey\n )\n}\n\nfunction columnAttrsEqual(\n a: import('../snapshot/types').ColumnSnapshot,\n b: import('../snapshot/types').ColumnSnapshot,\n): boolean {\n // Like columnsEqual but ignores name (since rename is *about* name change).\n return (\n a.type === b.type &&\n a.nullable === b.nullable &&\n a.default === b.default &&\n a.primaryKey === b.primaryKey\n )\n}\n","import type { Change, ChangeSet } from './types'\n\n/**\n * Reverse a forward ChangeSet so emitting it produces the SQL that undoes\n * the forward migration.\n *\n * The reverse of an *unambiguous* change is exact (rename → rename swapped,\n * add → drop, drop → add). The reverse of an *ambiguous* change (drop column,\n * drop table, type widen, NOT NULL gain without default) is a defensible\n * best-effort derived from the snapshot the forward change carried — the\n * runner refuses to apply a non-reviewed migration in non-dev so the operator\n * always sees the draft before it touches a DB.\n *\n * The order is reversed too: drop FK before drop index before drop table is\n * the safe sequence for tearing down what create-FK / create-index / create-\n * table built up.\n */\nexport function invertChanges(forward: ChangeSet): ChangeSet {\n const reversed: Change[] = []\n for (const change of forward) {\n reversed.push(invert(change))\n }\n return reversed.toReversed()\n}\n\nfunction invert(change: Change): Change {\n switch (change.kind) {\n case 'createTable':\n return { kind: 'dropTable', table: change.table }\n case 'dropTable':\n return { kind: 'createTable', table: change.table }\n case 'renameTable':\n return { kind: 'renameTable', from: change.to, to: change.from }\n case 'addColumn':\n return { kind: 'dropColumn', table: change.table, column: change.column }\n case 'dropColumn':\n return { kind: 'addColumn', table: change.table, column: change.column }\n case 'renameColumn':\n return {\n kind: 'renameColumn',\n table: change.table,\n from: change.to,\n to: change.from,\n }\n case 'alterColumn':\n return {\n kind: 'alterColumn',\n table: change.table,\n column: change.column,\n before: change.after,\n after: change.before,\n }\n case 'addIndex':\n return { kind: 'dropIndex', table: change.table, index: change.index }\n case 'dropIndex':\n return { kind: 'addIndex', table: change.table, index: change.index }\n case 'addForeignKey':\n return { kind: 'dropForeignKey', table: change.table, fk: change.fk }\n case 'dropForeignKey':\n return { kind: 'addForeignKey', table: change.table, fk: change.fk }\n case 'createEnum':\n return { kind: 'dropEnum', enum: change.enum }\n case 'dropEnum':\n return { kind: 'createEnum', enum: change.enum }\n case 'addEnumValue':\n // PG can't ALTER TYPE … DROP VALUE without recreating the type +\n // touching every column that uses it. Down-migrations carry the\n // forward change verbatim; the operator gets a draft + a clear\n // signal that the down won't auto-revert.\n return change\n case 'removeEnumValue':\n // The forward direction of a value removal is itself an\n // advisory + manual operation; the reverse is symmetric. Carry\n // the change verbatim so the down draft surfaces the same\n // SQL-comment guidance, with `removed` listing the values that\n // would need to be re-added.\n return change\n }\n}\n\n/**\n * Returns the change kinds that produce ambiguous reverses — drop column,\n * drop table, type widen — so the generator can flag the down.sql as a draft\n * even if every individual statement is technically valid SQL.\n */\nconst AMBIGUOUS_REVERSE_KINDS = new Set<Change['kind']>([\n 'dropTable',\n 'dropColumn',\n 'alterColumn',\n // PG enum value additions can't auto-reverse — drop-value isn't\n // supported without recreating the type. The down draft surfaces\n // the forward statement so the operator manually rewrites it.\n 'addEnumValue',\n // Removed values can't auto-reverse for the symmetric reason: the\n // value(s) that disappeared from the schema may have been held by\n // existing rows whose state is already gone. Down draft preserves\n // the advisory comment.\n 'removeEnumValue',\n])\n\nexport function hasAmbiguousReverse(forward: ChangeSet): boolean {\n return forward.some((c) => AMBIGUOUS_REVERSE_KINDS.has(c.kind))\n}\n","export class KickDbError extends Error {\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = this.constructor.name\n this.code = code\n }\n}\n","import { KickDbError } from '../errors'\n\nexport class MigrationError extends KickDbError {}\n\nexport class MigrationLockError extends MigrationError {\n constructor(message: string) {\n super('migration_lock_held', message)\n }\n}\n\nexport interface SchemaDiffSummary {\n added: string[]\n removed: string[]\n changed: string[]\n}\n\nexport class MigrationDriftError extends MigrationError {\n readonly diff: SchemaDiffSummary\n\n constructor(message: string, diff: SchemaDiffSummary) {\n super('migration_drift', message)\n this.diff = diff\n }\n}\n\nexport class MigrationHashError extends MigrationError {\n readonly id: string\n readonly expected: string\n readonly actual: string\n\n constructor(id: string, expected: string, actual: string) {\n super('migration_hash_mismatch', `Hash mismatch for migration ${id}`)\n this.id = id\n this.expected = expected\n this.actual = actual\n }\n}\n\nexport class UnreviewedMigrationError extends MigrationError {\n readonly id: string\n\n constructor(id: string) {\n super(\n 'migration_unreviewed',\n `Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`,\n )\n this.id = id\n }\n}\n","import { createHash } from 'node:crypto'\nimport { readFile, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\n\nimport type { Dialect } from '../snapshot/types'\n\nexport interface JournalEntry {\n id: string\n tag: string\n hash: string\n createdAt: string\n}\n\nexport interface Journal {\n version: 1\n dialect: Dialect\n entries: JournalEntry[]\n}\n\nconst FILE = '_journal.json'\n\nexport async function readJournal(migrationsDir: string, dialect: Dialect): Promise<Journal> {\n const file = path.join(migrationsDir, FILE)\n if (!existsSync(file)) {\n return { version: 1, dialect, entries: [] }\n }\n const raw = JSON.parse(await readFile(file, 'utf8'))\n if (raw.version !== 1) {\n throw new Error(`_journal.json version ${raw.version} unsupported (expected 1)`)\n }\n return raw\n}\n\nexport async function appendJournalEntry(\n migrationsDir: string,\n dialect: Dialect,\n entry: JournalEntry,\n): Promise<void> {\n const j = await readJournal(migrationsDir, dialect)\n j.entries.push(entry)\n const file = path.join(migrationsDir, FILE)\n await writeFile(file, JSON.stringify(j, null, 2) + '\\n', 'utf8')\n}\n\nexport async function computeMigrationHash(migrationDir: string): Promise<string> {\n const up = await readFile(path.join(migrationDir, 'up.sql'), 'utf8')\n const down = await readFile(path.join(migrationDir, 'down.sql'), 'utf8')\n const snap = await readFile(path.join(migrationDir, 'snapshot.json'), 'utf8')\n const h = createHash('sha256')\n .update(up)\n .update('|')\n .update(down)\n .update('|')\n .update(snap)\n .digest('hex')\n return `sha256:${h}`\n}\n\nexport async function verifyMigrationHash(\n migrationDir: string,\n expected: string,\n): Promise<boolean> {\n const actual = await computeMigrationHash(migrationDir)\n return actual === expected\n}\n","import type { Dialect } from '../snapshot/types'\n\nexport const KICK_MIGRATIONS_TABLE = 'kick_migrations'\nexport const KICK_LOCK_TABLE = 'kick_migrations_lock'\n\nexport function migrationsTableDdl(dialect: Dialect): string {\n switch (dialect) {\n case 'postgres':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}\" (\n \"id\" varchar(128) PRIMARY KEY,\n \"name\" text NOT NULL,\n \"hash\" text NOT NULL,\n \"batch\" integer NOT NULL,\n \"applied_at\" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \"direction\" varchar(8) NOT NULL DEFAULT 'up'\n );\n CREATE INDEX IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}_batch_idx\" ON \"${KICK_MIGRATIONS_TABLE}\" (\"batch\");`\n case 'sqlite':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}\" (\n \"id\" text PRIMARY KEY,\n \"name\" text NOT NULL,\n \"hash\" text NOT NULL,\n \"batch\" integer NOT NULL,\n \"applied_at\" text NOT NULL DEFAULT (datetime('now')),\n \"direction\" text NOT NULL DEFAULT 'up'\n );\n CREATE INDEX IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}_batch_idx\" ON \"${KICK_MIGRATIONS_TABLE}\" (\"batch\");`\n case 'mysql':\n return `CREATE TABLE IF NOT EXISTS \\`${KICK_MIGRATIONS_TABLE}\\` (\n \\`id\\` varchar(128) PRIMARY KEY,\n \\`name\\` text NOT NULL,\n \\`hash\\` text NOT NULL,\n \\`batch\\` int NOT NULL,\n \\`applied_at\\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \\`direction\\` varchar(8) NOT NULL DEFAULT 'up',\n INDEX \\`${KICK_MIGRATIONS_TABLE}_batch_idx\\` (\\`batch\\`)\n );`\n }\n}\n\nexport function lockTableDdl(dialect: Dialect): string {\n switch (dialect) {\n case 'postgres':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_LOCK_TABLE}\" (\n \"id\" smallint PRIMARY KEY,\n \"locked_at\" timestamptz,\n \"locked_by\" text\n );\n INSERT INTO \"${KICK_LOCK_TABLE}\" (\"id\") VALUES (1) ON CONFLICT DO NOTHING;`\n case 'sqlite':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_LOCK_TABLE}\" (\n \"id\" integer PRIMARY KEY,\n \"locked_at\" text,\n \"locked_by\" text\n );\n INSERT OR IGNORE INTO \"${KICK_LOCK_TABLE}\" (\"id\") VALUES (1);`\n case 'mysql':\n return `CREATE TABLE IF NOT EXISTS \\`${KICK_LOCK_TABLE}\\` (\n \\`id\\` smallint PRIMARY KEY,\n \\`locked_at\\` timestamp NULL,\n \\`locked_by\\` text\n );\n INSERT IGNORE INTO \\`${KICK_LOCK_TABLE}\\` (\\`id\\`) VALUES (1);`\n }\n}\n","import type { Dialect, SchemaSnapshot } from '../snapshot/types'\nimport type { MigrationAdapter, MigrationRow } from './adapter'\n\n/**\n * In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-\n * holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as\n * test-only stubs — the real DB-bound semantics are validated in db-pg's\n * integration tests, not here.\n */\nexport class MemoryMigrationAdapter implements MigrationAdapter {\n readonly dialect: Dialect = 'postgres'\n\n private rows: MigrationRow[] = []\n private locked: { by: string; at: string } | null = null\n private appliedSql: string[] = []\n private currentSchema: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n\n async ensureMigrationTables(): Promise<void> {\n /* no-op */\n }\n\n async listApplied(): Promise<MigrationRow[]> {\n return [...this.rows]\n }\n\n async recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void> {\n this.rows.push({ ...row, appliedAt: new Date().toISOString() })\n }\n\n async removeApplied(id: string): Promise<void> {\n this.rows = this.rows.filter((r) => r.id !== id)\n }\n\n async acquireLock(owner: string): Promise<boolean> {\n if (this.locked) return false\n this.locked = { by: owner, at: new Date().toISOString() }\n return true\n }\n\n async releaseLock(): Promise<void> {\n this.locked = null\n }\n\n async applySqlInTx(sql: string): Promise<void> {\n this.appliedSql.push(sql)\n }\n\n async applySqlNoTx(sql: string): Promise<void> {\n this.appliedSql.push(sql)\n }\n\n async introspect(): Promise<SchemaSnapshot> {\n return this.currentSchema\n }\n\n async close(): Promise<void> {\n /* no-op */\n }\n\n /** Test-only setter — let drift tests stage a \"live\" schema state. */\n __setIntrospectedSchema(snap: SchemaSnapshot): void {\n this.currentSchema = snap\n }\n\n /** Test-only inspector — what SQL we received. */\n __appliedSql(): readonly string[] {\n return this.appliedSql\n }\n}\n","import type {\n ForeignKeySnapshot,\n FkAction,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n} from '../snapshot/types'\nimport type { IntrospectPgOptions, PgQueryRunner } from './introspect-types'\n\nconst DEFAULT_EXCLUDED = ['kick_migrations', 'kick_migrations_lock']\n\ninterface ColumnRow {\n column_name: string\n data_type: string\n udt_name: string\n is_nullable: 'YES' | 'NO'\n column_default: string | null\n character_maximum_length: number | null\n numeric_precision: number | null\n numeric_scale: number | null\n}\n\ninterface IndexRow {\n index_name: string\n column_name: string\n is_unique: boolean\n is_primary: boolean\n}\n\ninterface FkRow {\n constraint_name: string\n column_name: string\n ref_table: string\n ref_column: string\n delete_rule: string\n update_rule: string\n}\n\nexport async function introspectPg(\n client: PgQueryRunner,\n opts: IntrospectPgOptions = {},\n): Promise<SchemaSnapshot> {\n const schema = opts.schema ?? 'public'\n const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED\n\n const tableRows = await client.query<{ table_name: string }>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1 AND table_type = 'BASE TABLE'\n ORDER BY table_name`,\n [schema],\n )\n\n const tables: Record<string, TableSnapshot> = {}\n for (const t of tableRows.rows) {\n if (excluded.includes(t.table_name)) continue\n tables[t.table_name] = {\n name: t.table_name,\n columns: await readColumns(client, schema, t.table_name),\n indexes: await readIndexes(client, schema, t.table_name),\n foreignKeys: await readForeignKeys(client, schema, t.table_name),\n checks: [],\n }\n }\n return { version: 1, dialect: 'postgres', tables }\n}\n\nasync function readColumns(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<TableSnapshot['columns']> {\n const cols = await client.query<ColumnRow>(\n `SELECT column_name, data_type, udt_name, is_nullable, column_default,\n character_maximum_length, numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema = $1 AND table_name = $2\n ORDER BY ordinal_position`,\n [schema, table],\n )\n\n const pkCols = await client.query<{ column_name: string }>(\n `SELECT k.column_name\n FROM information_schema.table_constraints c\n JOIN information_schema.key_column_usage k\n ON k.constraint_name = c.constraint_name\n AND k.table_schema = c.table_schema\n WHERE c.table_schema = $1 AND c.table_name = $2 AND c.constraint_type = 'PRIMARY KEY'\n ORDER BY k.ordinal_position`,\n [schema, table],\n )\n const pkSet = new Set(pkCols.rows.map((r) => r.column_name))\n\n const out: TableSnapshot['columns'] = {}\n for (const r of cols.rows) {\n const isSerial = isSerialColumn(r)\n out[r.column_name] = {\n name: r.column_name,\n type: isSerial ? serialTypeFor(r) : normalizeType(r),\n nullable: r.is_nullable === 'YES',\n // serial columns own their nextval default; collapse it to keep round-\n // trips (DSL → emit → introspect) idempotent.\n default: isSerial ? null : normalizeDefault(r.column_default),\n primaryKey: pkSet.has(r.column_name),\n }\n }\n return out\n}\n\nfunction isSerialColumn(r: ColumnRow): boolean {\n if (!r.column_default) return false\n if (!r.column_default.startsWith('nextval(')) return false\n return r.udt_name === 'int2' || r.udt_name === 'int4' || r.udt_name === 'int8'\n}\n\nfunction serialTypeFor(r: ColumnRow): string {\n if (r.udt_name === 'int8') return 'bigserial'\n if (r.udt_name === 'int2') return 'smallserial'\n return 'serial'\n}\n\nfunction normalizeType(r: ColumnRow): string {\n // Map PG's information_schema data_type back to the DSL surface.\n if (r.data_type === 'character varying') {\n return r.character_maximum_length ? `varchar(${r.character_maximum_length})` : 'varchar'\n }\n if (r.data_type === 'character') {\n return r.character_maximum_length ? `char(${r.character_maximum_length})` : 'char(1)'\n }\n if (r.data_type === 'numeric') {\n if (r.numeric_precision !== null && r.numeric_scale !== null) {\n return `numeric(${r.numeric_precision}, ${r.numeric_scale})`\n }\n if (r.numeric_precision !== null) return `numeric(${r.numeric_precision})`\n return 'numeric'\n }\n if (r.data_type === 'timestamp with time zone') return 'timestamptz'\n if (r.data_type === 'timestamp without time zone') return 'timestamp'\n if (r.data_type === 'time without time zone') return 'time'\n if (r.data_type === 'double precision') return 'double precision'\n if (r.data_type === 'USER-DEFINED') return r.udt_name\n if (r.data_type === 'ARRAY') {\n // udt_name for arrays is _<element>; strip and append [].\n const elem = r.udt_name.replace(/^_/, '')\n return `${elem}[]`\n }\n // bigint, integer, smallint, text, boolean, date, json, jsonb, bytea, uuid,\n // interval, etc — pass through as data_type when it matches the DSL.\n return r.data_type\n}\n\nfunction normalizeDefault(raw: string | null): string | null {\n if (!raw) return null\n // Strip PG's :: cast suffixes: 'true'::boolean → true, 'foo'::text → 'foo'\n const stripped = raw.replace(/::[\\w\" ]+(\\([^)]*\\))?$/, '')\n // Normalize CURRENT_TIMESTAMP / now() to the DSL canonical token.\n const upper = stripped.toUpperCase()\n if (upper === 'NOW()' || upper === 'CURRENT_TIMESTAMP') return 'CURRENT_TIMESTAMP'\n if (upper === 'GEN_RANDOM_UUID()') return 'gen_random_uuid()'\n // 'foo' literal → foo. true / false / numeric pass through.\n return stripped.replace(/^'(.*)'$/, '$1')\n}\n\nasync function readIndexes(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<IndexSnapshot[]> {\n const rows = await client.query<IndexRow>(\n `SELECT i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique AS is_unique,\n ix.indisprimary AS is_primary\n FROM pg_class t\n JOIN pg_namespace n ON n.oid = t.relnamespace\n JOIN pg_index ix ON ix.indrelid = t.oid\n JOIN pg_class i ON i.oid = ix.indexrelid\n JOIN unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) ON true\n JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum\n WHERE n.nspname = $1 AND t.relname = $2 AND t.relkind = 'r'\n ORDER BY i.relname, k.ord`,\n [schema, table],\n )\n\n // Group rows by index_name, preserve column order.\n type Tagged = IndexSnapshot & { _isPrimary: boolean }\n const byIndex = new Map<string, Tagged>()\n for (const r of rows.rows) {\n let entry = byIndex.get(r.index_name)\n if (!entry) {\n entry = {\n name: r.index_name,\n columns: [],\n unique: r.is_unique,\n _isPrimary: r.is_primary,\n }\n byIndex.set(r.index_name, entry)\n }\n entry.columns.push(r.column_name)\n }\n\n // Drop PK-backing indexes — primaryKey is recorded on the column itself.\n return [...byIndex.values()]\n .filter((i) => !i._isPrimary)\n .map(({ _isPrimary, ...rest }) => rest)\n .toSorted((a, b) => a.name.localeCompare(b.name))\n}\n\nasync function readForeignKeys(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<ForeignKeySnapshot[]> {\n const rows = await client.query<FkRow>(\n `SELECT tc.constraint_name,\n kcu.column_name,\n ccu.table_name AS ref_table,\n ccu.column_name AS ref_column,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON kcu.constraint_name = tc.constraint_name\n AND kcu.table_schema = tc.table_schema\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = rc.unique_constraint_name\n AND ccu.constraint_schema = rc.unique_constraint_schema\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, table],\n )\n\n const byName = new Map<string, ForeignKeySnapshot>()\n for (const r of rows.rows) {\n let fk = byName.get(r.constraint_name)\n if (!fk) {\n fk = {\n name: r.constraint_name,\n columns: [],\n refTable: r.ref_table,\n refColumns: [],\n onDelete: mapFkAction(r.delete_rule),\n onUpdate: mapFkAction(r.update_rule),\n }\n byName.set(r.constraint_name, fk)\n }\n fk.columns.push(r.column_name)\n fk.refColumns.push(r.ref_column)\n }\n return [...byName.values()].toSorted((a, b) => a.name.localeCompare(b.name))\n}\n\nfunction mapFkAction(raw: string): FkAction {\n switch (raw.toUpperCase()) {\n case 'CASCADE':\n return 'cascade'\n case 'RESTRICT':\n return 'restrict'\n case 'SET NULL':\n return 'set_null'\n case 'SET DEFAULT':\n return 'set_default'\n case 'NO ACTION':\n default:\n return 'no_action'\n }\n}\n","import { diff } from '../diff/engine'\nimport type { Change } from '../diff/types'\nimport type { SchemaSnapshot } from '../snapshot/types'\nimport { MigrationDriftError, type SchemaDiffSummary } from './errors'\n\nexport type DriftBehavior = 'error' | 'warn' | 'ignore'\n\nexport interface DriftLogger {\n warn: (message: string) => void\n}\n\nexport async function checkDrift(\n liveSnapshot: SchemaSnapshot,\n expectedSnapshot: SchemaSnapshot,\n behavior: DriftBehavior,\n log: DriftLogger = console,\n): Promise<void> {\n if (behavior === 'ignore') return\n // diff(prev, next) reads expected as `prev` and live as `next` so 'added'\n // means \"live has it but the snapshot doesn't\" — i.e. someone ran DDL\n // outside the migration runner.\n const changes = diff(expectedSnapshot, liveSnapshot)\n if (changes.length === 0) return\n\n const summary = summarize(changes)\n const message = `Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`\n if (behavior === 'warn') {\n log.warn(message)\n return\n }\n throw new MigrationDriftError(message, summary)\n}\n\nfunction summarize(changes: Change[]): SchemaDiffSummary {\n const added: string[] = []\n const removed: string[] = []\n const changed: string[] = []\n for (const c of changes) {\n switch (c.kind) {\n case 'createTable':\n added.push(c.table.name)\n break\n case 'dropTable':\n removed.push(c.table.name)\n break\n case 'addColumn':\n added.push(`${c.table}.${c.column.name}`)\n break\n case 'dropColumn':\n removed.push(`${c.table}.${c.column.name}`)\n break\n case 'alterColumn':\n changed.push(`${c.table}.${c.column}`)\n break\n case 'renameColumn':\n changed.push(`${c.table}.${c.from}→${c.to}`)\n break\n case 'renameTable':\n changed.push(`${c.from}→${c.to}`)\n break\n case 'addIndex':\n added.push(`${c.table}#${c.index.name}`)\n break\n case 'dropIndex':\n removed.push(`${c.table}#${c.index.name}`)\n break\n case 'addForeignKey':\n added.push(`${c.table}!${c.fk.name}`)\n break\n case 'dropForeignKey':\n removed.push(`${c.table}!${c.fk.name}`)\n break\n }\n }\n return { added, removed, changed }\n}\n","import path from 'node:path'\nimport { readFile } from 'node:fs/promises'\n\nimport { readJournal, computeMigrationHash } from './journal'\nimport { MigrationLockError, MigrationHashError, UnreviewedMigrationError } from './errors'\nimport { checkDrift, type DriftBehavior, type DriftLogger } from './drift'\nimport type { MigrationAdapter } from './adapter'\nimport type { SchemaSnapshot } from '../snapshot/types'\n\nexport interface RunnerOptions {\n adapter: MigrationAdapter\n migrationsDir: string\n /** When true, refuse to apply migrations whose meta.json.reviewed is false. Defaults to true outside dev. */\n requireReviewed?: boolean\n /** Owner string written into the lock table for diagnostics. */\n owner?: string\n /** Drift detection mode. Default 'error'. */\n driftCheck?: DriftBehavior\n /** Logger surface for drift warnings. Defaults to console. */\n log?: DriftLogger\n}\n\nexport interface AppliedSummary {\n applied: string[]\n batch: number | null\n}\n\ninterface PreparedEntry {\n id: string\n tag: string\n hash: string\n}\n\nasync function withLock<T>(opts: RunnerOptions, fn: () => Promise<T>): Promise<T> {\n const owner = opts.owner ?? `${process.pid}@${new Date().toISOString()}`\n const got = await opts.adapter.acquireLock(owner)\n if (!got) {\n throw new MigrationLockError('Another process holds the migration lock')\n }\n try {\n return await fn()\n } finally {\n await opts.adapter.releaseLock()\n }\n}\n\n/**\n * Verify pending entries: hash matches stored, meta.reviewed is true (if\n * requireReviewed). Throws MigrationHashError or UnreviewedMigrationError on\n * the first failure.\n */\nasync function verifyPending(\n pending: PreparedEntry[],\n migrationsDir: string,\n requireReviewed: boolean,\n): Promise<void> {\n for (const entry of pending) {\n const dir = path.join(migrationsDir, entry.id)\n const actualHash = await computeMigrationHash(dir)\n if (actualHash !== entry.hash) {\n throw new MigrationHashError(entry.id, entry.hash, actualHash)\n }\n if (requireReviewed) {\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8'))\n if (meta.reviewed !== true) {\n throw new UnreviewedMigrationError(entry.id)\n }\n }\n }\n}\n\nasync function applyEntry(entry: PreparedEntry, batch: number, opts: RunnerOptions): Promise<void> {\n const dir = path.join(opts.migrationsDir, entry.id)\n const upSql = await readFile(path.join(dir, 'up.sql'), 'utf8')\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8'))\n const useTx = meta.transaction !== false\n\n if (useTx) {\n await opts.adapter.applySqlInTx(upSql)\n } else {\n await opts.adapter.applySqlNoTx(upSql)\n }\n await opts.adapter.recordApplied({\n id: entry.id,\n name: entry.tag,\n hash: entry.hash,\n batch,\n direction: 'up',\n })\n}\n\nasync function runForward(opts: RunnerOptions, pending: PreparedEntry[]): Promise<AppliedSummary> {\n if (pending.length === 0) {\n return { applied: [], batch: null }\n }\n\n const requireReviewed = opts.requireReviewed ?? process.env.NODE_ENV !== 'development'\n await verifyPending(pending, opts.migrationsDir, requireReviewed)\n\n const applied = await opts.adapter.listApplied()\n const nextBatch = (applied.length === 0 ? 0 : Math.max(...applied.map((r) => r.batch))) + 1\n\n const ids: string[] = []\n for (const entry of pending) {\n await applyEntry(entry, nextBatch, opts)\n ids.push(entry.id)\n }\n return { applied: ids, batch: nextBatch }\n}\n\nasync function listPending(opts: RunnerOptions): Promise<PreparedEntry[]> {\n const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect)\n const applied = await opts.adapter.listApplied()\n const appliedIds = new Set(applied.map((r) => r.id))\n return journal.entries\n .filter((e) => !appliedIds.has(e.id))\n .map((e) => ({ id: e.id, tag: e.tag, hash: e.hash }))\n}\n\nasync function maybeCheckDrift(opts: RunnerOptions): Promise<void> {\n const behavior = opts.driftCheck ?? 'error'\n if (behavior === 'ignore') return\n const applied = await opts.adapter.listApplied()\n if (applied.length === 0) return // nothing to compare against\n const sorted = [...applied].toSorted((a, b) =>\n a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt),\n )\n const last = sorted[sorted.length - 1]\n let expected: SchemaSnapshot\n try {\n expected = JSON.parse(\n await readFile(path.join(opts.migrationsDir, last.id, 'snapshot.json'), 'utf8'),\n )\n } catch {\n return // snapshot missing — diagnostic, not fatal here\n }\n const live = await opts.adapter.introspect()\n await checkDrift(live, expected, behavior, opts.log)\n}\n\nexport async function migrateLatest(opts: RunnerOptions): Promise<AppliedSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n await maybeCheckDrift(opts)\n const pending = await listPending(opts)\n return runForward(opts, pending)\n })\n}\n\nexport async function migrateUp(opts: RunnerOptions): Promise<AppliedSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n await maybeCheckDrift(opts)\n const pending = await listPending(opts)\n return runForward(opts, pending.slice(0, 1))\n })\n}\n\nexport interface ReversedSummary {\n reversed: string | null\n}\n\nasync function applyReverse(id: string, opts: RunnerOptions): Promise<void> {\n const dir = path.join(opts.migrationsDir, id)\n const downSql = await readFile(path.join(dir, 'down.sql'), 'utf8')\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8'))\n const requireReviewed = opts.requireReviewed ?? process.env.NODE_ENV !== 'development'\n if (requireReviewed && meta.reviewed !== true) {\n throw new UnreviewedMigrationError(id)\n }\n const useTx = meta.transaction !== false\n if (useTx) {\n await opts.adapter.applySqlInTx(downSql)\n } else {\n await opts.adapter.applySqlNoTx(downSql)\n }\n await opts.adapter.removeApplied(id)\n}\n\nexport async function migrateDown(opts: RunnerOptions): Promise<ReversedSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n const applied = await opts.adapter.listApplied()\n if (applied.length === 0) return { reversed: null }\n // Sort by batch then appliedAt so 'most recent' is unambiguous even if\n // two migrations share a batch number (same `migrate latest` run).\n const sorted = [...applied].toSorted((a, b) =>\n a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt),\n )\n const last = sorted[sorted.length - 1]\n await applyReverse(last.id, opts)\n return { reversed: last.id }\n })\n}\n\nexport interface RollbackSummary {\n reversed: string[]\n batch: number | null\n}\n\nexport interface StatusEntry {\n id: string\n tag: string\n hash: string\n state: 'applied' | 'pending'\n batch: number | null\n appliedAt: string | null\n reviewed: boolean\n}\n\nexport async function migrateStatus(\n opts: Pick<RunnerOptions, 'adapter' | 'migrationsDir'>,\n): Promise<StatusEntry[]> {\n await opts.adapter.ensureMigrationTables()\n const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect)\n const applied = await opts.adapter.listApplied()\n const byId = new Map(applied.map((r) => [r.id, r]))\n\n const entries: StatusEntry[] = []\n for (const e of journal.entries) {\n const row = byId.get(e.id)\n let reviewed = false\n try {\n const meta = JSON.parse(\n await readFile(path.join(opts.migrationsDir, e.id, 'meta.json'), 'utf8'),\n )\n reviewed = meta.reviewed === true\n } catch {\n // Missing meta.json — treat as un-reviewed; the runner will refuse to\n // apply anyway. Don't fail status output for diagnostic purposes.\n }\n entries.push({\n id: e.id,\n tag: e.tag,\n hash: e.hash,\n state: row ? 'applied' : 'pending',\n batch: row?.batch ?? null,\n appliedAt: row?.appliedAt ?? null,\n reviewed,\n })\n }\n return entries\n}\n\nexport async function migrateRollback(opts: RunnerOptions): Promise<RollbackSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n const applied = await opts.adapter.listApplied()\n if (applied.length === 0) return { reversed: [], batch: null }\n\n const lastBatch = Math.max(...applied.map((r) => r.batch))\n // Reverse-applied order so teardown matches dependencies (drop FK before\n // drop table etc).\n const targets = applied\n .filter((r) => r.batch === lastBatch)\n .toSorted((a, b) => a.appliedAt.localeCompare(b.appliedAt))\n .toReversed()\n\n const reversed: string[] = []\n for (const row of targets) {\n await applyReverse(row.id, opts)\n reversed.push(row.id)\n }\n return { reversed, batch: lastBatch }\n })\n}\n","import { defineAdapter } from '@forinda/kickjs'\nimport type { InjectionToken } from '@forinda/kickjs'\n\nimport { migrateLatest, migrateStatus } from './migrate/runner'\nimport type { MigrationAdapter } from './migrate/adapter'\nimport type { DriftBehavior } from './migrate/drift'\n\nexport type MigrationsOnBoot = 'fail-if-pending' | 'apply' | 'ignore'\n\nexport interface KickDbAdapterConfig {\n /** The driver-bound MigrationAdapter — pgAdapter() in @forinda/kickjs-db-pg, etc. */\n migrationAdapter: MigrationAdapter\n /** Directory containing the generated migrations + _journal.json. */\n migrationsDir: string\n /** Boot policy. Default 'fail-if-pending' — mirror the operator-explicit philosophy. */\n migrationsOnBoot?: MigrationsOnBoot\n /** Drift detection mode. Default 'error' outside dev. */\n driftCheck?: DriftBehavior\n /** Default true outside dev. */\n requireReviewed?: boolean\n /** Optional DI token to register the migrationAdapter under, for adopters who need direct access. */\n token?: InjectionToken<MigrationAdapter>\n /**\n * Optional KickEventBus the adapter publishes migration events to.\n * When set, `db:migration-applied` fires after a successful\n * `migrateLatest()` on boot (apply policy only). Pair with\n * `DEVTOOLS_BUS` so the events surface in the DevTools panel:\n *\n * import { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\n * // Resolve only when devtools is actually wired — adopters who\n * // skip @forinda/kickjs-devtools never register the token, and\n * // resolve() throws on missing tokens.\n * const adapter = kickDbAdapter({\n * ...,\n * bus: container.has(DEVTOOLS_BUS) ? container.resolve(DEVTOOLS_BUS) : undefined,\n * })\n *\n * Type imported via `import type` so kickjs-db keeps devtools-kit\n * as an optional peer.\n */\n bus?: import('@forinda/kickjs-devtools-kit/bus').KickEventBus\n}\n\n/**\n * KickJS lifecycle adapter for kickjs-db. Three jobs:\n *\n * 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.\n * - 'fail-if-pending' (default): throw if any pending exists. Operators\n * run `kick db migrate latest` explicitly before deploys land. Avoids\n * the prisma footgun where migrations silently apply on deploy.\n * - 'apply': run migrateLatest() automatically. Useful for dev / preview\n * environments where convenience matters more than safety.\n * - 'ignore': boot regardless. Last-resort escape hatch.\n * 2. On shutdown, close the migrationAdapter (drains the pool, etc).\n * 3. Register the migrationAdapter under an optional DI token so adopters\n * can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers\n * separately under DB_PRIMARY.\n */\nexport const kickDbAdapter = defineAdapter<KickDbAdapterConfig>({\n name: 'kickjs-db',\n build: (config) => ({\n async beforeStart({ container }) {\n const policy = config.migrationsOnBoot ?? 'fail-if-pending'\n const status = await migrateStatus({\n adapter: config.migrationAdapter,\n migrationsDir: config.migrationsDir,\n })\n const pending = status.filter((s) => s.state === 'pending')\n\n if (pending.length > 0) {\n if (policy === 'fail-if-pending') {\n throw new Error(\n `kickjs-db: ${pending.length} pending migration(s); run \\`kick db migrate latest\\` before boot`,\n )\n }\n if (policy === 'apply') {\n const result = await migrateLatest({\n adapter: config.migrationAdapter,\n migrationsDir: config.migrationsDir,\n requireReviewed: config.requireReviewed,\n driftCheck: config.driftCheck,\n })\n // Republish to DevTools when a bus is wired so the panel\n // can surface \"migrations ran on boot\" without polling.\n // `applied` is the list of migration ids the runner ran;\n // `batch` is the batch number the journal stamped them with.\n if (config.bus) {\n config.bus.emit('db:migration-applied', {\n applied: result.applied,\n batch: result.batch,\n })\n }\n }\n // 'ignore' falls through.\n }\n\n if (config.token) {\n container.registerFactory(config.token, () => config.migrationAdapter)\n }\n },\n async shutdown() {\n await config.migrationAdapter.close()\n },\n }),\n})\n","import { createToken, type InjectionToken } from '@forinda/kickjs'\n\nimport type { KickDbClient } from './client/types'\n\n// First-party tokens own the reserved `kick/` namespace. Adopter-defined\n// tokens (e.g. additional shards / read replicas beyond the default pair)\n// should use the adopter's own scope (e.g. `app/db/tenants`).\nexport const DB_PRIMARY: InjectionToken<KickDbClient> = createToken<KickDbClient>('kick/db/primary')\nexport const DB_REPLICA: InjectionToken<KickDbClient> = createToken<KickDbClient>('kick/db/replica')\n\n/**\n * Alias for the default DB. Adopters who only have one database can inject\n * `DB_CLIENT` instead of remembering whether it's primary/replica.\n */\nexport const DB_CLIENT = DB_PRIMARY\n","import { EventEmitter } from 'node:events'\nimport type { KickDbClientEvents } from './types'\n\ntype Listener<E extends keyof KickDbClientEvents> = (\n e: KickDbClientEvents[E],\n) => void | Promise<void>\n\n/**\n * Per-client typed event emitter. Wraps a Node EventEmitter to keep the\n * surface narrow (no `addListener`, no `removeAllListeners`, no `setMaxListeners`).\n *\n * The Kysely query interceptor surface is intentionally minimal in M1:\n * transactionStart/Commit/Rollback fire from createDbClient's transaction()\n * wrapper. The full beforeQuery / query / queryError emit pipeline lands in\n * M2 alongside `$extends` since it requires a proper Kysely query plugin\n * with access to the compiled SQL string + parameters. The types are stable\n * now so adopter code can wire listeners; only the runtime emit is deferred.\n */\nexport class KickDbEventEmitter {\n private readonly emitter = new EventEmitter()\n\n on<E extends keyof KickDbClientEvents>(event: E, listener: Listener<E>): void {\n this.emitter.on(event, listener as (...args: unknown[]) => void)\n }\n\n off<E extends keyof KickDbClientEvents>(event: E, listener: Listener<E>): void {\n this.emitter.off(event, listener as (...args: unknown[]) => void)\n }\n\n emit<E extends keyof KickDbClientEvents>(event: E, payload: KickDbClientEvents[E]): void {\n this.emitter.emit(event, payload)\n }\n}\n","// customType<T>() — adopter-defined column type with optional driver\n// codecs. Lets a project introduce a typed column that doesn't ship\n// in the built-in DSL (encrypted strings, custom JSON shapes, citext,\n// PostGIS geometry, etc.) without forking the package.\n//\n// Schema usage:\n//\n// const encrypted = customType<EncryptedString>({\n// dataType: () => 'text',\n// toDriver: (s) => encrypt(s),\n// fromDriver: (raw) => decrypt(String(raw)),\n// })\n//\n// export const secrets = table('secrets', {\n// id: serial().primaryKey(),\n// value: encrypted().notNull(),\n// })\n//\n// `SchemaToTypes<typeof schema>` reads the phantom T from the\n// CustomColumnBuilder so `db.selectFrom('secrets').select('value')`\n// types `value: EncryptedString` (not `string`). Driver codecs flow\n// through the lifecycle plugin landing in M2.F-T19; until then they\n// are stored on the builder for the runtime hookup to pick up.\n\nimport { ColumnBuilder } from './dsl/columns/types'\n\nexport interface CustomTypeOptions<TJs, TDriver = unknown> {\n /**\n * SQL data type as it would appear in `CREATE TABLE` — `'text'`,\n * `'jsonb'`, `'citext'`, `'geometry(Point, 4326)'`, etc. Returned\n * via a thunk so adopters can compute the type from runtime config\n * (e.g. dialect-specific overrides).\n */\n dataType: () => string\n /** Optional encode hook applied at insert / update time. */\n toDriver?: (value: TJs) => TDriver\n /** Optional decode hook applied to selected rows. */\n fromDriver?: (driver: TDriver) => TJs\n}\n\n/**\n * ColumnBuilder subclass produced by `customType()`. Carries the\n * driver codecs so the (future) hooks pipeline can wire them through\n * a Kysely plugin without each consumer re-declaring its mapping.\n *\n * The phantom `T` flows through `SchemaToTypes<S>` exactly like any\n * other ColumnBuilder<T>, so adopters get full row-shape inference\n * for free.\n */\nexport class CustomColumnBuilder<TJs> extends ColumnBuilder<TJs> {\n /** Encode hook — run on values heading into the database. */\n readonly toDriver?: (value: TJs) => unknown\n /** Decode hook — run on row values coming out of the database. */\n readonly fromDriver?: (driver: unknown) => TJs\n\n constructor(opts: CustomTypeOptions<TJs>) {\n super(opts.dataType())\n this.toDriver = opts.toDriver as never\n this.fromDriver = opts.fromDriver as never\n }\n}\n\n/**\n * Build a reusable column factory for a custom type. The returned\n * function is what callers use inside `table('foo', { col: factory() })`\n * — same shape as the built-in `varchar()`, `text()`, etc.\n *\n * @example\n * ```ts\n * const ulid = customType<string>({\n * dataType: () => 'char(26)',\n * toDriver: (s) => s,\n * fromDriver: (raw) => String(raw),\n * })\n *\n * const events = table('events', {\n * id: ulid().primaryKey(),\n * ts: timestamp().notNull().defaultNow(),\n * })\n * ```\n */\nexport function customType<TJs>(opts: CustomTypeOptions<TJs>): () => CustomColumnBuilder<TJs> {\n return () => new CustomColumnBuilder<TJs>(opts)\n}\n","// Codec plugin — wires CustomColumnBuilder codecs into Kysely.\n//\n// Two transforms in one plugin:\n//\n// - `transformQuery` walks the AST for INSERT and UPDATE statements\n// and applies `toDriver(value)` to every ValueNode whose surrounding\n// ColumnNode matches a column in the encoder map. Pass-through for\n// `insert ... select`, `defaultValues`, references, and other\n// non-literal value expressions.\n//\n// - `transformResult` walks selected rows and applies `fromDriver` per\n// matching column name. Null/undefined pass through so codecs don't\n// need a nullable branch.\n//\n// Both maps are keyed by COLUMN NAME (not table.column). Two tables\n// declaring the same name share a codec — the row shape returned from\n// joins doesn't always carry table provenance, so any table-aware\n// scheme would degrade silently. Adopters using clashing column names\n// across tables with different codecs should declare distinct\n// `customType` instances or rename the column.\n\nimport type {\n KyselyPlugin,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n UnknownRow,\n} from 'kysely'\nimport {\n ColumnNode,\n ColumnUpdateNode,\n InsertQueryNode,\n PrimitiveValueListNode,\n UpdateQueryNode,\n ValueListNode,\n ValueNode,\n ValuesNode,\n type OperationNode,\n type ValuesItemNode,\n} from 'kysely'\n\nimport { CustomColumnBuilder } from '../custom-type'\nimport type { ColumnBuilder } from '../dsl/columns/types'\nimport type { TableDecl } from '../dsl/table'\n\n/** Map of column name → encoder/decoder. Built once at createDbClient time. */\nexport type CodecMap = Map<string, (value: unknown) => unknown>\n\nexport class CodecPlugin implements KyselyPlugin {\n constructor(\n private encoders: CodecMap,\n private decoders: CodecMap,\n ) {}\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n if (this.encoders.size === 0) return args.node\n const node = args.node\n if (InsertQueryNode.is(node)) return this.transformInsert(node)\n if (UpdateQueryNode.is(node)) return this.transformUpdate(node)\n return node\n }\n\n async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<UnknownRow>> {\n if (this.decoders.size === 0) return args.result\n const rows = args.result.rows.map((row) => this.decodeRow(row))\n return { ...args.result, rows }\n }\n\n // ---------------------------- query side ----------------------------\n\n private transformInsert(node: InsertQueryNode): InsertQueryNode {\n const cols = node.columns\n const values = node.values\n if (!cols || !values) return node\n // Build per-position encoder lookup once. Positions without a\n // matching encoder stay null so the inner loop can early-skip\n // without re-hashing on every row.\n const positional = this.positionalEncoders(cols)\n if (!positional) return node\n\n if (ValuesNode.is(values)) {\n const items = values.values.map((item) => this.encodeValuesItem(item, positional))\n // Reference equality preserved when no item changed.\n const changed = items.some((item, i) => item !== values.values[i])\n if (!changed) return node\n // ValuesItemNode is the public union ValueListNode | PrimitiveValueListNode;\n // every encodeValuesItem path either returns the original item (already a\n // ValuesItemNode) or rebuilds via the matching factory, so the cast holds.\n return InsertQueryNode.cloneWith(node, {\n values: ValuesNode.create(items as unknown as ReadonlyArray<ValuesItemNode>),\n })\n }\n\n // SelectQueryNode (insert from select), DefaultInsertValueNode, and\n // any future shape: pass through. We can't safely transform values\n // we didn't read literally.\n return node\n }\n\n private transformUpdate(node: UpdateQueryNode): UpdateQueryNode {\n const updates = node.updates\n if (!updates || updates.length === 0) return node\n\n let changed = false\n const next = updates.map((u) => {\n const col = u.column\n if (!ColumnNode.is(col)) return u\n const encoder = this.encoders.get(col.column.name)\n if (!encoder) return u\n const encoded = this.encodeValueNode(u.value, encoder)\n if (encoded === u.value) return u\n changed = true\n return ColumnUpdateNode.create(col, encoded)\n })\n if (!changed) return node\n // Kysely's UpdateQueryNode.cloneWithUpdates APPENDS to existing\n // updates rather than replacing them — wrong semantics for our\n // mutate-in-place flow. Spread directly. `node` is already\n // narrowed to UpdateQueryNode so the override typechecks cleanly.\n return { ...node, updates: next }\n }\n\n private positionalEncoders(\n cols: ReadonlyArray<ColumnNode>,\n ): Array<((v: unknown) => unknown) | null> | null {\n const out: Array<((v: unknown) => unknown) | null> = Array.from({ length: cols.length })\n let any = false\n for (let i = 0; i < cols.length; i++) {\n const enc = this.encoders.get(cols[i].column.name) ?? null\n out[i] = enc\n if (enc) any = true\n }\n return any ? out : null\n }\n\n private encodeValuesItem(\n item: OperationNode,\n positional: Array<((v: unknown) => unknown) | null>,\n ): OperationNode {\n if (ValueListNode.is(item)) {\n const next = item.values.map((v, i) => {\n const enc = positional[i]\n if (!enc) return v\n return this.encodeValueNode(v, enc)\n })\n const changed = next.some((v, i) => v !== item.values[i])\n return changed ? ValueListNode.create(next) : item\n }\n if (PrimitiveValueListNode.is(item)) {\n const next = item.values.map((v, i) => {\n const enc = positional[i]\n if (!enc) return v\n return this.encodePrimitive(v, enc)\n })\n const changed = next.some((v, i) => v !== item.values[i])\n return changed ? PrimitiveValueListNode.create(next) : item\n }\n return item\n }\n\n private encodeValueNode(node: OperationNode, encoder: (v: unknown) => unknown): OperationNode {\n if (!ValueNode.is(node)) return node\n const value = node.value\n if (value === null || value === undefined) return node\n const encoded = encoder(value)\n if (encoded === value) return node\n return ValueNode.create(encoded)\n }\n\n private encodePrimitive(value: unknown, encoder: (v: unknown) => unknown): unknown {\n if (value === null || value === undefined) return value\n return encoder(value)\n }\n\n // ---------------------------- result side ----------------------------\n\n private decodeRow(row: UnknownRow): UnknownRow {\n let mutated = false\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(row)) {\n const value = (row as Record<string, unknown>)[key]\n const decoder = this.decoders.get(key)\n if (decoder && value !== null && value !== undefined) {\n out[key] = decoder(value)\n mutated = true\n } else {\n out[key] = value\n }\n }\n return (mutated ? out : row) as UnknownRow\n }\n}\n\n/**\n * Walk a schema record and collect decoders from every column whose\n * builder is a `CustomColumnBuilder` with a `fromDriver` codec set.\n */\nexport function buildDecoderMap(schema: unknown): CodecMap {\n return collectCodecs(schema, 'fromDriver')\n}\n\n/**\n * Walk a schema record and collect encoders from every column whose\n * builder is a `CustomColumnBuilder` with a `toDriver` codec set.\n */\nexport function buildEncoderMap(schema: unknown): CodecMap {\n return collectCodecs(schema, 'toDriver')\n}\n\nfunction collectCodecs(schema: unknown, key: 'toDriver' | 'fromDriver'): CodecMap {\n const out: CodecMap = new Map()\n if (!schema || typeof schema !== 'object') return out\n\n for (const value of Object.values(schema as Record<string, unknown>)) {\n if (!isTableDecl(value)) continue\n for (const [colName, col] of Object.entries(value.__columns)) {\n if (col instanceof CustomColumnBuilder) {\n const fn = col[key]\n if (fn) out.set(colName, fn as (v: unknown) => unknown)\n }\n }\n }\n return out\n}\n\nfunction isTableDecl(value: unknown): value is TableDecl<string, Record<string, ColumnBuilder>> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __isTable?: boolean }).__isTable === true\n )\n}\n","// ResultExtensionPlugin — Kysely plugin that powers `$extends({ result })`.\n//\n// Two halves:\n//\n// 1. transformQuery walks SelectQueryNode + identifies the table,\n// then injects ColumnNode references for every `needs` column\n// not already in the SELECT list. Selects already using `*`\n// (SelectAllNode) skip injection — the column is implicitly\n// there.\n//\n// 2. transformResult walks the rows after the driver returns them,\n// runs each compute(row) per matching table, and assigns the\n// result to row[<computedKey>]. Null/undefined rows pass through\n// untouched.\n//\n// The two halves share state via a per-queryId Map so transformResult\n// only fires for queries this plugin marked in transformQuery — joins,\n// sub-selects, multi-table FROMs, and other shapes we can't reliably\n// attribute to a single table pass through both halves untouched.\n// Aliased single-table selects (`.from('posts as p')`) ARE supported —\n// the alias unwrap walks through to the underlying TableNode.\n\nimport {\n ColumnNode,\n ReferenceNode,\n SelectAllNode,\n SelectQueryNode,\n SelectionNode,\n TableNode,\n type KyselyPlugin,\n type OperationNode,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n type QueryId,\n type QueryResult,\n type RootOperationNode,\n type UnknownRow,\n} from 'kysely'\n\nimport type { ResultExtension, ResultExtensions } from './types'\n\n/** Per-table computed-field bag. */\ntype TableExtensionBag = Record<string, ResultExtension<UnknownRow>>\n\nexport class ResultExtensionPlugin implements KyselyPlugin {\n private byTable: Map<string, TableExtensionBag>\n /**\n * Map of queryId → table name the query targets. Populated in\n * transformQuery, consumed in transformResult, deleted after use so\n * it doesn't leak across long-lived clients.\n */\n private pending = new Map<QueryId, string>()\n\n constructor(extensions: ResultExtensions<unknown>) {\n this.byTable = new Map()\n for (const [tableName, bag] of Object.entries(extensions)) {\n if (!bag) continue\n const entries = Object.entries(bag) as Array<[string, ResultExtension<UnknownRow>]>\n if (entries.length === 0) continue\n this.byTable.set(tableName, Object.fromEntries(entries))\n }\n }\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n const { node, queryId } = args\n if (!SelectQueryNode.is(node)) return node\n const tableName = singleTableTarget(node)\n if (!tableName) return node\n const bag = this.byTable.get(tableName)\n if (!bag) return node\n\n // Tag the query so transformResult knows to apply computeds.\n this.pending.set(queryId, tableName)\n\n return injectNeeds(node, bag)\n }\n\n async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<UnknownRow>> {\n const tableName = this.pending.get(args.queryId)\n if (!tableName) return args.result\n this.pending.delete(args.queryId)\n\n const bag = this.byTable.get(tableName)\n if (!bag) return args.result\n const computeds = Object.entries(bag) as Array<[string, ResultExtension<UnknownRow>]>\n if (computeds.length === 0) return args.result\n\n const rows = args.result.rows.map((row) => {\n if (row === null || row === undefined) return row\n const base = row as Record<string, unknown>\n const next: Record<string, unknown> = { ...base }\n // Pass `base` (the pristine row, not `next`) into compute so\n // computeds can't read each other's outputs by accident — order\n // independence keeps the contract simple. Cross-computed\n // dependencies are an explicit non-feature.\n for (const [key, ext] of computeds) {\n try {\n next[key] = ext.compute(base as UnknownRow)\n } catch {\n // A throwing compute shouldn't poison the entire row set;\n // surface as undefined so the caller still gets the\n // pre-existing columns.\n next[key] = undefined\n }\n }\n return next as UnknownRow\n })\n return { ...args.result, rows }\n }\n}\n\n/**\n * Detect the single table this select reads from. Returns the table\n * name when from has exactly one TableNode (or AliasNode wrapping\n * one); returns null for joins, sub-selects, multi-table selects,\n * and anything we can't reliably attribute. The plugin only acts on\n * single-table selects in v1.\n */\nfunction singleTableTarget(node: SelectQueryNode): string | null {\n const from = node.from\n if (!from || from.froms.length !== 1) return null\n const target = unwrapAlias(from.froms[0])\n if (!TableNode.is(target)) return null\n return target.table.identifier.name\n}\n\nfunction unwrapAlias(node: OperationNode): OperationNode {\n // AliasNode wraps a child node in `.node`; we only care about the\n // underlying TableNode. Anything else passes through.\n if (node.kind === 'AliasNode') {\n const aliased = (node as unknown as { node: OperationNode }).node\n return aliased\n }\n return node\n}\n\n/**\n * Inject every needs column not already represented in the select\n * list. SelectAllNode (the `*` wildcard) means \"all columns\", in\n * which case there's nothing to add. Specific column references are\n * deduped by name so a column already selected explicitly stays put\n * exactly once.\n */\nfunction injectNeeds(node: SelectQueryNode, bag: TableExtensionBag): SelectQueryNode {\n const selections = node.selections ?? []\n // Wildcard select — every column is implicitly present.\n if (selections.some(isSelectAll)) return node\n\n const have = new Set<string>()\n for (const sel of selections) {\n const inner = sel.selection\n if (ReferenceNode.is(inner) && ColumnNode.is(inner.column)) {\n have.add(inner.column.column.name)\n } else if (ColumnNode.is(inner as OperationNode)) {\n have.add((inner as ColumnNode).column.name)\n }\n }\n\n const allNeeded = new Set<string>()\n for (const ext of Object.values(bag)) {\n for (const col of Object.keys(ext.needs)) {\n allNeeded.add(col)\n }\n }\n\n const missing = [...allNeeded].filter((c) => !have.has(c))\n if (missing.length === 0) return node\n\n const additions: SelectionNode[] = missing.map((col) =>\n SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))),\n )\n return SelectQueryNode.cloneWithSelections(node, additions)\n}\n\nfunction isSelectAll(node: SelectionNode): boolean {\n const inner = node.selection\n if (SelectAllNode.is(inner)) return true\n if (ReferenceNode.is(inner) && SelectAllNode.is(inner.column)) return true\n return false\n}\n","// Runtime for `$extends({ model, result })`.\n//\n// Two extension surfaces, applied in order:\n//\n// 1. **result extensions** rebuild the client around a Kysely\n// instance with the ResultExtensionPlugin appended. We can't\n// mutate plugins on a live Kysely (it freezes the plugin chain\n// at construction), but `qb.withPlugin(plugin)` returns a fresh\n// Kysely with the plugin added — that's what we wrap. The new\n// client shares the same InternalContext as the parent (events\n// emitter identity stays stable across extensions, transactions\n// keep working), but routes queries through the plugin.\n//\n// 2. **model extensions** layer a Proxy over whatever client the\n// previous step produced. The Proxy's `get` returns the per-\n// table method bag for keys that match a model entry; methods\n// are pre-bound via Function.prototype.call so `this` inside\n// the method is the extended proxy. That way chaining\n// `this.<otherTable>.<method>` or `this.transaction(...)`\n// resolves naturally regardless of which extension order ran.\n//\n// Lazy proxy reference: the bound methods need to capture `proxy`\n// itself, but the proxy can't exist until its handler is built.\n// Closure over a mutable `proxy` reference solves the cycle — by the\n// time any method actually runs, the binding has landed.\n\nimport type { KickDbClient } from '../client/types'\nimport type { ExtendedClient, ExtensionDefinition, ResultExtensions } from './types'\nimport { ResultExtensionPlugin } from './result-plugin'\nimport { wrap, type InternalContext } from '../client/wrap'\n\nexport function applyExtensions<DB, E extends ExtensionDefinition<DB>>(\n client: KickDbClient<DB>,\n ctx: InternalContext,\n ext: E,\n): ExtendedClient<DB, E> {\n // 1. Result extensions — rebuild Kysely around the plugin chain.\n // `wrap` and this module form an ESM cycle (wrap calls\n // applyExtensions for the client's `$extends`; we call wrap to\n // rebuild the client). ESM live bindings handle this fine as\n // long as nothing reads the binding at module top-level — both\n // sides only call into each other inside functions.\n let baseClient: KickDbClient<DB> = client\n if (hasResultExtensions(ext.result)) {\n const plugin = new ResultExtensionPlugin(ext.result as ResultExtensions<unknown>)\n const newQb = client.qb.withPlugin(plugin)\n baseClient = wrap<DB>(newQb, ctx)\n }\n\n // 2. Model proxy — layered on top of whichever base client we got\n // so model methods see the result-augmented row types via `this`.\n let proxy: ExtendedClient<DB, E>\n\n const modelBag: Record<string, Record<string, (...args: unknown[]) => unknown>> = {}\n const model = ext.model ?? {}\n for (const tableName of Object.keys(model) as (keyof typeof model)[]) {\n const methods = model[tableName]\n if (!methods) continue\n const bound: Record<string, (...args: unknown[]) => unknown> = {}\n for (const [methodName, fn] of Object.entries(methods)) {\n bound[methodName] = (...args) => (fn as (...a: unknown[]) => unknown).call(proxy, ...args)\n }\n modelBag[tableName as string] = bound\n }\n\n proxy = new Proxy(baseClient, {\n get(target, prop) {\n // Own-property check — `prop in modelBag` would also match\n // inherited keys like `toString` / `hasOwnProperty` from\n // Object.prototype, intercepting properties we never asked to\n // own and breaking the underlying client's own equivalents.\n if (typeof prop === 'string' && Object.prototype.hasOwnProperty.call(modelBag, prop)) {\n return modelBag[prop]\n }\n // Fall through. Bound methods on the underlying KickDbClient\n // (selectFrom, transaction, etc.) keep their original `this`\n // since `wrap()` already bound them to kysely at create time.\n const value = (target as unknown as Record<PropertyKey, unknown>)[prop as PropertyKey]\n return value\n },\n }) as ExtendedClient<DB, E>\n\n return proxy\n}\n\nfunction hasResultExtensions(result: unknown): boolean {\n if (!result || typeof result !== 'object') return false\n for (const bag of Object.values(result as Record<string, unknown>)) {\n if (bag && typeof bag === 'object' && Object.keys(bag as object).length > 0) return true\n }\n return false\n}\n","// Wraps a Kysely<DB> + InternalContext into a KickDbClient<DB>.\n//\n// Lives in its own module so consumers that need to rebuild the\n// client around a new Kysely instance — `$extends({ result })` adds a\n// result-extension Kysely plugin via `qb.withPlugin(...)`, then wraps\n// the new instance back into a client — can do so without an import\n// cycle through `client/create.ts`. Both `create.ts` and\n// `extend/apply.ts` import from here.\n//\n// `InternalContext` carries everything the wrap needs that lives\n// outside the Kysely instance itself: the lifecycle event emitter,\n// the cached dialect tag, and the savepoint counter. Sharing the same\n// ctx across re-wraps keeps the event listener identity stable —\n// adopters who attached `db.on('slowQuery', ...)` continue receiving\n// events from the rebuilt-after-`$extends` client.\n\nimport { Kysely, sql } from 'kysely'\n\nimport type { KickDbClient, TransactionEvent } from './types'\nimport { applyExtensions } from '../extend/apply'\nimport type { KickDbEventEmitter } from './events'\n\nexport interface InternalContext {\n events: KickDbEventEmitter | null\n dialect: KickDbClient['dialect']\n /** Increments per savepoint open inside this client; used for SP_<n> names. */\n savepointCounter: { value: number }\n}\n\nexport function wrap<DB>(qb: Kysely<DB>, ctx: InternalContext): KickDbClient<DB> {\n const client: KickDbClient<DB> = {\n qb,\n dialect: ctx.dialect,\n\n selectFrom: qb.selectFrom.bind(qb),\n insertInto: qb.insertInto.bind(qb),\n updateTable: qb.updateTable.bind(qb),\n deleteFrom: qb.deleteFrom.bind(qb),\n\n on(event, listener) {\n ctx.events?.on(event, listener)\n return client\n },\n off(event, listener) {\n ctx.events?.off(event, listener)\n return client\n },\n\n transaction: ((\n a: TransactionEvent | ((tx: KickDbClient<DB>) => Promise<unknown>),\n b?: (tx: KickDbClient<DB>) => Promise<unknown>,\n ) => {\n const txOpts = typeof a === 'function' ? {} : a\n const fn = (typeof a === 'function' ? a : b) as (tx: KickDbClient<DB>) => Promise<unknown>\n\n const run = async () => {\n ctx.events?.emit('transactionStart', { isolation: txOpts.isolation })\n try {\n const result = await qb.transaction().execute(async (tx) => {\n if (txOpts.isolation) {\n const level = txOpts.isolation.toUpperCase()\n await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx)\n }\n const child = wrap<DB>(tx as unknown as Kysely<DB>, ctx)\n return await fn(child)\n })\n ctx.events?.emit('transactionCommit', { isolation: txOpts.isolation })\n return result\n } catch (err) {\n ctx.events?.emit('transactionRollback', {\n isolation: txOpts.isolation,\n error: err,\n })\n throw err\n }\n }\n return run()\n }) as KickDbClient<DB>['transaction'],\n\n $extends(ext) {\n return applyExtensions(client, ctx, ext)\n },\n\n async savepoint(fn) {\n const name = `sp_${++ctx.savepointCounter.value}`\n // Savepoints only make sense inside a transaction. The query\n // builder's transaction proxies route SQL through the same\n // connection; sql.raw() against the wrapper lands on that\n // connection's tx context.\n await sql.raw(`SAVEPOINT ${name}`).execute(qb)\n try {\n const result = await fn(wrap<DB>(qb, ctx))\n await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb)\n return result\n } catch (err) {\n await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb)\n throw err\n }\n },\n\n async destroy() {\n await qb.destroy()\n },\n }\n return client\n}\n","import { Kysely, type Dialect as KyselyDialect } from 'kysely'\n\nimport type { CreateDbClientOptions, KickDbClient } from './types'\nimport type { SchemaToTypes } from './schema-types'\nimport { KickDbEventEmitter } from './events'\nimport { CodecPlugin, buildDecoderMap, buildEncoderMap } from './codec-plugin'\nimport { wrap, type InternalContext } from './wrap'\n\n// DB defaults to SchemaToTypes<TSchema> so the returned client is typed\n// directly from the schema parameter — no KickDbRegister lookup at the call\n// site. This breaks the `dbClient → RegisteredDB → KickDbRegister['db'] →\n// typeof dbClient` cycle that would otherwise resolve to `unknown`.\n// KickDbRegister is only consulted when consumers reference `KickDbClient`\n// with no explicit generic.\nexport function createDbClient<TSchema, DB = SchemaToTypes<TSchema>>(\n opts: CreateDbClientOptions<TSchema, DB>,\n): KickDbClient<DB> {\n // `slowQueryThresholdMs` and `bus` both imply events — listeners can't\n // subscribe to slowQuery / queryError, and the bus republisher can't\n // observe them, without the emitter being live.\n const eventsEnabled = opts.events || opts.slowQueryThresholdMs != null || opts.bus != null\n const events = eventsEnabled ? new KickDbEventEmitter() : null\n const slowThreshold = opts.slowQueryThresholdMs ?? null\n const bus = opts.bus ?? null\n\n // Republish to the DevTools event bus when wired. Mirror the local\n // event names under a `db:` namespace so adopter tabs / cross-cutting\n // log consumers know they came from kickjs-db.\n if (events && bus) {\n events.on('slowQuery', (payload) => {\n bus.emit('db:slow-query', payload)\n })\n events.on('queryError', (payload) => {\n bus.emit('db:query-error', payload)\n })\n }\n\n // Kysely's `log` config fires on every query — both success\n // (level 'query') and failure (level 'error') — with the compiled\n // SQL, params, and timing. Cleanest hook for the lifecycle events;\n // a full KyselyPlugin (transformQuery / transformResult) is heavier\n // and only worth it when we need to mutate the SQL tree.\n // Build customType codec maps once. Both transforms short-circuit\n // when their map is empty so the plugin is free of per-row /\n // per-query cost when no customType is in play. Plugin only\n // attached when at least one side has work to do.\n const decoders = buildDecoderMap(opts.schema)\n const encoders = buildEncoderMap(opts.schema)\n const codecPlugin =\n decoders.size > 0 || encoders.size > 0 ? new CodecPlugin(encoders, decoders) : null\n\n const kysely = new Kysely<DB>({\n dialect: opts.dialect,\n plugins: codecPlugin ? [codecPlugin] : undefined,\n log: events\n ? (event) => {\n if (event.level === 'query') {\n const durationMs = event.queryDurationMillis\n const payload = {\n sql: event.query.sql,\n parameters: event.query.parameters,\n durationMs,\n }\n events.emit('query', payload)\n if (slowThreshold != null && durationMs >= slowThreshold) {\n events.emit('slowQuery', { ...payload, thresholdMs: slowThreshold })\n }\n } else if (event.level === 'error') {\n events.emit('queryError', {\n sql: event.query.sql,\n parameters: event.query.parameters,\n error: event.error,\n })\n }\n }\n : undefined,\n })\n\n const ctx: InternalContext = {\n events,\n dialect: detectDialect(opts.dialect),\n savepointCounter: { value: 0 },\n }\n return wrap<DB>(kysely, ctx)\n}\n\nfunction detectDialect(dialect: KyselyDialect): KickDbClient['dialect'] {\n // Kysely's dialects have ctor names like PostgresDialect / SqliteDialect / MysqlDialect.\n const name = (dialect.constructor as { name?: string })?.name ?? ''\n if (name.includes('Postgres')) return 'postgres'\n if (name.includes('Mysql') || name.includes('MySql')) return 'mysql'\n return 'sqlite'\n}\n","export function quoteIdent(name: string): string {\n return name\n .split('.')\n .map((part) => '\"' + part.replace(/\"/g, '\"\"') + '\"')\n .join('.')\n}\n\nexport function quoteLiteral(value: string): string {\n return \"'\" + value.replace(/'/g, \"''\") + \"'\"\n}\n","import type { Change, ChangeSet } from '../diff/types'\nimport type { ColumnSnapshot, TableSnapshot } from '../snapshot/types'\nimport { quoteIdent, quoteLiteral } from './identifiers'\n\nexport function emitPg(changes: ChangeSet): string {\n return changes.map(emitChange).join('\\n')\n}\n\nfunction emitChange(change: Change): string {\n switch (change.kind) {\n case 'createTable':\n return emitCreateTable(change.table)\n case 'dropTable':\n return `DROP TABLE ${quoteIdent(change.table.name)};`\n case 'renameTable':\n return `ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`\n case 'addColumn':\n return emitAddColumn(change.table, change.column)\n case 'dropColumn':\n return `ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`\n case 'renameColumn':\n return `ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`\n case 'alterColumn':\n return emitAlterColumn(change.table, change.before, change.after)\n case 'addIndex':\n return emitAddIndex(change.table, change.index)\n case 'dropIndex':\n return `DROP INDEX ${quoteIdent(change.index.name)};`\n case 'addForeignKey':\n return emitAddFk(change.table, change.fk)\n case 'dropForeignKey':\n return `ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`\n case 'createEnum': {\n const values = change.enum.values.map((v) => quoteLiteral(v)).join(', ')\n return `CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`\n }\n case 'dropEnum':\n return `DROP TYPE ${quoteIdent(change.enum.name)};`\n case 'addEnumValue': {\n const before = change.before ? ` BEFORE ${quoteLiteral(change.before)}` : ''\n return `ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`\n }\n case 'removeEnumValue':\n return emitRemoveEnumValueAdvisory(change.enum, change.removed)\n }\n}\n\n/**\n * PostgreSQL has no `ALTER TYPE … DROP VALUE` — emitting silently\n * here would drop these values from the schema's intent without\n * reflecting in the database. Instead we render a multi-line SQL\n * comment with the manual migration steps the operator must take.\n *\n * The migration file still applies cleanly; the comment block makes\n * the missing operation visible in code review and in the generated\n * SQL output.\n */\nfunction emitRemoveEnumValueAdvisory(name: string, removed: readonly string[]): string {\n const safeName = sanitizeForLineComment(quoteIdent(name))\n const valuesList = removed.map((v) => sanitizeForLineComment(quoteLiteral(v))).join(', ')\n return [\n `-- WARNING: enum ${safeName} dropped value(s): ${valuesList}.`,\n `-- PostgreSQL has no ALTER TYPE ... DROP VALUE. To round-trip this`,\n `-- removal you must:`,\n `-- 1. Drop or migrate every column whose type is ${safeName} (or any`,\n `-- composite that references it).`,\n `-- 2. DROP TYPE ${safeName};`,\n `-- 3. CREATE TYPE ${safeName} AS ENUM (...) with the new value list.`,\n `-- 4. Recreate the columns + restore data, mapping any rows that held`,\n `-- one of the dropped value(s) to a still-valid replacement first.`,\n `-- This migration emits no SQL for this change — write the steps above`,\n `-- by hand if the removal is intentional, or restore the value(s) in`,\n `-- the schema definition to silence this warning.`,\n ].join('\\n')\n}\n\n/**\n * Make a value safe to interpolate into a single-line `--` SQL\n * comment. Identifiers and quoted literals normally don't carry\n * line breaks, but the user-supplied portion (enum name + values)\n * can contain anything an adopter passes to `pgEnum()`. A literal\n * `\\n` would terminate the comment early and turn the rest of the\n * line into executable SQL.\n *\n * Scope of the sanitiser:\n * - Line-break code points (`\\r`, `\\n`, `U+2028`, `U+2029`) collapse\n * runs to a single space so the comment stays on one line.\n * - C0 control bytes excluding tab (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F)\n * plus DEL (0x7F) escape to `\\x<hh>`.\n * - Tab (0x09) passes through — visually fine inside a `--` comment.\n *\n * Out of scope on purpose: C1 controls (U+0080-U+009F) and other\n * non-ASCII characters pass through unchanged. Adopters do legitimately\n * pass UTF-8 enum names + values (`'café'`, `'naïve'`); aggressively\n * escaping them would degrade the migration file's readability without\n * adding security — only line terminators can break out of a `--`\n * comment, and those are handled above.\n */\nfunction sanitizeForLineComment(value: string): string {\n // Walk code units rather than regex character classes \\u2014 control-char\n // regex literals trip `no-control-regex` lints and confuse some\n // editor analysers with \"unreachable\" warnings on the second\n // replace. Code-unit iteration is unambiguous: for every char we\n // either pass it through, collapse a line-break to a space, or\n // escape a control byte into `\\x<hh>`.\n let out = ''\n let prevWasLineBreak = false\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i)\n // Line-break code points \\u2192 collapse runs to a single space.\n // Includes \\r (0x0D), \\n (0x0A), U+2028 (LINE SEPARATOR),\n // U+2029 (PARAGRAPH SEPARATOR).\n const isLineBreak = code === 0x0a || code === 0x0d || code === 0x2028 || code === 0x2029\n if (isLineBreak) {\n if (!prevWasLineBreak) out += ' '\n prevWasLineBreak = true\n continue\n }\n prevWasLineBreak = false\n // Tab (0x09) passes through \\u2014 visually fine inside a `--` comment.\n // Other C0 control bytes (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F) and\n // DEL (0x7F) escape to `\\x<hh>` so the migration file stays\n // printable ASCII clean.\n const isControl =\n (code >= 0x00 && code <= 0x08) ||\n code === 0x0b ||\n code === 0x0c ||\n (code >= 0x0e && code <= 0x1f) ||\n code === 0x7f\n if (isControl) {\n out += `\\\\x${code.toString(16).padStart(2, '0')}`\n continue\n }\n out += value[i]\n }\n return out\n}\n\nfunction emitAddColumn(table: string, c: ColumnSnapshot): string {\n return `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`\n}\n\nfunction emitAlterColumn(table: string, before: ColumnSnapshot, after: ColumnSnapshot): string {\n const stmts: string[] = []\n const t = quoteIdent(table)\n const c = quoteIdent(after.name)\n\n const typeChanged = before.type !== after.type\n const nullChanged = before.nullable !== after.nullable\n const defaultChanged = before.default !== after.default\n const losingNotNull = !before.nullable && after.nullable\n\n if (typeChanged) {\n stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`)\n }\n\n // Default precedes nullable when loosening (DROP DEFAULT before DROP NOT NULL keeps\n // each interim state valid). Otherwise nullable precedes default (SET NOT NULL before\n // SET DEFAULT lets the default apply on the now-required column).\n const emitDefault = () => {\n if (!defaultChanged) return\n stmts.push(\n after.default === null\n ? `ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;`\n : `ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`,\n )\n }\n const emitNullable = () => {\n if (!nullChanged) return\n stmts.push(\n `ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'};`,\n )\n }\n\n if (losingNotNull) {\n emitDefault()\n emitNullable()\n } else {\n emitNullable()\n emitDefault()\n }\n\n return stmts.join('\\n')\n}\n\nfunction emitAddIndex(table: string, i: import('../snapshot/types').IndexSnapshot): string {\n const cols = i.columns.map(quoteIdent).join(', ')\n return `CREATE${i.unique ? ' UNIQUE' : ''} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`\n}\n\nconst FK_ACTIONS: Record<string, string> = {\n cascade: 'CASCADE',\n restrict: 'RESTRICT',\n set_null: 'SET NULL',\n set_default: 'SET DEFAULT',\n no_action: 'NO ACTION',\n}\n\nfunction emitAddFk(table: string, fk: import('../snapshot/types').ForeignKeySnapshot): string {\n const cols = fk.columns.map(quoteIdent).join(', ')\n const refCols = fk.refColumns.map(quoteIdent).join(', ')\n return (\n `ALTER TABLE ${quoteIdent(table)} ADD CONSTRAINT ${quoteIdent(fk.name)} ` +\n `FOREIGN KEY (${cols}) REFERENCES ${quoteIdent(fk.refTable)} (${refCols}) ` +\n `ON DELETE ${FK_ACTIONS[fk.onDelete]} ON UPDATE ${FK_ACTIONS[fk.onUpdate]};`\n )\n}\n\nfunction emitCreateTable(t: TableSnapshot): string {\n const cols = Object.values(t.columns).map(emitColumnDecl)\n const pk = Object.values(t.columns)\n .filter((c) => c.primaryKey)\n .map((c) => quoteIdent(c.name))\n const lines = [...cols]\n if (pk.length > 0) lines.push(`PRIMARY KEY (${pk.join(', ')})`)\n return `CREATE TABLE ${quoteIdent(t.name)} (\\n ${lines.join(',\\n ')}\\n);`\n}\n\nfunction emitColumnDecl(c: ColumnSnapshot): string {\n let s = `${quoteIdent(c.name)} ${c.type}`\n if (!c.nullable) s += ' NOT NULL'\n if (c.default !== null) s += ` DEFAULT ${formatDefault(c.default)}`\n return s\n}\n\nfunction formatDefault(value: string): string {\n // SQL keywords pass through bare.\n if (/^[A-Z_]+$/.test(value)) return value // CURRENT_TIMESTAMP, CURRENT_DATE, NULL, etc.\n // SQL function calls pass through bare: NOW(), gen_random_uuid(), etc.\n if (/^[a-z_][a-z0-9_]*\\s*\\([^)]*\\)$/i.test(value)) return value\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) return value // numeric\n if (value === 'true' || value === 'false') return value // boolean literal\n return quoteLiteral(value)\n}\n","import path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Dialect } from '../snapshot/types'\nimport type { MigrationAdapter } from '../migrate/adapter'\n\nexport type MigrationAdapterFactory = () => MigrationAdapter | Promise<MigrationAdapter>\n\nexport interface DbConfig {\n schemaPath: string\n migrationsDir: string\n dialect: Dialect\n /**\n * Postgres connection string for the built-in pgAdapter path. Read from\n * `db.connectionString` in kick.config.ts, or falls back to the\n * DATABASE_URL env var. The CLI uses this when no `adapter` factory is\n * provided.\n */\n connectionString?: string\n /**\n * Escape hatch: a factory returning a fully-constructed MigrationAdapter.\n * Takes precedence over `connectionString` when both are set. Use this\n * for non-default adapter wiring (custom pool, neon-serverless, etc).\n */\n adapter?: MigrationAdapterFactory\n}\n\nexport async function resolveDbConfig(opts: { configPath: string }): Promise<DbConfig> {\n const abs = path.resolve(opts.configPath)\n const mod = await import(pathToFileURL(abs).href)\n const cfg = mod.default ?? mod\n const db = cfg?.db ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n }\n}\n","import path from 'node:path'\nimport { mkdir, readFile, writeFile, readdir } from 'node:fs/promises'\nimport { pathToFileURL } from 'node:url'\nimport { existsSync } from 'node:fs'\n\nimport { extractSnapshot } from '../snapshot/extract'\nimport { diff } from '../diff/engine'\nimport { invertChanges, hasAmbiguousReverse } from '../diff/invert'\nimport { emitPg } from '../emit/pg'\nimport { appendJournalEntry, computeMigrationHash } from '../migrate/journal'\nimport type { DbConfig } from './config'\nimport type { SchemaSnapshot } from '../snapshot/types'\n\nexport interface GenerateOptions {\n name: string\n config: DbConfig\n cwd: string\n now?: () => Date\n /**\n * When true, skip the schema diff and emit an empty migration shell\n * (up.sql / down.sql with just the REVIEWED header, snapshot.json copying\n * the prior schema state). Used for data migrations, seed inserts, or any\n * change the diff engine can't author. Matches knex's `migrate:make`.\n */\n empty?: boolean\n}\n\nexport interface GenerateResult {\n status: 'created' | 'no-changes'\n migrationDir?: string\n changeCount: number\n empty?: boolean\n}\n\nexport async function generate(opts: GenerateOptions): Promise<GenerateResult> {\n const migrationsAbs = path.resolve(opts.cwd, opts.config.migrationsDir)\n const { snapshot: prev, id: previousId } = await readLatestSnapshotEntry(migrationsAbs)\n\n if (opts.empty) {\n return await writeMigration({\n opts,\n migrationsAbs,\n previousId,\n // Empty migrations don't change schema state — keep the prior snapshot\n // so the next diff-based generate stays consistent.\n target: prev,\n upBody: '',\n downBody: '',\n changeCount: 0,\n draft: false,\n empty: true,\n })\n }\n\n const schemaAbs = path.resolve(opts.cwd, opts.config.schemaPath)\n const schemaModule = await import(pathToFileURL(schemaAbs).href)\n const target = extractSnapshot(schemaModule, opts.config.dialect)\n const changes = diff(prev, target)\n\n if (changes.length === 0) {\n return { status: 'no-changes', changeCount: 0 }\n }\n\n return await writeMigration({\n opts,\n migrationsAbs,\n previousId,\n target,\n upBody: emitPg(changes),\n downBody: emitPg(invertChanges(changes)),\n changeCount: changes.length,\n draft: hasAmbiguousReverse(changes),\n empty: false,\n })\n}\n\ninterface WriteMigrationParams {\n opts: GenerateOptions\n migrationsAbs: string\n previousId: string | null\n target: SchemaSnapshot\n upBody: string\n downBody: string\n changeCount: number\n draft: boolean\n empty: boolean\n}\n\nasync function writeMigration(p: WriteMigrationParams): Promise<GenerateResult> {\n const id = formatId(p.opts.now?.() ?? new Date(), p.opts.name)\n const dir = path.join(p.migrationsAbs, id)\n await mkdir(dir, { recursive: true })\n\n const upHeader = '-- REVIEWED: false\\n'\n const upHint = p.empty\n ? '-- Empty migration — author SQL below (data migration, seed, etc).\\n'\n : ''\n const upSql = upHeader + upHint + p.upBody + (p.upBody ? '\\n' : '')\n await writeFile(path.join(dir, 'up.sql'), upSql, 'utf8')\n\n const downHeader = '-- REVIEWED: false\\n'\n const downDraft = p.draft\n ? '-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.\\n'\n : ''\n const downHint = p.empty ? '-- Empty migration — author the reverse SQL here.\\n' : ''\n const downSql = downHeader + downDraft + downHint + p.downBody + (p.downBody ? '\\n' : '')\n await writeFile(path.join(dir, 'down.sql'), downSql, 'utf8')\n\n await writeFile(path.join(dir, 'snapshot.json'), JSON.stringify(p.target, null, 2) + '\\n', 'utf8')\n\n await writeFile(\n path.join(dir, 'meta.json'),\n JSON.stringify(\n {\n id,\n name: p.opts.name,\n createdAt: (p.opts.now?.() ?? new Date()).toISOString(),\n reviewed: false,\n dialect: p.opts.config.dialect,\n previousId: p.previousId,\n downIsDraft: p.draft,\n empty: p.empty,\n },\n null,\n 2,\n ) + '\\n',\n 'utf8',\n )\n\n // Append to _journal.json so the runner has the canonical applied-order\n // and integrity hash. Hash includes up + down + snapshot, so any later\n // hand-edit of those files will surface as a MigrationHashError at apply.\n const hash = await computeMigrationHash(dir)\n await appendJournalEntry(p.migrationsAbs, p.opts.config.dialect, {\n id,\n tag: p.opts.name,\n hash,\n createdAt: (p.opts.now?.() ?? new Date()).toISOString(),\n })\n\n return { status: 'created', migrationDir: dir, changeCount: p.changeCount, empty: p.empty }\n}\n\ninterface LatestEntry {\n snapshot: SchemaSnapshot\n id: string | null\n}\n\nasync function readLatestSnapshotEntry(migrationsDir: string): Promise<LatestEntry> {\n const empty: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n if (!existsSync(migrationsDir)) {\n return { snapshot: empty, id: null }\n }\n const entries = await readdir(migrationsDir)\n const dirs = entries.filter((e) => /^\\d{8}_\\d{6}_/.test(e)).toSorted()\n if (dirs.length === 0) {\n return { snapshot: empty, id: null }\n }\n const latest = dirs[dirs.length - 1]\n const file = path.join(migrationsDir, latest, 'snapshot.json')\n const snapshot = JSON.parse(await readFile(file, 'utf8')) as SchemaSnapshot\n return { snapshot, id: latest }\n}\n\nfunction formatId(date: Date, name: string): string {\n const pad = (n: number) => n.toString().padStart(2, '0')\n const ts =\n date.getUTCFullYear().toString() +\n pad(date.getUTCMonth() + 1) +\n pad(date.getUTCDate()) +\n '_' +\n pad(date.getUTCHours()) +\n pad(date.getUTCMinutes()) +\n pad(date.getUTCSeconds())\n const slug = name.replace(/[^a-z0-9]+/gi, '_').toLowerCase()\n return `${ts}_${slug}`\n}\n","import { ColumnBuilder, type GeneratedBrand, type NotNullBrand } from './types'\n\n// ── helpers ───────────────────────────────────────────────────────────────\n\n/**\n * Type-level brand stamps. Runtime is identity; the cast attaches the\n * relevant brand so `SchemaToTypes<S>` reads them per column.\n */\nfunction brandGenerated<C>(col: C): C & GeneratedBrand {\n return col as C & GeneratedBrand\n}\n\nfunction brandNotNull<C>(col: C): C & NotNullBrand {\n return col as C & NotNullBrand\n}\n\nfunction formatNumeric(base: string, precision?: number, scale?: number): string {\n if (precision === undefined) return base\n if (scale === undefined) return `${base}(${precision})`\n return `${base}(${precision}, ${scale})`\n}\n\n// ── auto-assigned identity columns (DB picks the value) ───────────────────\n//\n// Auto-identity columns are always NOT NULL by SQL semantics, so we stamp\n// both NotNullBrand (drop the `| null`) and GeneratedBrand (wrap in\n// Generated<T>) at the constructor.\n\nexport function serial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<number>('serial', { nullable: false })))\n}\n\nexport function bigSerial(): ColumnBuilder<bigint> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<bigint>('bigserial', { nullable: false })))\n}\n\nexport function smallSerial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<number>('smallserial', { nullable: false })))\n}\n\n// ── numeric ───────────────────────────────────────────────────────────────\n\nexport function integer(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('integer')\n}\n\nexport function bigint(): ColumnBuilder<bigint> {\n return new ColumnBuilder<bigint>('bigint')\n}\n\nexport function smallint(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('smallint')\n}\n\nexport function decimal(precision?: number, scale?: number): ColumnBuilder<string> {\n return new ColumnBuilder<string>(formatNumeric('decimal', precision, scale))\n}\n\nexport function numeric(precision?: number, scale?: number): ColumnBuilder<string> {\n return new ColumnBuilder<string>(formatNumeric('numeric', precision, scale))\n}\n\nexport function real(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('real')\n}\n\nexport function doublePrecision(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('double precision')\n}\n\n// ── string-shaped ─────────────────────────────────────────────────────────\n\nexport function varchar(length = 255): ColumnBuilder<string> {\n return new ColumnBuilder<string>(`varchar(${length})`)\n}\n\nexport function char(length = 1): ColumnBuilder<string> {\n return new ColumnBuilder<string>(`char(${length})`)\n}\n\nexport function text(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('text')\n}\n\n// ── boolean ───────────────────────────────────────────────────────────────\n\nexport function boolean(): ColumnBuilder<boolean> {\n return new ColumnBuilder<boolean>('boolean')\n}\n\n// ── date / time ───────────────────────────────────────────────────────────\n\n/**\n * Subtype builder so `defaultNow()` can mark the resulting column as\n * generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter\n * omits the column on insert. Returns `this & GeneratedBrand` so the\n * subclass identity is preserved through the chain.\n */\nexport class TimestampBuilder extends ColumnBuilder<Date> {\n constructor(typeName: string = 'timestamp') {\n super(typeName)\n }\n\n defaultNow(): this & GeneratedBrand {\n this.state.default = 'CURRENT_TIMESTAMP'\n return brandGenerated(this)\n }\n}\n\nexport function timestamp(): TimestampBuilder {\n return new TimestampBuilder('timestamp')\n}\n\nexport function timestamptz(): TimestampBuilder {\n return new TimestampBuilder('timestamptz')\n}\n\nexport function date(): ColumnBuilder<Date> {\n return new ColumnBuilder<Date>('date')\n}\n\nexport function time(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('time')\n}\n\nexport function interval(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('interval')\n}\n\n// ── identity-shaped (uuid) ────────────────────────────────────────────────\n\n/**\n * Subtype builder so `defaultRandom()` can mark the resulting column as\n * generated — when the DB fills in `gen_random_uuid()` for omitted columns.\n * Returns `this & GeneratedBrand` so chaining works in either order:\n * uuid().defaultRandom().primaryKey()\n * uuid().primaryKey().defaultRandom() ← also works\n */\nexport class UuidBuilder extends ColumnBuilder<string> {\n constructor() {\n super('uuid')\n }\n\n defaultRandom(): this & GeneratedBrand {\n this.state.default = 'gen_random_uuid()'\n return brandGenerated(this)\n }\n}\n\nexport function uuid(): UuidBuilder {\n return new UuidBuilder()\n}\n\n// ── structured / binary ───────────────────────────────────────────────────\n\n/**\n * The `T` generic exists so adopters can declare their JSON shape:\n *\n * meta: jsonb<{ tags: string[] }>()\n *\n * `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the\n * row type narrows to `{ tags: string[] } | null`.\n */\nexport function json<T = unknown>(): ColumnBuilder<T> {\n return new ColumnBuilder<T>('json')\n}\n\nexport function jsonb<T = unknown>(): ColumnBuilder<T> {\n return new ColumnBuilder<T>('jsonb')\n}\n\nexport function bytea(): ColumnBuilder<Uint8Array> {\n return new ColumnBuilder<Uint8Array>('bytea')\n}\n","import type { ColumnBuilder, ColumnRef } from './columns/types'\nimport type { IndexDecl } from './constraints'\n\nexport type { ColumnRef }\n\nexport interface TableDecl<\n TName extends string = string,\n C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>,\n> {\n __isTable: true\n __name: TName\n __columns: C\n __indexes: IndexDecl[]\n}\n\ntype TableRefs<TName extends string, C extends Record<string, ColumnBuilder>> = TableDecl<\n TName,\n C\n> & {\n [K in keyof C]: ColumnRef\n}\n\ntype ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: {\n [K in keyof C]: ColumnRef\n}) => Record<string, IndexDecl>\n\n/**\n * Declare a typed table. The `TName extends string` generic narrows to the\n * literal table name so `SchemaToTypes<S>` can index by it without losing\n * the constant — `table('users', …)` widens to `TableDecl<'users', …>`,\n * not `TableDecl<string, …>`.\n */\nexport function table<TName extends string, C extends Record<string, ColumnBuilder>>(\n name: TName,\n columns: C,\n constraints?: ConstraintBuilder<C>,\n): TableRefs<TName, C> {\n const decl: TableDecl<TName, C> = {\n __isTable: true,\n __name: name,\n __columns: columns,\n __indexes: [],\n }\n\n const refs = {} as { [K in keyof C]: ColumnRef }\n for (const [key, builder] of Object.entries(columns) as [keyof C, ColumnBuilder][]) {\n refs[key] = {\n __tableName: name,\n __name: key as string,\n __builder: builder,\n __state: () => builder.__state(),\n }\n }\n\n if (constraints) {\n const declared = constraints(refs)\n decl.__indexes = Object.values(declared)\n }\n\n return Object.assign(decl, refs)\n}\n","export interface IndexDecl {\n name: string\n columns: string[]\n unique: boolean\n}\n\ninterface ColRef {\n __name: string\n}\n\nexport function index(name: string) {\n return {\n on(...cols: ColRef[]): IndexDecl {\n return { name, columns: cols.map((c) => c.__name), unique: false }\n },\n }\n}\n\nexport function unique(name: string) {\n return {\n on(...cols: ColRef[]): IndexDecl {\n return { name, columns: cols.map((c) => c.__name), unique: true }\n },\n }\n}\n","import type { TableDecl, ColumnRef } from './table'\nimport type { ColumnBuilder } from './columns/types'\n\nexport interface RelationOne {\n kind: 'one'\n target: TableDecl<string, Record<string, ColumnBuilder>>\n fields: ColumnRef[]\n references: ColumnRef[]\n}\n\nexport interface RelationMany {\n kind: 'many'\n target: TableDecl<string, Record<string, ColumnBuilder>>\n}\n\nexport type Relation = RelationOne | RelationMany\n\nexport interface RelationsDecl {\n __isRelations: true\n __sourceTable: string\n __relations: Record<string, Relation>\n}\n\ninterface Helpers {\n one: (\n target: TableDecl<string, Record<string, ColumnBuilder>>,\n opts: { fields: ColumnRef[]; references: ColumnRef[] },\n ) => RelationOne\n many: (target: TableDecl<string, Record<string, ColumnBuilder>>) => RelationMany\n}\n\nexport function relations<T extends TableDecl<string, Record<string, ColumnBuilder>>>(\n source: T,\n builder: (h: Helpers) => Record<string, Relation>,\n): RelationsDecl {\n const helpers: Helpers = {\n one: (target, opts) => ({\n kind: 'one',\n target,\n fields: opts.fields,\n references: opts.references,\n }),\n many: (target) => ({ kind: 'many', target }),\n }\n return {\n __isRelations: true,\n __sourceTable: source.__name,\n __relations: builder(helpers),\n }\n}\n"],"mappings":";;;;;;;;;;qlBAkBA,SAAS,QAAQ,EAAmE,CAClF,MAAO,GAAQ,GAAK,OAAO,GAAM,UAAa,EAAiB,YAAc,IAc/E,SAAS,SAAS,EAAkE,CAClF,GAAI,OAAO,GAAM,WAAY,MAAO,GACpC,IAAM,EAAI,EACV,OAAO,OAAO,EAAE,UAAa,UAAY,MAAM,QAAQ,EAAE,OAAO,CAGlE,SAAgB,gBAAgB,OAAiC,QAAkC,CACjG,IAAM,OAAwC,EAAE,CAC1C,MAAsC,EAAE,CAE9C,IAAK,IAAM,SAAS,OAAO,OAAO,OAAO,CACnC,QAAQ,MAAM,CAChB,OAAO,MAAM,QAAU,aAAa,MAAM,CACjC,SAAS,MAAM,GACxB,MAAM,MAAM,UAAY,CAAE,KAAM,MAAM,SAAU,OAAQ,CAAC,GAAG,MAAM,OAAO,CAAE,EAS/E,OAHI,UAAY,YAAc,OAAO,KAAK,MAAM,CAAC,OAAS,EACjD,CAAE,QAAS,EAAG,QAAS,OAAQ,MAAO,CAExC,CAAE,QAAS,EAAG,QAAS,OAAQ,CAGxC,SAAS,aAAa,EAAoE,CACxF,IAAM,QAAoC,EAAE,CACtC,QAA2B,CAAC,GAAG,EAAE,UAAU,CAC3C,YAAoC,EAAE,CAE5C,IAAK,GAAM,CAAC,OAAQ,WAAY,OAAO,QAAQ,EAAE,UAAU,CAAE,CAC3D,QAAQ,QAAU,QAAQ,OAAO,OAAO,CACxC,IAAM,MAAQ,QAAQ,SAAS,CAQ/B,GAPI,MAAM,QACR,QAAQ,KAAK,CACX,KAAM,GAAG,EAAE,OAAO,GAAG,OAAO,SAC5B,QAAS,CAAC,OAAO,CACjB,OAAQ,GACT,CAAC,CAEA,MAAM,WAAY,CAGpB,IAAM,IAAM,MAAM,WAAW,OAAO,CACpC,YAAY,KAAK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,QAAQ,CAClD,KAAK,KAAO,CACV,YAAa,KACb,OAAQ,IACR,UAAW,QACX,YAAe,QAAQ,SAAS,CACjC,CAGH,GAAI,YAAa,CACf,IAAM,SAAW,YAAY,KAAK,CAClC,KAAK,UAAY,OAAO,OAAO,SAAS,CAG1C,OAAO,OAAO,OAAO,KAAM,KAAK,CCjDlC,SAAgB,MAAM,KAAc,CAClC,MAAO,CACL,GAAG,GAAG,KAA2B,CAC/B,MAAO,CAAE,KAAM,QAAS,KAAK,IAAK,GAAM,EAAE,OAAO,CAAE,OAAQ,GAAO,EAErE,CAGH,SAAgB,OAAO,KAAc,CACnC,MAAO,CACL,GAAG,GAAG,KAA2B,CAC/B,MAAO,CAAE,KAAM,QAAS,KAAK,IAAK,GAAM,EAAE,OAAO,CAAE,OAAQ,GAAM,EAEpE,CCQH,SAAgB,UACd,OACA,QACe,CAUf,MAAO,CACL,cAAe,GACf,cAAe,OAAO,OACtB,YAAa,QAZU,CACvB,KAAM,OAAQ,QAAU,CACtB,KAAM,MACN,OACA,OAAQ,KAAK,OACb,WAAY,KAAK,WAClB,EACD,KAAO,SAAY,CAAE,KAAM,OAAQ,OAAQ,EAC5C,CAI8B,CAC9B"}
1
+ {"version":3,"file":"index.mjs","names":["jsonArrayFrom","jsonObjectFrom","jsonArrayFrom","jsonObjectFrom"],"sources":["../src/errors.ts","../src/query/errors.ts","../src/query/extract-relations.ts","../src/snapshot/extract.ts","../src/snapshot/render.ts","../src/diff/engine.ts","../src/diff/invert.ts","../src/migrate/errors.ts","../src/emit/identifiers.ts","../src/emit/pg.ts","../src/migrate/enum-drop-gate.ts","../src/migrate/journal.ts","../src/migrate/schema.ts","../src/migrate/memory-adapter.ts","../src/migrate/introspect-pg.ts","../src/migrate/drift.ts","../src/migrate/runner.ts","../src/adapter.ts","../src/tokens.ts","../src/client/events.ts","../src/custom-type.ts","../src/client/codec-plugin.ts","../src/extend/result-plugin.ts","../src/extend/apply.ts","../src/query/builder.ts","../src/client/wrap.ts","../src/query/compile-shared.ts","../src/query/compile-pg.ts","../src/query/compile-sqlite.ts","../src/query/compile-mysql.ts","../src/query/compilers.ts","../src/client/create.ts","../src/cli/config.ts","../src/cli/generate.ts","../src/dsl/columns/builders.ts","../src/dsl/table.ts","../src/dsl/constraints.ts","../src/dsl/relations.ts"],"sourcesContent":["export class KickDbError extends Error {\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.name = this.constructor.name\n this.code = code\n }\n}\n","/**\n * Errors thrown by the relational-query compiler. All extend\n * `KickDbError` so adopters can catch the family with a single\n * `instanceof` check.\n *\n * Spec: docs/db/spec-relational-query.md §6 (edge cases) + §7 (R-3,\n * R-5).\n */\n\nimport { KickDbError } from '../errors'\n\n/**\n * Thrown at compile time when a `with` key references a relation\n * that the source table doesn't declare.\n */\nexport class RelationalQueryUnknownRelationError extends KickDbError {\n readonly sourceTable: string\n readonly relationKey: string\n constructor(sourceTable: string, relationKey: string) {\n super(\n 'KICK_DB_RELATIONAL_UNKNOWN_RELATION',\n `Unknown relation \\`${sourceTable}.${relationKey}\\` — declare it via \\`relations()\\` ` +\n `before referencing it inside \\`db.query.${sourceTable}.findMany({ with })\\`.`,\n )\n this.sourceTable = sourceTable\n this.relationKey = relationKey\n }\n}\n\n/**\n * Thrown at compile time when a `with` clause nests deeper than\n * `maxDepth` (spec §7 R-3, default 5). Catches infinite specs on\n * self-referencing tables before any SQL is built.\n */\nexport class RelationalQueryDepthError extends KickDbError {\n readonly maxDepth: number\n readonly trace: readonly string[]\n constructor(maxDepth: number, trace: readonly string[]) {\n super(\n 'KICK_DB_RELATIONAL_DEPTH_EXCEEDED',\n `Relational query exceeds maxDepth=${maxDepth}. Path: ${trace.join(' → ')}. ` +\n `Override with \\`{ maxDepth: N }\\` on the call site if intentional.`,\n )\n this.maxDepth = maxDepth\n this.trace = trace\n }\n}\n\n/**\n * Thrown at compile time when a relation name collides with a\n * literal column on the same table (spec §7 R-5). Forces the schema\n * author to rename one of them so the LATERAL alias stays\n * unambiguous.\n */\nexport class RelationalQueryAliasCollisionError extends KickDbError {\n readonly sourceTable: string\n readonly conflictingName: string\n constructor(sourceTable: string, conflictingName: string) {\n super(\n 'KICK_DB_RELATIONAL_ALIAS_COLLISION',\n `Relation \\`${sourceTable}.${conflictingName}\\` collides with a column of the same name. ` +\n `Rename the relation or the column to disambiguate.`,\n )\n this.sourceTable = sourceTable\n this.conflictingName = conflictingName\n }\n}\n\n/**\n * Thrown by SQLite + MySQL compiler stubs in v1. The interface ships\n * with PG only; the other dialects fill in during M4 without an API\n * change at the call site.\n */\nexport class RelationalQueryNotSupportedError extends KickDbError {\n readonly dialect: string\n constructor(dialect: string) {\n super(\n 'KICK_DB_RELATIONAL_NOT_SUPPORTED',\n `Relational query compiler for dialect \\`${dialect}\\` lands in M4. ` +\n `Use layer 1 / 2 (\\`db.selectFrom(...)\\`) with manual joins for now.`,\n )\n this.dialect = dialect\n }\n}\n\n/**\n * Thrown at extract time when more than one inverse `one` declared\n * on the **target** table shares the same `relationName` AND points\n * back at the same source — the actual ambiguity case for resolver\n * step 1. Scope is per `(sourceTable, targetTable, relationName)`:\n * the same tag can be reused across unrelated table pairs. Spec:\n * docs/db/spec-relation-name.md §7 R-2.\n */\nexport class RelationalQueryAmbiguousRelationNameError extends KickDbError {\n readonly sourceTable: string\n readonly targetTable: string\n readonly relationName: string\n /** Relation keys on the target table whose inverse `one` shares the tag. */\n readonly conflicting: readonly string[]\n constructor(\n sourceTable: string,\n targetTable: string,\n relationName: string,\n conflicting: readonly string[],\n ) {\n super(\n 'KICK_DB_RELATIONAL_AMBIGUOUS_RELATION_NAME',\n `Cannot pair \\`${sourceTable}\\`'s \\`many\\` with relationName='${relationName}' — ` +\n `multiple \\`one\\` relations on \\`${targetTable}\\` share that tag and point back at ` +\n `\\`${sourceTable}\\` (${conflicting.map((c) => `\\`${targetTable}.${c}\\``).join(', ')}). ` +\n `The pairing tag must be unique per (source, target, name) triple — rename one of the ` +\n `\\`one\\` relations on \\`${targetTable}\\` or split the schema.`,\n )\n this.sourceTable = sourceTable\n this.targetTable = targetTable\n this.relationName = relationName\n this.conflicting = conflicting\n }\n}\n\n/**\n * Thrown at extract time when a `many` relation has no inverse\n * `one` declared on the target table. The compiler needs the FK\n * column pair to build the join predicate; without an inverse we\n * have no way to discover it. Adopters fix by declaring the inverse\n * `one` on the target side (drizzle-style symmetric declarations).\n */\nexport class RelationalQueryMissingInverseError extends KickDbError {\n readonly sourceTable: string\n readonly relationName: string\n readonly targetTable: string\n constructor(sourceTable: string, relationName: string, targetTable: string) {\n super(\n 'KICK_DB_RELATIONAL_MISSING_INVERSE',\n `Cannot resolve \\`many\\` relation \\`${sourceTable}.${relationName}\\` — ` +\n `no inverse \\`one\\` relation declared on \\`${targetTable}\\` pointing back to \\`${sourceTable}\\`, ` +\n `and ${targetTable}'s foreign keys to ${sourceTable} are either zero or ambiguous. ` +\n `If the target has multiple FKs to the source, tag both sides with the same ` +\n `\\`relationName: 'foo'\\` to pair them — see docs/db/spec-relation-name.md. ` +\n `Otherwise add e.g. \\`relations(${targetTable}, h => ({ ${sourceTable}: h.one(${sourceTable}, { fields: [${targetTable}.${sourceTable}Id], references: [${sourceTable}.id] }) }))\\` ` +\n `so the compiler knows which columns join the two tables.`,\n )\n this.sourceTable = sourceTable\n this.relationName = relationName\n this.targetTable = targetTable\n }\n}\n","/**\n * Resolve `relations()` declarations into the JSON-serializable\n * sidecar shape consumed by the relational-query compiler.\n *\n * - `one` relations resolve straight from `RelationOne.{fields,\n * references}`.\n * - `many` relations resolve via the inverse `one` on the target\n * table — drizzle-style symmetric declarations. If no inverse\n * exists, throw `RelationalQueryMissingInverseError` at extract\n * time so adopters get a clear error before the schema ships.\n * - Alias collisions (a relation name that shadows a column on the\n * same table) throw `RelationalQueryAliasCollisionError` per spec\n * §7 R-5.\n *\n * Spec: docs/db/spec-relational-query.md §5.3.\n */\n\nimport type { Relation, RelationOne, RelationsDecl } from '../dsl/relations'\nimport type { TableSnapshot } from '../snapshot/types'\nimport type { ResolvedRelations } from './relations'\nimport {\n RelationalQueryAliasCollisionError,\n RelationalQueryAmbiguousRelationNameError,\n RelationalQueryMissingInverseError,\n} from './errors'\n\ninterface MaybeRelations {\n __isRelations?: boolean\n __sourceTable?: string\n __relations?: Record<string, Relation>\n}\n\nfunction isRelations(v: unknown): v is RelationsDecl {\n return Boolean(v && typeof v === 'object' && (v as MaybeRelations).__isRelations === true)\n}\n\n/**\n * Walk the schema record for `RelationsDecl` entries and return the\n * resolved sidecar. Returns `undefined` when no relations are\n * declared so callers can leave the snapshot's `relations` field\n * absent.\n */\nexport function extractRelations(\n schema: Record<string, unknown>,\n tables: Record<string, TableSnapshot>,\n): ResolvedRelations | undefined {\n const declsBySource: Record<string, Record<string, Relation>> = {}\n\n for (const value of Object.values(schema)) {\n if (isRelations(value)) {\n // A second `relations()` call against the same source merges —\n // adopters can split one large declaration across files. Last\n // writer wins on duplicate keys.\n declsBySource[value.__sourceTable] = {\n ...declsBySource[value.__sourceTable],\n ...value.__relations,\n }\n }\n }\n\n if (Object.keys(declsBySource).length === 0) return undefined\n\n const out: ResolvedRelations = {}\n\n for (const [sourceTable, relations] of Object.entries(declsBySource)) {\n const tableSnapshot = tables[sourceTable]\n // Ignore relations declared against an unknown table — `extract`\n // already skips non-table entries; mismatched relations() calls\n // get the same treatment rather than throwing on a typo.\n if (!tableSnapshot) continue\n\n out[sourceTable] = {}\n\n for (const [relationName, rel] of Object.entries(relations)) {\n if (relationName in tableSnapshot.columns) {\n throw new RelationalQueryAliasCollisionError(sourceTable, relationName)\n }\n\n if (rel.kind === 'one') {\n out[sourceTable][relationName] = {\n kind: 'one',\n target: rel.target.__name,\n sourceColumns: rel.fields.map((f) => f.__name),\n targetColumns: rel.references.map((r) => r.__name),\n ...(rel.relationName !== undefined ? { relationName: rel.relationName } : {}),\n }\n continue\n }\n\n // `many` resolution precedence (spec-relation-name.md §4):\n // 1. `relationName` match — both sides declared.\n // 2. Single untagged inverse `one` — exactly one + neither\n // side has a relationName.\n // 3. FK introspection — exactly one FK back to source.\n // 4. Throw MissingInverseError with hint.\n const target = rel.target.__name\n const targetRelations = declsBySource[target] ?? {}\n\n // Preserve the source-side `relationName` on the resolved\n // sidecar regardless of which step ends up resolving the join.\n // The tag is part of the public surface (RelationSnapshot /\n // RelationMapEntry) and shouldn't drop just because step 1 fell\n // through to step 2/3.\n const relNameSpread = rel.relationName !== undefined ? { relationName: rel.relationName } : {}\n\n // Step 1 — paired by relationName.\n if (rel.relationName !== undefined) {\n const matchingInverses = findInversesByRelationName(\n targetRelations,\n sourceTable,\n rel.relationName,\n )\n if (matchingInverses.length > 1) {\n throw new RelationalQueryAmbiguousRelationNameError(\n sourceTable,\n target,\n rel.relationName,\n matchingInverses.map((m) => m.relationKey),\n )\n }\n if (matchingInverses.length === 1) {\n const inverse = matchingInverses[0]!.relation\n out[sourceTable][relationName] = {\n kind: 'many',\n target,\n sourceColumns: inverse.references.map((r) => r.__name),\n targetColumns: inverse.fields.map((f) => f.__name),\n ...relNameSpread,\n }\n continue\n }\n // Tagged on this side but no matching inverse — fall through\n // to FK fallback so the eventual error message lists what\n // the resolver looked at.\n }\n\n // Step 2 — single untagged inverse `one`.\n const untaggedInverse = findUniqueUntaggedInverse(targetRelations, sourceTable)\n if (untaggedInverse) {\n out[sourceTable][relationName] = {\n kind: 'many',\n target,\n sourceColumns: untaggedInverse.references.map((r) => r.__name),\n targetColumns: untaggedInverse.fields.map((f) => f.__name),\n ...relNameSpread,\n }\n continue\n }\n\n // Step 3 — FK introspection fallback.\n const fkFallback = resolveByForeignKey(tables[target], sourceTable)\n if (fkFallback) {\n out[sourceTable][relationName] = {\n kind: 'many',\n target,\n sourceColumns: fkFallback.refColumns,\n targetColumns: fkFallback.columns,\n ...relNameSpread,\n }\n continue\n }\n\n // Step 4 — give up.\n throw new RelationalQueryMissingInverseError(sourceTable, relationName, target)\n }\n }\n\n return out\n}\n\n/**\n * Step-1 helper — find inverse `one` declarations on the target\n * table whose `relationName` matches the requested tag AND whose\n * own target is the source. Returns the relation key alongside the\n * relation itself so the ambiguous-error message can list the\n * conflicting names.\n */\nfunction findInversesByRelationName(\n targetRelations: Record<string, Relation>,\n sourceTable: string,\n relationName: string,\n): Array<{ relationKey: string; relation: RelationOne }> {\n const matches: Array<{ relationKey: string; relation: RelationOne }> = []\n for (const [key, rel] of Object.entries(targetRelations)) {\n if (\n rel.kind === 'one' &&\n rel.target.__name === sourceTable &&\n rel.relationName === relationName\n ) {\n matches.push({ relationKey: key, relation: rel })\n }\n }\n return matches\n}\n\n/**\n * Step-2 helper — find a single inverse `one` on the target table\n * pointing at the source AND with **no** `relationName` set. The\n * uniqueness check is the M4.B tightening of M3's first-match\n * heuristic; multi-FK schemas now surface as `MissingInverseError`\n * (which routes adopters at adding `relationName`) instead of\n * silently picking the first inverse.\n */\nfunction findUniqueUntaggedInverse(\n targetRelations: Record<string, Relation>,\n sourceTable: string,\n): RelationOne | null {\n let unique: RelationOne | null = null\n for (const rel of Object.values(targetRelations)) {\n if (rel.kind === 'one' && rel.target.__name === sourceTable && rel.relationName === undefined) {\n if (unique) return null // ambiguous — caller falls through\n unique = rel\n }\n }\n return unique\n}\n\n/**\n * Fallback resolution path for `many` relations without an inverse\n * `one`. Walks the target table's FK list for a single edge back to\n * the source. Returns `null` when there is no FK or when more than\n * one FK qualifies — adopters with ambiguous schemas need the\n * explicit inverse to disambiguate.\n */\nfunction resolveByForeignKey(\n targetTable: TableSnapshot | undefined,\n sourceTable: string,\n): { columns: readonly string[]; refColumns: readonly string[] } | null {\n if (!targetTable) return null\n const matches = targetTable.foreignKeys.filter((fk) => fk.refTable === sourceTable)\n if (matches.length !== 1) return null\n const fk = matches[0]!\n return { columns: fk.columns, refColumns: fk.refColumns }\n}\n","import type { ColumnBuilder } from '../dsl/columns/types'\nimport type { TableDecl } from '../dsl/table'\nimport { extractRelations } from '../query/extract-relations'\nimport type {\n Dialect,\n EnumSnapshot,\n ForeignKeySnapshot,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n} from './types'\n\ninterface MaybeTable {\n __isTable?: boolean\n __name?: string\n __columns?: Record<string, ColumnBuilder>\n __indexes?: IndexSnapshot[]\n}\n\nfunction isTable(v: unknown): v is TableDecl<string, Record<string, ColumnBuilder>> {\n return Boolean(v && typeof v === 'object' && (v as MaybeTable).__isTable === true)\n}\n\n/**\n * pgEnum() returns a function with `enumName` + `values` attached.\n * Detect via duck-typing rather than `instanceof` so the snapshot\n * code stays decoupled from the PG-specific module — the snapshot\n * pipeline runs for every dialect.\n */\ninterface MaybePgEnum {\n enumName?: unknown\n values?: unknown\n}\n\nfunction isPgEnum(v: unknown): v is { enumName: string; values: readonly string[] } {\n if (typeof v !== 'function') return false\n const f = v as MaybePgEnum\n return typeof f.enumName === 'string' && Array.isArray(f.values)\n}\n\nexport function extractSnapshot(schema: Record<string, unknown>, dialect: Dialect): SchemaSnapshot {\n const tables: Record<string, TableSnapshot> = {}\n const enums: Record<string, EnumSnapshot> = {}\n\n for (const value of Object.values(schema)) {\n if (isTable(value)) {\n tables[value.__name] = extractTable(value)\n } else if (isPgEnum(value)) {\n enums[value.enumName] = { name: value.enumName, values: [...value.values] }\n }\n }\n\n const relations = extractRelations(schema, tables)\n\n // Only carry `enums` on PG snapshots — other dialects don't define\n // them and an empty record would just bloat the diff output.\n // `relations` is dialect-agnostic (query-time sugar) but we still\n // omit it when absent to keep snapshots minimal for adopters who\n // don't use the relational query layer.\n const snapshot: SchemaSnapshot = { version: 1, dialect, tables }\n if (dialect === 'postgres' && Object.keys(enums).length > 0) {\n snapshot.enums = enums\n }\n if (relations) {\n snapshot.relations = relations\n }\n return snapshot\n}\n\nfunction extractTable(t: TableDecl<string, Record<string, ColumnBuilder>>): TableSnapshot {\n const columns: TableSnapshot['columns'] = {}\n const indexes: IndexSnapshot[] = [...t.__indexes]\n const foreignKeys: ForeignKeySnapshot[] = []\n\n for (const [colKey, builder] of Object.entries(t.__columns)) {\n columns[colKey] = builder.toJSON(colKey)\n const state = builder.__state()\n if (state.unique) {\n indexes.push({\n name: `${t.__name}_${colKey}_unique`,\n columns: [colKey],\n unique: true,\n })\n }\n if (state.references) {\n // Resolve the FK thunk lazily — by extract time the table const has\n // been bound, so self-references (`() => self.id`) work.\n const ref = state.references.thunk()\n foreignKeys.push({\n name: `${t.__name}_${colKey}_fk`,\n columns: [colKey],\n refTable: ref.__tableName,\n refColumns: [ref.__name],\n onDelete: state.references.onDelete,\n onUpdate: state.references.onUpdate,\n })\n }\n }\n\n return { name: t.__name, columns, indexes, foreignKeys, checks: [] }\n}\n","import type {\n ColumnSnapshot,\n ForeignKeySnapshot,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n} from './types'\n\n/**\n * Render a SchemaSnapshot to TypeScript source matching the kickjs-db DSL.\n * Inverse of extractSnapshot().\n *\n * Naming: tables become exported `const`s with the same name. Constants\n * starting with digits get an underscore prefix to stay JS-valid.\n *\n * Limits (M1 — refined in M2/M3):\n * - No relations() emission. Adopter adds them manually post-introspect.\n * - No checks (M1 doesn't model CHECK constraints in the snapshot).\n * - Default values pass through as-is. The DSL accepts string defaults,\n * so 'true' / 'CURRENT_TIMESTAMP' / \"'foo'\" all round-trip.\n * - Auto-derived constraint names (`<table>_<col>_unique`, `<table>_<col>_fk`)\n * are detected and rendered as the chained .unique() / .references() form.\n * Custom-named constraints fall back to the third-arg callback / FK helper.\n */\nexport function renderSchemaSource(snapshot: SchemaSnapshot): string {\n const usedColumnHelpers = new Set<string>()\n const tableSources: string[] = []\n\n // First pass: render every table, accumulating which column helpers we used.\n for (const table of Object.values(snapshot.tables)) {\n tableSources.push(renderTable(table, usedColumnHelpers))\n }\n\n const helpers = ['table', ...Array.from(usedColumnHelpers).toSorted()]\n // Common constraint helpers used by tables with secondary objects.\n const needsIndex = Object.values(snapshot.tables).some((t) =>\n t.indexes.some((i) => !isAutoUniqueName(t.name, i)),\n )\n if (needsIndex) helpers.push('index')\n const needsUnique = Object.values(snapshot.tables).some((t) =>\n t.indexes.some((i) => i.unique && !isAutoUniqueName(t.name, i)),\n )\n if (needsUnique && !helpers.includes('unique')) helpers.push('unique')\n\n const importLine = `import { ${helpers.join(', ')} } from '@forinda/kickjs-db'`\n return [importLine, '', ...tableSources].join('\\n').trimEnd() + '\\n'\n}\n\nfunction renderTable(table: TableSnapshot, helpers: Set<string>): string {\n const ident = jsIdent(table.name)\n const columns: string[] = []\n for (const col of Object.values(table.columns)) {\n const fk = table.foreignKeys.find(\n (f) =>\n f.columns.length === 1 &&\n f.columns[0] === col.name &&\n f.name === `${table.name}_${col.name}_fk`,\n )\n const inlineUnique =\n table.indexes.find(\n (i) =>\n i.unique &&\n i.columns.length === 1 &&\n i.columns[0] === col.name &&\n isAutoUniqueName(table.name, i),\n ) !== undefined\n columns.push(` ${jsKey(col.name)}: ${renderColumn(col, helpers, fk, inlineUnique)},`)\n }\n\n // Constraints that don't fit on a column chain.\n const explicitIndexes = table.indexes.filter((i) => !isAutoUniqueName(table.name, i))\n const explicitFks = table.foreignKeys.filter(\n (f) => f.name !== `${table.name}_${f.columns[0]}_fk` || f.columns.length !== 1,\n )\n\n const hasThirdArg = explicitIndexes.length > 0\n const tableArgs: string[] = [`'${table.name}'`, `{\\n${columns.join('\\n')}\\n}`]\n\n if (hasThirdArg) {\n const callbacks = explicitIndexes\n .map((i) => ` ${jsKey(i.name)}: ${renderIndexCall(i)}`)\n .join(',\\n')\n tableArgs.push(`(t) => ({\\n${callbacks},\\n })`)\n }\n\n let src = `export const ${ident} = table(${tableArgs.join(', ')})`\n\n // Explicit FKs that don't fit the auto-derived <table>_<col>_fk pattern get\n // logged as TODO comments — adopter handles them manually. M3 may upgrade\n // this to emit a separate ALTER snippet.\n if (explicitFks.length > 0) {\n src +=\n '\\n// TODO: kick db introspect — composite or custom-named foreign keys not auto-rendered:\\n'\n for (const f of explicitFks) {\n src += `// ${f.name}: (${f.columns.join(', ')}) → ${f.refTable}(${f.refColumns.join(', ')})\\n`\n }\n }\n\n return src\n}\n\nfunction renderColumn(\n col: ColumnSnapshot,\n helpers: Set<string>,\n fk: ForeignKeySnapshot | undefined,\n inlineUnique: boolean,\n): string {\n const { helperName, args } = pickColumnHelper(col)\n helpers.add(helperName)\n\n let chain = `${helperName}(${args})`\n if (col.primaryKey) chain += '.primaryKey()'\n if (!col.primaryKey && !col.nullable) chain += '.notNull()'\n if (col.default !== null) chain += `.default(${JSON.stringify(col.default)})`\n if (inlineUnique) chain += '.unique()'\n if (fk) {\n const ref = `${jsIdent(fk.refTable)}.${jsIdent(fk.refColumns[0])}`\n const onDelete = fk.onDelete === 'no_action' ? '' : `, { onDelete: '${fk.onDelete}' }`\n chain += `.references(() => ${ref}${onDelete})`\n }\n return chain\n}\n\nfunction pickColumnHelper(col: ColumnSnapshot): { helperName: string; args: string } {\n // Strip array suffix; render as base type + .array() chain in renderColumn\n // (M2 — for now arrays land as a literal `<T>[]` type which the DSL doesn't\n // round-trip). For M1, just pick the closest helper.\n const t = col.type\n\n if (t === 'serial') return { helperName: 'serial', args: '' }\n if (t === 'bigserial') return { helperName: 'bigSerial', args: '' }\n if (t === 'smallserial') return { helperName: 'serial', args: '' }\n if (t === 'integer') return { helperName: 'integer', args: '' }\n if (t === 'bigint') return { helperName: 'bigint', args: '' }\n if (t === 'smallint') return { helperName: 'smallint', args: '' }\n if (t === 'real') return { helperName: 'real', args: '' }\n if (t === 'double precision') return { helperName: 'doublePrecision', args: '' }\n if (/^numeric(\\(.+\\))?$/.test(t)) return { helperName: 'numeric', args: extractParens(t) }\n if (/^varchar(\\(\\d+\\))?$/.test(t)) return { helperName: 'varchar', args: extractParens(t) }\n if (/^char(\\(\\d+\\))?$/.test(t)) return { helperName: 'char', args: extractParens(t) }\n if (t === 'text') return { helperName: 'text', args: '' }\n if (t === 'boolean') return { helperName: 'boolean', args: '' }\n if (t === 'timestamp') return { helperName: 'timestamp', args: '' }\n if (t === 'timestamptz') return { helperName: 'timestamptz', args: '' }\n if (t === 'date') return { helperName: 'date', args: '' }\n if (t === 'time') return { helperName: 'time', args: '' }\n if (t === 'interval') return { helperName: 'interval', args: '' }\n if (t === 'uuid') return { helperName: 'uuid', args: '' }\n if (t === 'jsonb') return { helperName: 'jsonb', args: '' }\n if (t === 'json') return { helperName: 'json', args: '' }\n if (t === 'bytea') return { helperName: 'bytea', args: '' }\n\n // Fallback: emit as a comment + placeholder text() so the file still\n // parses. Adopter edits to the right helper.\n return { helperName: 'text', args: `/* TODO: ${t} */` }\n}\n\nfunction extractParens(t: string): string {\n const m = t.match(/\\(([^)]+)\\)/)\n return m ? m[1] : ''\n}\n\nfunction renderIndexCall(idx: IndexSnapshot): string {\n const helper = idx.unique ? 'unique' : 'index'\n const cols = idx.columns.map((c) => `t.${jsIdent(c)}`).join(', ')\n return `${helper}('${idx.name}').on(${cols})`\n}\n\nfunction isAutoUniqueName(tableName: string, idx: IndexSnapshot): boolean {\n return (\n idx.unique && idx.columns.length === 1 && idx.name === `${tableName}_${idx.columns[0]}_unique`\n )\n}\n\n/** Make a JS-safe identifier from a snake_case column/table name. */\nfunction jsIdent(raw: string): string {\n if (/^[A-Za-z_$][\\w$]*$/.test(raw)) return raw\n // Prefix digits-leading names with underscore.\n return `_${raw.replace(/[^\\w$]/g, '_')}`\n}\n\n/** Render a record key — quoted if not a valid identifier. */\nfunction jsKey(raw: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(raw) ? raw : JSON.stringify(raw)\n}\n","import type { SchemaSnapshot, TableSnapshot } from '../snapshot/types'\nimport type { Change, ChangeSet } from './types'\n\nexport function diff(prev: SchemaSnapshot, next: SchemaSnapshot): ChangeSet {\n const changes: Change[] = []\n\n const prevTables = new Set(Object.keys(prev.tables))\n const nextTables = new Set(Object.keys(next.tables))\n\n // Enum diffs run BEFORE table operations on the create side (so a new\n // table referencing a new enum sees the type already exist) and AFTER\n // table operations on the drop side (so a dropped enum can't have\n // dangling column references). Order: createEnum → addEnumValue →\n // table changes → dropEnum (appended at the end).\n diffEnumsCreatePhase(prev, next, changes)\n\n // Drops first (so FKs that depend on dropped tables are handled before drops below)\n for (const name of prevTables) {\n if (!nextTables.has(name)) {\n changes.push({ kind: 'dropTable', table: prev.tables[name] })\n }\n }\n\n // Creates — three passes so secondary objects only land after every new\n // table exists. Pass 1: every CREATE TABLE. Pass 2: every CREATE INDEX.\n // Pass 3: every ADD FOREIGN KEY. This keeps the order safe regardless of\n // ESM namespace iteration (which is alphabetical, not declaration order)\n // and lets each change kind map 1:1 to a SQL statement.\n const newTableNames = [...nextTables].filter((n) => !prevTables.has(n))\n for (const name of newTableNames) {\n changes.push({ kind: 'createTable', table: next.tables[name] })\n }\n for (const name of newTableNames) {\n for (const i of next.tables[name].indexes) {\n changes.push({ kind: 'addIndex', table: name, index: i })\n }\n }\n for (const name of newTableNames) {\n for (const f of next.tables[name].foreignKeys) {\n changes.push({ kind: 'addForeignKey', table: name, fk: f })\n }\n }\n\n // Common tables — column/index/fk diff comes in Tasks 10-12\n for (const name of nextTables) {\n if (!prevTables.has(name)) continue\n diffTable(prev.tables[name], next.tables[name], changes)\n }\n\n // Drop enums after every dependent table change has been emitted.\n diffEnumsDropPhase(prev, next, changes)\n\n return changes\n}\n\nfunction diffEnumsCreatePhase(prev: SchemaSnapshot, next: SchemaSnapshot, changes: Change[]) {\n const prevEnums = prev.enums ?? {}\n const nextEnums = next.enums ?? {}\n\n // New enums first.\n for (const [name, e] of Object.entries(nextEnums)) {\n if (prevEnums[name]) continue\n changes.push({ kind: 'createEnum', enum: e })\n }\n\n // ALTER TYPE ADD VALUE for non-destructive value additions on\n // existing enums. Removed values are NOT round-trippable without\n // dropping every column that references the type — those surface\n // as a `removeEnumValue` advisory the emitter turns into a SQL\n // comment with explicit operator guidance.\n for (const [name, e] of Object.entries(nextEnums)) {\n const prior = prevEnums[name]\n if (!prior) continue\n const priorValues = new Set(prior.values)\n const nextValues = new Set(e.values)\n const nextValueList = e.values\n\n let lastInsertedAt = -1\n for (let i = 0; i < nextValueList.length; i++) {\n const value = nextValueList[i]\n if (priorValues.has(value)) {\n lastInsertedAt = i\n continue\n }\n // New value — emit ADD VALUE. PG honours the BEFORE clause so\n // we preserve the declaration order on existing values.\n const before = nextValueList[i + 1]\n const beforeIsExisting = before != null && priorValues.has(before)\n changes.push({\n kind: 'addEnumValue',\n enum: name,\n value,\n ...(beforeIsExisting ? { before } : {}),\n })\n void lastInsertedAt\n }\n\n // Removed values — collect in declaration order from the prior\n // snapshot so the emitter list matches the order the operator\n // originally wrote.\n const removed = prior.values.filter((v) => !nextValues.has(v))\n if (removed.length > 0) {\n changes.push({\n kind: 'removeEnumValue',\n enum: name,\n removed,\n values: nextValueList,\n affectedColumns: collectColumnsByEnumType(next, name),\n })\n }\n }\n}\n\n/**\n * Walk the next snapshot for columns whose declared type matches the\n * enum being modified. The emitter rewrites each via\n * `ALTER TABLE … ALTER COLUMN … TYPE foo USING column::text::foo`\n * inside the rename-recreate block.\n */\nfunction collectColumnsByEnumType(\n snapshot: SchemaSnapshot,\n enumName: string,\n): { table: string; column: string }[] {\n const out: { table: string; column: string }[] = []\n for (const [tableName, table] of Object.entries(snapshot.tables)) {\n for (const [columnName, column] of Object.entries(table.columns)) {\n if (column.type === enumName) {\n out.push({ table: tableName, column: columnName })\n }\n }\n }\n return out\n}\n\nfunction diffEnumsDropPhase(prev: SchemaSnapshot, next: SchemaSnapshot, changes: Change[]) {\n const prevEnums = prev.enums ?? {}\n const nextEnums = next.enums ?? {}\n for (const [name, e] of Object.entries(prevEnums)) {\n if (nextEnums[name]) continue\n changes.push({ kind: 'dropEnum', enum: e })\n }\n}\n\nfunction diffTable(prev: TableSnapshot, next: TableSnapshot, changes: Change[]) {\n const prevCols = new Map(Object.entries(prev.columns))\n const nextCols = new Map(Object.entries(next.columns))\n\n const drops: string[] = []\n const adds: string[] = []\n for (const c of prevCols.keys()) if (!nextCols.has(c)) drops.push(c)\n for (const c of nextCols.keys()) if (!prevCols.has(c)) adds.push(c)\n\n // Rename heuristic — pair only if exactly one drop + one add with identical attrs.\n if (drops.length === 1 && adds.length === 1) {\n const before = prevCols.get(drops[0])!\n const after = nextCols.get(adds[0])!\n if (columnAttrsEqual(before, after)) {\n changes.push({ kind: 'renameColumn', table: next.name, from: drops[0], to: adds[0] })\n drops.length = 0\n adds.length = 0\n }\n }\n\n for (const c of drops) {\n changes.push({ kind: 'dropColumn', table: next.name, column: prevCols.get(c)! })\n }\n for (const c of adds) {\n changes.push({ kind: 'addColumn', table: next.name, column: nextCols.get(c)! })\n }\n\n // Common columns — alter detection\n for (const c of nextCols.keys()) {\n if (!prevCols.has(c)) continue\n const before = prevCols.get(c)!\n const after = nextCols.get(c)!\n if (!columnsEqual(before, after)) {\n changes.push({ kind: 'alterColumn', table: next.name, column: c, before, after })\n }\n }\n\n diffByName(\n prev.indexes,\n next.indexes,\n (i) => changes.push({ kind: 'dropIndex', table: next.name, index: i }),\n (i) => changes.push({ kind: 'addIndex', table: next.name, index: i }),\n )\n\n diffByName(\n prev.foreignKeys,\n next.foreignKeys,\n (f) => changes.push({ kind: 'dropForeignKey', table: next.name, fk: f }),\n (f) => changes.push({ kind: 'addForeignKey', table: next.name, fk: f }),\n )\n}\n\nfunction diffByName<T extends { name: string }>(\n prev: T[],\n next: T[],\n onDrop: (item: T) => void,\n onAdd: (item: T) => void,\n) {\n const prevByName = new Map(prev.map((p) => [p.name, p]))\n const nextByName = new Map(next.map((n) => [n.name, n]))\n for (const [n, p] of prevByName) if (!nextByName.has(n)) onDrop(p)\n for (const [n, x] of nextByName) if (!prevByName.has(n)) onAdd(x)\n}\n\nfunction columnsEqual(\n a: import('../snapshot/types').ColumnSnapshot,\n b: import('../snapshot/types').ColumnSnapshot,\n): boolean {\n return (\n a.type === b.type &&\n a.nullable === b.nullable &&\n a.default === b.default &&\n a.primaryKey === b.primaryKey\n )\n}\n\nfunction columnAttrsEqual(\n a: import('../snapshot/types').ColumnSnapshot,\n b: import('../snapshot/types').ColumnSnapshot,\n): boolean {\n // Like columnsEqual but ignores name (since rename is *about* name change).\n return (\n a.type === b.type &&\n a.nullable === b.nullable &&\n a.default === b.default &&\n a.primaryKey === b.primaryKey\n )\n}\n","import type { Change, ChangeSet } from './types'\n\n/**\n * Reverse a forward ChangeSet so emitting it produces the SQL that undoes\n * the forward migration.\n *\n * The reverse of an *unambiguous* change is exact (rename → rename swapped,\n * add → drop, drop → add). The reverse of an *ambiguous* change (drop column,\n * drop table, type widen, NOT NULL gain without default) is a defensible\n * best-effort derived from the snapshot the forward change carried — the\n * runner refuses to apply a non-reviewed migration in non-dev so the operator\n * always sees the draft before it touches a DB.\n *\n * The order is reversed too: drop FK before drop index before drop table is\n * the safe sequence for tearing down what create-FK / create-index / create-\n * table built up.\n */\nexport function invertChanges(forward: ChangeSet): ChangeSet {\n const reversed: Change[] = []\n for (const change of forward) {\n reversed.push(invert(change))\n }\n return reversed.toReversed()\n}\n\nfunction invert(change: Change): Change {\n switch (change.kind) {\n case 'createTable':\n return { kind: 'dropTable', table: change.table }\n case 'dropTable':\n return { kind: 'createTable', table: change.table }\n case 'renameTable':\n return { kind: 'renameTable', from: change.to, to: change.from }\n case 'addColumn':\n return { kind: 'dropColumn', table: change.table, column: change.column }\n case 'dropColumn':\n return { kind: 'addColumn', table: change.table, column: change.column }\n case 'renameColumn':\n return {\n kind: 'renameColumn',\n table: change.table,\n from: change.to,\n to: change.from,\n }\n case 'alterColumn':\n return {\n kind: 'alterColumn',\n table: change.table,\n column: change.column,\n before: change.after,\n after: change.before,\n }\n case 'addIndex':\n return { kind: 'dropIndex', table: change.table, index: change.index }\n case 'dropIndex':\n return { kind: 'addIndex', table: change.table, index: change.index }\n case 'addForeignKey':\n return { kind: 'dropForeignKey', table: change.table, fk: change.fk }\n case 'dropForeignKey':\n return { kind: 'addForeignKey', table: change.table, fk: change.fk }\n case 'createEnum':\n return { kind: 'dropEnum', enum: change.enum }\n case 'dropEnum':\n return { kind: 'createEnum', enum: change.enum }\n case 'addEnumValue':\n // PG can't ALTER TYPE … DROP VALUE without recreating the type +\n // touching every column that uses it. Down-migrations carry the\n // forward change verbatim; the operator gets a draft + a clear\n // signal that the down won't auto-revert.\n return change\n case 'removeEnumValue':\n // The forward direction of a value removal is itself an\n // advisory + manual operation; the reverse is symmetric. Carry\n // the change verbatim so the down draft surfaces the same\n // SQL-comment guidance, with `removed` listing the values that\n // would need to be re-added.\n return change\n }\n}\n\n/**\n * Returns the change kinds that produce ambiguous reverses — drop column,\n * drop table, type widen — so the generator can flag the down.sql as a draft\n * even if every individual statement is technically valid SQL.\n */\nconst AMBIGUOUS_REVERSE_KINDS = new Set<Change['kind']>([\n 'dropTable',\n 'dropColumn',\n 'alterColumn',\n // PG enum value additions can't auto-reverse — drop-value isn't\n // supported without recreating the type. The down draft surfaces\n // the forward statement so the operator manually rewrites it.\n 'addEnumValue',\n // Removed values can't auto-reverse for the symmetric reason: the\n // value(s) that disappeared from the schema may have been held by\n // existing rows whose state is already gone. Down draft preserves\n // the advisory comment.\n 'removeEnumValue',\n])\n\nexport function hasAmbiguousReverse(forward: ChangeSet): boolean {\n return forward.some((c) => AMBIGUOUS_REVERSE_KINDS.has(c.kind))\n}\n","import { KickDbError } from '../errors'\n\nexport class MigrationError extends KickDbError {}\n\nexport class MigrationLockError extends MigrationError {\n constructor(message: string) {\n super('migration_lock_held', message)\n }\n}\n\nexport interface SchemaDiffSummary {\n added: string[]\n removed: string[]\n changed: string[]\n}\n\nexport class MigrationDriftError extends MigrationError {\n readonly diff: SchemaDiffSummary\n\n constructor(message: string, diff: SchemaDiffSummary) {\n super('migration_drift', message)\n this.diff = diff\n }\n}\n\nexport class MigrationHashError extends MigrationError {\n readonly id: string\n readonly expected: string\n readonly actual: string\n\n constructor(id: string, expected: string, actual: string) {\n super('migration_hash_mismatch', `Hash mismatch for migration ${id}`)\n this.id = id\n this.expected = expected\n this.actual = actual\n }\n}\n\nexport class UnreviewedMigrationError extends MigrationError {\n readonly id: string\n\n constructor(id: string) {\n super(\n 'migration_unreviewed',\n `Migration ${id} has -- REVIEWED: false; flip the marker before applying outside dev`,\n )\n this.id = id\n }\n}\n\n/**\n * Thrown by the runner when a migration carries the `-- KICK ENUM\n * REMOVE` header and the operator hasn't passed `confirmEnumDrop:\n * true` (CLI: `--confirm-enum-drop`). Spec:\n * docs/db/spec-enum-value-removal.md §4.\n */\nexport class MigrationEnumDropError extends MigrationError {\n readonly id: string\n readonly enums: readonly string[]\n readonly removed: readonly string[]\n readonly columns: readonly string[]\n\n constructor(\n id: string,\n enums: readonly string[],\n removed: readonly string[],\n columns: readonly string[],\n ) {\n const enumList = enums.join(', ')\n const valueList = removed.join(', ')\n super(\n 'migration_enum_drop_unconfirmed',\n `Migration ${id} drops value(s) ${valueList} from PostgreSQL enum(s) ${enumList}. ` +\n `Re-run with \\`--confirm-enum-drop\\` (CLI) or \\`confirmEnumDrop: true\\` ` +\n `(RunnerOptions) after reviewing the column-USING clauses in up.sql.`,\n )\n this.id = id\n this.enums = enums\n this.removed = removed\n this.columns = columns\n }\n}\n","export function quoteIdent(name: string): string {\n return name\n .split('.')\n .map((part) => '\"' + part.replace(/\"/g, '\"\"') + '\"')\n .join('.')\n}\n\nexport function quoteLiteral(value: string): string {\n return \"'\" + value.replace(/'/g, \"''\") + \"'\"\n}\n","import type { Change, ChangeSet } from '../diff/types'\nimport type { ColumnSnapshot, TableSnapshot } from '../snapshot/types'\nimport { quoteIdent, quoteLiteral } from './identifiers'\n\nexport function emitPg(changes: ChangeSet): string {\n return changes.map(emitChange).join('\\n')\n}\n\nfunction emitChange(change: Change): string {\n switch (change.kind) {\n case 'createTable':\n return emitCreateTable(change.table)\n case 'dropTable':\n return `DROP TABLE ${quoteIdent(change.table.name)};`\n case 'renameTable':\n return `ALTER TABLE ${quoteIdent(change.from)} RENAME TO ${quoteIdent(change.to)};`\n case 'addColumn':\n return emitAddColumn(change.table, change.column)\n case 'dropColumn':\n return `ALTER TABLE ${quoteIdent(change.table)} DROP COLUMN ${quoteIdent(change.column.name)};`\n case 'renameColumn':\n return `ALTER TABLE ${quoteIdent(change.table)} RENAME COLUMN ${quoteIdent(change.from)} TO ${quoteIdent(change.to)};`\n case 'alterColumn':\n return emitAlterColumn(change.table, change.before, change.after)\n case 'addIndex':\n return emitAddIndex(change.table, change.index)\n case 'dropIndex':\n return `DROP INDEX ${quoteIdent(change.index.name)};`\n case 'addForeignKey':\n return emitAddFk(change.table, change.fk)\n case 'dropForeignKey':\n return `ALTER TABLE ${quoteIdent(change.table)} DROP CONSTRAINT ${quoteIdent(change.fk.name)};`\n case 'createEnum': {\n const values = change.enum.values.map((v) => quoteLiteral(v)).join(', ')\n return `CREATE TYPE ${quoteIdent(change.enum.name)} AS ENUM (${values});`\n }\n case 'dropEnum':\n return `DROP TYPE ${quoteIdent(change.enum.name)};`\n case 'addEnumValue': {\n const before = change.before ? ` BEFORE ${quoteLiteral(change.before)}` : ''\n return `ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`\n }\n case 'removeEnumValue':\n return emitRemoveEnumValueRecreate(change)\n }\n}\n\n/**\n * Magic header line that the migration runner detects to gate the\n * apply step behind `confirmEnumDrop`. Kept short + on its own line\n * so a `String.includes` is enough to find it. Any change to this\n * literal must also update the runner's check function.\n */\nexport const ENUM_DROP_HEADER = '-- KICK ENUM REMOVE'\n\n/**\n * Render the rename-recreate dance for a `pgEnum` value removal.\n *\n * ALTER TYPE foo RENAME TO foo__old\n * CREATE TYPE foo AS ENUM (…new value list…)\n * for each affected column:\n * ALTER TABLE T ALTER COLUMN C TYPE foo USING C::text::foo\n * DROP TYPE foo__old\n *\n * No explicit `BEGIN; … COMMIT;` — the runner wraps every up.sql\n * in `applySqlInTx` by default, and PG DDL is transactional, so\n * the four statements either all commit or all roll back. Wrapping\n * here would nest a transaction inside the runner's outer one,\n * which PG accepts (NOTICE-level warning) but commits early on the\n * inner COMMIT, defeating the runner's atomic-apply guarantee.\n *\n * The leading `-- KICK ENUM REMOVE` header is the runner's gate\n * signal — without `confirmEnumDrop`, the runner refuses to apply\n * before any DB write happens.\n *\n * Spec: docs/db/spec-enum-value-removal.md.\n */\nfunction emitRemoveEnumValueRecreate(change: {\n enum: string\n removed: readonly string[]\n values: readonly string[]\n affectedColumns: readonly { table: string; column: string }[]\n}): string {\n const safeName = sanitizeForLineComment(quoteIdent(change.enum))\n const removedList = change.removed.map((v) => sanitizeForLineComment(quoteLiteral(v))).join(', ')\n const columnsList = change.affectedColumns\n .map((c) => sanitizeForLineComment(`${c.table}.${c.column}`))\n .join(', ')\n\n const oldTypeName = quoteIdent(`${change.enum}__old`)\n const typeName = quoteIdent(change.enum)\n const valuesList = change.values.map((v) => quoteLiteral(v)).join(', ')\n\n const header = [\n ENUM_DROP_HEADER,\n `-- enum: ${safeName}`,\n `-- removed: ${removedList}`,\n `-- columns: ${columnsList || '(none)'}`,\n `--`,\n `-- This migration drops values from a PostgreSQL ENUM type. The`,\n `-- runner refuses to apply it without the --confirm-enum-drop flag`,\n `-- (or \\`confirmEnumDrop: true\\` in RunnerOptions). Inspect the`,\n `-- column USING clauses below to confirm rows holding a removed`,\n `-- value will fail loudly rather than silently coerce.`,\n ]\n\n const body: string[] = [\n `ALTER TYPE ${typeName} RENAME TO ${oldTypeName};`,\n `CREATE TYPE ${typeName} AS ENUM (${valuesList});`,\n ]\n for (const col of change.affectedColumns) {\n body.push(\n `ALTER TABLE ${quoteIdent(col.table)}`,\n ` ALTER COLUMN ${quoteIdent(col.column)} TYPE ${typeName}`,\n ` USING ${quoteIdent(col.column)}::text::${typeName};`,\n )\n }\n body.push(`DROP TYPE ${oldTypeName};`)\n\n return [...header, ...body].join('\\n')\n}\n\n/**\n * Make a value safe to interpolate into a single-line `--` SQL\n * comment. Identifiers and quoted literals normally don't carry\n * line breaks, but the user-supplied portion (enum name + values)\n * can contain anything an adopter passes to `pgEnum()`. A literal\n * `\\n` would terminate the comment early and turn the rest of the\n * line into executable SQL.\n *\n * Scope of the sanitiser:\n * - Line-break code points (`\\r`, `\\n`, `U+2028`, `U+2029`) collapse\n * runs to a single space so the comment stays on one line.\n * - C0 control bytes excluding tab (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F)\n * plus DEL (0x7F) escape to `\\x<hh>`.\n * - Tab (0x09) passes through — visually fine inside a `--` comment.\n *\n * Out of scope on purpose: C1 controls (U+0080-U+009F) and other\n * non-ASCII characters pass through unchanged. Adopters do legitimately\n * pass UTF-8 enum names + values (`'café'`, `'naïve'`); aggressively\n * escaping them would degrade the migration file's readability without\n * adding security — only line terminators can break out of a `--`\n * comment, and those are handled above.\n */\nfunction sanitizeForLineComment(value: string): string {\n // Walk code units rather than regex character classes \\u2014 control-char\n // regex literals trip `no-control-regex` lints and confuse some\n // editor analysers with \"unreachable\" warnings on the second\n // replace. Code-unit iteration is unambiguous: for every char we\n // either pass it through, collapse a line-break to a space, or\n // escape a control byte into `\\x<hh>`.\n let out = ''\n let prevWasLineBreak = false\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i)\n // Line-break code points \\u2192 collapse runs to a single space.\n // Includes \\r (0x0D), \\n (0x0A), U+2028 (LINE SEPARATOR),\n // U+2029 (PARAGRAPH SEPARATOR).\n const isLineBreak = code === 0x0a || code === 0x0d || code === 0x2028 || code === 0x2029\n if (isLineBreak) {\n if (!prevWasLineBreak) out += ' '\n prevWasLineBreak = true\n continue\n }\n prevWasLineBreak = false\n // Tab (0x09) passes through \\u2014 visually fine inside a `--` comment.\n // Other C0 control bytes (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F) and\n // DEL (0x7F) escape to `\\x<hh>` so the migration file stays\n // printable ASCII clean.\n const isControl =\n (code >= 0x00 && code <= 0x08) ||\n code === 0x0b ||\n code === 0x0c ||\n (code >= 0x0e && code <= 0x1f) ||\n code === 0x7f\n if (isControl) {\n out += `\\\\x${code.toString(16).padStart(2, '0')}`\n continue\n }\n out += value[i]\n }\n return out\n}\n\nfunction emitAddColumn(table: string, c: ColumnSnapshot): string {\n return `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`\n}\n\nfunction emitAlterColumn(table: string, before: ColumnSnapshot, after: ColumnSnapshot): string {\n const stmts: string[] = []\n const t = quoteIdent(table)\n const c = quoteIdent(after.name)\n\n const typeChanged = before.type !== after.type\n const nullChanged = before.nullable !== after.nullable\n const defaultChanged = before.default !== after.default\n const losingNotNull = !before.nullable && after.nullable\n\n if (typeChanged) {\n stmts.push(`ALTER TABLE ${t} ALTER COLUMN ${c} TYPE ${after.type} USING ${c}::${after.type};`)\n }\n\n // Default precedes nullable when loosening (DROP DEFAULT before DROP NOT NULL keeps\n // each interim state valid). Otherwise nullable precedes default (SET NOT NULL before\n // SET DEFAULT lets the default apply on the now-required column).\n const emitDefault = () => {\n if (!defaultChanged) return\n stmts.push(\n after.default === null\n ? `ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT;`\n : `ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${formatDefault(after.default)};`,\n )\n }\n const emitNullable = () => {\n if (!nullChanged) return\n stmts.push(\n `ALTER TABLE ${t} ALTER COLUMN ${c} ${after.nullable ? 'DROP NOT NULL' : 'SET NOT NULL'};`,\n )\n }\n\n if (losingNotNull) {\n emitDefault()\n emitNullable()\n } else {\n emitNullable()\n emitDefault()\n }\n\n return stmts.join('\\n')\n}\n\nfunction emitAddIndex(table: string, i: import('../snapshot/types').IndexSnapshot): string {\n const cols = i.columns.map(quoteIdent).join(', ')\n return `CREATE${i.unique ? ' UNIQUE' : ''} INDEX ${quoteIdent(i.name)} ON ${quoteIdent(table)} (${cols});`\n}\n\nconst FK_ACTIONS: Record<string, string> = {\n cascade: 'CASCADE',\n restrict: 'RESTRICT',\n set_null: 'SET NULL',\n set_default: 'SET DEFAULT',\n no_action: 'NO ACTION',\n}\n\nfunction emitAddFk(table: string, fk: import('../snapshot/types').ForeignKeySnapshot): string {\n const cols = fk.columns.map(quoteIdent).join(', ')\n const refCols = fk.refColumns.map(quoteIdent).join(', ')\n return (\n `ALTER TABLE ${quoteIdent(table)} ADD CONSTRAINT ${quoteIdent(fk.name)} ` +\n `FOREIGN KEY (${cols}) REFERENCES ${quoteIdent(fk.refTable)} (${refCols}) ` +\n `ON DELETE ${FK_ACTIONS[fk.onDelete]} ON UPDATE ${FK_ACTIONS[fk.onUpdate]};`\n )\n}\n\nfunction emitCreateTable(t: TableSnapshot): string {\n const cols = Object.values(t.columns).map(emitColumnDecl)\n const pk = Object.values(t.columns)\n .filter((c) => c.primaryKey)\n .map((c) => quoteIdent(c.name))\n const lines = [...cols]\n if (pk.length > 0) lines.push(`PRIMARY KEY (${pk.join(', ')})`)\n return `CREATE TABLE ${quoteIdent(t.name)} (\\n ${lines.join(',\\n ')}\\n);`\n}\n\nfunction emitColumnDecl(c: ColumnSnapshot): string {\n let s = `${quoteIdent(c.name)} ${c.type}`\n if (!c.nullable) s += ' NOT NULL'\n if (c.default !== null) s += ` DEFAULT ${formatDefault(c.default)}`\n return s\n}\n\nfunction formatDefault(value: string): string {\n // SQL keywords pass through bare.\n if (/^[A-Z_]+$/.test(value)) return value // CURRENT_TIMESTAMP, CURRENT_DATE, NULL, etc.\n // SQL function calls pass through bare: NOW(), gen_random_uuid(), etc.\n if (/^[a-z_][a-z0-9_]*\\s*\\([^)]*\\)$/i.test(value)) return value\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) return value // numeric\n if (value === 'true' || value === 'false') return value // boolean literal\n return quoteLiteral(value)\n}\n","/**\n * Runner gate for the `-- KICK ENUM REMOVE` header.\n *\n * Pure parser + decision function — no I/O, no adapter, no DB. The\n * runner reads up.sql, hands it to `parseEnumDropHeader`, and\n * passes the result to `enforceEnumDropGate` which throws\n * `MigrationEnumDropError` when the header is present and\n * `confirmEnumDrop` is falsy.\n *\n * Spec: docs/db/spec-enum-value-removal.md §4.\n */\n\nimport { ENUM_DROP_HEADER } from '../emit/pg'\nimport { MigrationEnumDropError } from './errors'\n\n/**\n * Parsed payload from the header block. Empty arrays for keys not\n * present (resilient to operators editing the migration by hand).\n */\nexport interface EnumDropHeader {\n enums: string[]\n removed: string[]\n columns: string[]\n}\n\n/**\n * Scan the first 64 lines of an up.sql for one or more enum-drop\n * header blocks. Returns null when no header is present.\n */\nexport function parseEnumDropHeader(sql: string): EnumDropHeader | null {\n if (!sql.includes(ENUM_DROP_HEADER)) return null\n\n const lines = sql.split(/\\r?\\n/, 64)\n const enums: string[] = []\n const removed: string[] = []\n const columns: string[] = []\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]?.trim() ?? ''\n if (line !== ENUM_DROP_HEADER) continue\n for (let j = i + 1; j < lines.length; j++) {\n const next = lines[j]?.trim() ?? ''\n if (!next.startsWith('--')) break\n const m = /^--\\s*([a-z]+):\\s*(.+)$/i.exec(next)\n if (!m) continue\n const key = m[1]!.toLowerCase()\n const raw = m[2]!.trim()\n if (key === 'enum') enums.push(raw)\n else if (key === 'removed') removed.push(...splitListing(raw))\n else if (key === 'columns') columns.push(...splitListing(raw))\n }\n }\n\n if (enums.length === 0 && removed.length === 0 && columns.length === 0) {\n return { enums: [], removed: [], columns: [] }\n }\n return { enums, removed, columns }\n}\n\n/**\n * Throws `MigrationEnumDropError` when the migration has an\n * enum-drop header and `confirmEnumDrop` is not set. Returns\n * silently otherwise.\n */\nexport function enforceEnumDropGate(\n id: string,\n sql: string,\n confirmEnumDrop: boolean,\n): EnumDropHeader | null {\n const header = parseEnumDropHeader(sql)\n if (!header) return null\n if (!confirmEnumDrop) {\n throw new MigrationEnumDropError(id, header.enums, header.removed, header.columns)\n }\n return header\n}\n\nfunction splitListing(raw: string): string[] {\n if (raw === '(none)' || raw === '') return []\n return raw\n .split(',')\n .map((s) => s.trim().replace(/^['\"`]|['\"`]$/g, ''))\n .filter((s) => s.length > 0)\n}\n","import { createHash } from 'node:crypto'\nimport { readFile, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport path from 'node:path'\n\nimport type { Dialect } from '../snapshot/types'\n\nexport interface JournalEntry {\n id: string\n tag: string\n hash: string\n createdAt: string\n}\n\nexport interface Journal {\n version: 1\n dialect: Dialect\n entries: JournalEntry[]\n}\n\nconst FILE = '_journal.json'\n\nexport async function readJournal(migrationsDir: string, dialect: Dialect): Promise<Journal> {\n const file = path.join(migrationsDir, FILE)\n if (!existsSync(file)) {\n return { version: 1, dialect, entries: [] }\n }\n const raw = JSON.parse(await readFile(file, 'utf8'))\n if (raw.version !== 1) {\n throw new Error(`_journal.json version ${raw.version} unsupported (expected 1)`)\n }\n return raw\n}\n\nexport async function appendJournalEntry(\n migrationsDir: string,\n dialect: Dialect,\n entry: JournalEntry,\n): Promise<void> {\n const j = await readJournal(migrationsDir, dialect)\n j.entries.push(entry)\n const file = path.join(migrationsDir, FILE)\n await writeFile(file, JSON.stringify(j, null, 2) + '\\n', 'utf8')\n}\n\nexport async function computeMigrationHash(migrationDir: string): Promise<string> {\n const up = await readFile(path.join(migrationDir, 'up.sql'), 'utf8')\n const down = await readFile(path.join(migrationDir, 'down.sql'), 'utf8')\n const snap = await readFile(path.join(migrationDir, 'snapshot.json'), 'utf8')\n const h = createHash('sha256')\n .update(up)\n .update('|')\n .update(down)\n .update('|')\n .update(snap)\n .digest('hex')\n return `sha256:${h}`\n}\n\nexport async function verifyMigrationHash(\n migrationDir: string,\n expected: string,\n): Promise<boolean> {\n const actual = await computeMigrationHash(migrationDir)\n return actual === expected\n}\n","import type { Dialect } from '../snapshot/types'\n\nexport const KICK_MIGRATIONS_TABLE = 'kick_migrations'\nexport const KICK_LOCK_TABLE = 'kick_migrations_lock'\n\nexport function migrationsTableDdl(dialect: Dialect): string {\n switch (dialect) {\n case 'postgres':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}\" (\n \"id\" varchar(128) PRIMARY KEY,\n \"name\" text NOT NULL,\n \"hash\" text NOT NULL,\n \"batch\" integer NOT NULL,\n \"applied_at\" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \"direction\" varchar(8) NOT NULL DEFAULT 'up'\n );\n CREATE INDEX IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}_batch_idx\" ON \"${KICK_MIGRATIONS_TABLE}\" (\"batch\");`\n case 'sqlite':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}\" (\n \"id\" text PRIMARY KEY,\n \"name\" text NOT NULL,\n \"hash\" text NOT NULL,\n \"batch\" integer NOT NULL,\n \"applied_at\" text NOT NULL DEFAULT (datetime('now')),\n \"direction\" text NOT NULL DEFAULT 'up'\n );\n CREATE INDEX IF NOT EXISTS \"${KICK_MIGRATIONS_TABLE}_batch_idx\" ON \"${KICK_MIGRATIONS_TABLE}\" (\"batch\");`\n case 'mysql':\n return `CREATE TABLE IF NOT EXISTS \\`${KICK_MIGRATIONS_TABLE}\\` (\n \\`id\\` varchar(128) PRIMARY KEY,\n \\`name\\` text NOT NULL,\n \\`hash\\` text NOT NULL,\n \\`batch\\` int NOT NULL,\n \\`applied_at\\` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,\n \\`direction\\` varchar(8) NOT NULL DEFAULT 'up',\n INDEX \\`${KICK_MIGRATIONS_TABLE}_batch_idx\\` (\\`batch\\`)\n );`\n }\n}\n\nexport function lockTableDdl(dialect: Dialect): string {\n switch (dialect) {\n case 'postgres':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_LOCK_TABLE}\" (\n \"id\" smallint PRIMARY KEY,\n \"locked_at\" timestamptz,\n \"locked_by\" text\n );\n INSERT INTO \"${KICK_LOCK_TABLE}\" (\"id\") VALUES (1) ON CONFLICT DO NOTHING;`\n case 'sqlite':\n return `CREATE TABLE IF NOT EXISTS \"${KICK_LOCK_TABLE}\" (\n \"id\" integer PRIMARY KEY,\n \"locked_at\" text,\n \"locked_by\" text\n );\n INSERT OR IGNORE INTO \"${KICK_LOCK_TABLE}\" (\"id\") VALUES (1);`\n case 'mysql':\n return `CREATE TABLE IF NOT EXISTS \\`${KICK_LOCK_TABLE}\\` (\n \\`id\\` smallint PRIMARY KEY,\n \\`locked_at\\` timestamp NULL,\n \\`locked_by\\` text\n );\n INSERT IGNORE INTO \\`${KICK_LOCK_TABLE}\\` (\\`id\\`) VALUES (1);`\n }\n}\n","import type { Dialect, SchemaSnapshot } from '../snapshot/types'\nimport type { MigrationAdapter, MigrationRow } from './adapter'\n\n/**\n * In-memory MigrationAdapter for unit tests. Lock semantics are exact (single-\n * holder atomic), but applySqlInTx / applySqlNoTx / introspect are shaped as\n * test-only stubs — the real DB-bound semantics are validated in db-pg's\n * integration tests, not here.\n */\nexport class MemoryMigrationAdapter implements MigrationAdapter {\n readonly dialect: Dialect = 'postgres'\n\n private rows: MigrationRow[] = []\n private locked: { by: string; at: string } | null = null\n private appliedSql: string[] = []\n private currentSchema: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n\n async ensureMigrationTables(): Promise<void> {\n /* no-op */\n }\n\n async listApplied(): Promise<MigrationRow[]> {\n return [...this.rows]\n }\n\n async recordApplied(row: Omit<MigrationRow, 'appliedAt'>): Promise<void> {\n this.rows.push({ ...row, appliedAt: new Date().toISOString() })\n }\n\n async removeApplied(id: string): Promise<void> {\n this.rows = this.rows.filter((r) => r.id !== id)\n }\n\n async acquireLock(owner: string): Promise<boolean> {\n if (this.locked) return false\n this.locked = { by: owner, at: new Date().toISOString() }\n return true\n }\n\n async releaseLock(): Promise<void> {\n this.locked = null\n }\n\n async applySqlInTx(sql: string): Promise<void> {\n this.appliedSql.push(sql)\n }\n\n async applySqlNoTx(sql: string): Promise<void> {\n this.appliedSql.push(sql)\n }\n\n async introspect(): Promise<SchemaSnapshot> {\n return this.currentSchema\n }\n\n async close(): Promise<void> {\n /* no-op */\n }\n\n /** Test-only setter — let drift tests stage a \"live\" schema state. */\n __setIntrospectedSchema(snap: SchemaSnapshot): void {\n this.currentSchema = snap\n }\n\n /** Test-only inspector — what SQL we received. */\n __appliedSql(): readonly string[] {\n return this.appliedSql\n }\n}\n","import type {\n ForeignKeySnapshot,\n FkAction,\n IndexSnapshot,\n SchemaSnapshot,\n TableSnapshot,\n} from '../snapshot/types'\nimport type { IntrospectPgOptions, PgQueryRunner } from './introspect-types'\n\nconst DEFAULT_EXCLUDED = ['kick_migrations', 'kick_migrations_lock']\n\ninterface ColumnRow {\n column_name: string\n data_type: string\n udt_name: string\n is_nullable: 'YES' | 'NO'\n column_default: string | null\n character_maximum_length: number | null\n numeric_precision: number | null\n numeric_scale: number | null\n}\n\ninterface IndexRow {\n index_name: string\n column_name: string\n is_unique: boolean\n is_primary: boolean\n}\n\ninterface FkRow {\n constraint_name: string\n column_name: string\n ref_table: string\n ref_column: string\n delete_rule: string\n update_rule: string\n}\n\nexport async function introspectPg(\n client: PgQueryRunner,\n opts: IntrospectPgOptions = {},\n): Promise<SchemaSnapshot> {\n const schema = opts.schema ?? 'public'\n const excluded = opts.excludeTables ?? DEFAULT_EXCLUDED\n\n const tableRows = await client.query<{ table_name: string }>(\n `SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = $1 AND table_type = 'BASE TABLE'\n ORDER BY table_name`,\n [schema],\n )\n\n const tables: Record<string, TableSnapshot> = {}\n for (const t of tableRows.rows) {\n if (excluded.includes(t.table_name)) continue\n tables[t.table_name] = {\n name: t.table_name,\n columns: await readColumns(client, schema, t.table_name),\n indexes: await readIndexes(client, schema, t.table_name),\n foreignKeys: await readForeignKeys(client, schema, t.table_name),\n checks: [],\n }\n }\n return { version: 1, dialect: 'postgres', tables }\n}\n\nasync function readColumns(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<TableSnapshot['columns']> {\n const cols = await client.query<ColumnRow>(\n `SELECT column_name, data_type, udt_name, is_nullable, column_default,\n character_maximum_length, numeric_precision, numeric_scale\n FROM information_schema.columns\n WHERE table_schema = $1 AND table_name = $2\n ORDER BY ordinal_position`,\n [schema, table],\n )\n\n const pkCols = await client.query<{ column_name: string }>(\n `SELECT k.column_name\n FROM information_schema.table_constraints c\n JOIN information_schema.key_column_usage k\n ON k.constraint_name = c.constraint_name\n AND k.table_schema = c.table_schema\n WHERE c.table_schema = $1 AND c.table_name = $2 AND c.constraint_type = 'PRIMARY KEY'\n ORDER BY k.ordinal_position`,\n [schema, table],\n )\n const pkSet = new Set(pkCols.rows.map((r) => r.column_name))\n\n const out: TableSnapshot['columns'] = {}\n for (const r of cols.rows) {\n const isSerial = isSerialColumn(r)\n out[r.column_name] = {\n name: r.column_name,\n type: isSerial ? serialTypeFor(r) : normalizeType(r),\n nullable: r.is_nullable === 'YES',\n // serial columns own their nextval default; collapse it to keep round-\n // trips (DSL → emit → introspect) idempotent.\n default: isSerial ? null : normalizeDefault(r.column_default),\n primaryKey: pkSet.has(r.column_name),\n }\n }\n return out\n}\n\nfunction isSerialColumn(r: ColumnRow): boolean {\n if (!r.column_default) return false\n if (!r.column_default.startsWith('nextval(')) return false\n return r.udt_name === 'int2' || r.udt_name === 'int4' || r.udt_name === 'int8'\n}\n\nfunction serialTypeFor(r: ColumnRow): string {\n if (r.udt_name === 'int8') return 'bigserial'\n if (r.udt_name === 'int2') return 'smallserial'\n return 'serial'\n}\n\nfunction normalizeType(r: ColumnRow): string {\n // Map PG's information_schema data_type back to the DSL surface.\n if (r.data_type === 'character varying') {\n return r.character_maximum_length ? `varchar(${r.character_maximum_length})` : 'varchar'\n }\n if (r.data_type === 'character') {\n return r.character_maximum_length ? `char(${r.character_maximum_length})` : 'char(1)'\n }\n if (r.data_type === 'numeric') {\n if (r.numeric_precision !== null && r.numeric_scale !== null) {\n return `numeric(${r.numeric_precision}, ${r.numeric_scale})`\n }\n if (r.numeric_precision !== null) return `numeric(${r.numeric_precision})`\n return 'numeric'\n }\n if (r.data_type === 'timestamp with time zone') return 'timestamptz'\n if (r.data_type === 'timestamp without time zone') return 'timestamp'\n if (r.data_type === 'time without time zone') return 'time'\n if (r.data_type === 'double precision') return 'double precision'\n if (r.data_type === 'USER-DEFINED') return r.udt_name\n if (r.data_type === 'ARRAY') {\n // udt_name for arrays is _<element>; strip and append [].\n const elem = r.udt_name.replace(/^_/, '')\n return `${elem}[]`\n }\n // bigint, integer, smallint, text, boolean, date, json, jsonb, bytea, uuid,\n // interval, etc — pass through as data_type when it matches the DSL.\n return r.data_type\n}\n\nfunction normalizeDefault(raw: string | null): string | null {\n if (!raw) return null\n // Strip PG's :: cast suffixes: 'true'::boolean → true, 'foo'::text → 'foo'\n const stripped = raw.replace(/::[\\w\" ]+(\\([^)]*\\))?$/, '')\n // Normalize CURRENT_TIMESTAMP / now() to the DSL canonical token.\n const upper = stripped.toUpperCase()\n if (upper === 'NOW()' || upper === 'CURRENT_TIMESTAMP') return 'CURRENT_TIMESTAMP'\n if (upper === 'GEN_RANDOM_UUID()') return 'gen_random_uuid()'\n // 'foo' literal → foo. true / false / numeric pass through.\n return stripped.replace(/^'(.*)'$/, '$1')\n}\n\nasync function readIndexes(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<IndexSnapshot[]> {\n const rows = await client.query<IndexRow>(\n `SELECT i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique AS is_unique,\n ix.indisprimary AS is_primary\n FROM pg_class t\n JOIN pg_namespace n ON n.oid = t.relnamespace\n JOIN pg_index ix ON ix.indrelid = t.oid\n JOIN pg_class i ON i.oid = ix.indexrelid\n JOIN unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord) ON true\n JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum\n WHERE n.nspname = $1 AND t.relname = $2 AND t.relkind = 'r'\n ORDER BY i.relname, k.ord`,\n [schema, table],\n )\n\n // Group rows by index_name, preserve column order.\n type Tagged = IndexSnapshot & { _isPrimary: boolean }\n const byIndex = new Map<string, Tagged>()\n for (const r of rows.rows) {\n let entry = byIndex.get(r.index_name)\n if (!entry) {\n entry = {\n name: r.index_name,\n columns: [],\n unique: r.is_unique,\n _isPrimary: r.is_primary,\n }\n byIndex.set(r.index_name, entry)\n }\n entry.columns.push(r.column_name)\n }\n\n // Drop PK-backing indexes — primaryKey is recorded on the column itself.\n return [...byIndex.values()]\n .filter((i) => !i._isPrimary)\n .map(({ _isPrimary, ...rest }) => rest)\n .toSorted((a, b) => a.name.localeCompare(b.name))\n}\n\nasync function readForeignKeys(\n client: PgQueryRunner,\n schema: string,\n table: string,\n): Promise<ForeignKeySnapshot[]> {\n const rows = await client.query<FkRow>(\n `SELECT tc.constraint_name,\n kcu.column_name,\n ccu.table_name AS ref_table,\n ccu.column_name AS ref_column,\n rc.delete_rule,\n rc.update_rule\n FROM information_schema.table_constraints tc\n JOIN information_schema.key_column_usage kcu\n ON kcu.constraint_name = tc.constraint_name\n AND kcu.table_schema = tc.table_schema\n JOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\n JOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = rc.unique_constraint_name\n AND ccu.constraint_schema = rc.unique_constraint_schema\n WHERE tc.table_schema = $1\n AND tc.table_name = $2\n AND tc.constraint_type = 'FOREIGN KEY'\n ORDER BY tc.constraint_name, kcu.ordinal_position`,\n [schema, table],\n )\n\n const byName = new Map<string, ForeignKeySnapshot>()\n for (const r of rows.rows) {\n let fk = byName.get(r.constraint_name)\n if (!fk) {\n fk = {\n name: r.constraint_name,\n columns: [],\n refTable: r.ref_table,\n refColumns: [],\n onDelete: mapFkAction(r.delete_rule),\n onUpdate: mapFkAction(r.update_rule),\n }\n byName.set(r.constraint_name, fk)\n }\n fk.columns.push(r.column_name)\n fk.refColumns.push(r.ref_column)\n }\n return [...byName.values()].toSorted((a, b) => a.name.localeCompare(b.name))\n}\n\nfunction mapFkAction(raw: string): FkAction {\n switch (raw.toUpperCase()) {\n case 'CASCADE':\n return 'cascade'\n case 'RESTRICT':\n return 'restrict'\n case 'SET NULL':\n return 'set_null'\n case 'SET DEFAULT':\n return 'set_default'\n case 'NO ACTION':\n default:\n return 'no_action'\n }\n}\n","import { diff } from '../diff/engine'\nimport type { Change } from '../diff/types'\nimport type { SchemaSnapshot } from '../snapshot/types'\nimport { MigrationDriftError, type SchemaDiffSummary } from './errors'\n\nexport type DriftBehavior = 'error' | 'warn' | 'ignore'\n\nexport interface DriftLogger {\n warn: (message: string) => void\n}\n\nexport async function checkDrift(\n liveSnapshot: SchemaSnapshot,\n expectedSnapshot: SchemaSnapshot,\n behavior: DriftBehavior,\n log: DriftLogger = console,\n): Promise<void> {\n if (behavior === 'ignore') return\n // diff(prev, next) reads expected as `prev` and live as `next` so 'added'\n // means \"live has it but the snapshot doesn't\" — i.e. someone ran DDL\n // outside the migration runner.\n const changes = diff(expectedSnapshot, liveSnapshot)\n if (changes.length === 0) return\n\n const summary = summarize(changes)\n const message = `Schema drift detected: ${summary.added.length} added, ${summary.removed.length} removed, ${summary.changed.length} changed`\n if (behavior === 'warn') {\n log.warn(message)\n return\n }\n throw new MigrationDriftError(message, summary)\n}\n\nfunction summarize(changes: Change[]): SchemaDiffSummary {\n const added: string[] = []\n const removed: string[] = []\n const changed: string[] = []\n for (const c of changes) {\n switch (c.kind) {\n case 'createTable':\n added.push(c.table.name)\n break\n case 'dropTable':\n removed.push(c.table.name)\n break\n case 'addColumn':\n added.push(`${c.table}.${c.column.name}`)\n break\n case 'dropColumn':\n removed.push(`${c.table}.${c.column.name}`)\n break\n case 'alterColumn':\n changed.push(`${c.table}.${c.column}`)\n break\n case 'renameColumn':\n changed.push(`${c.table}.${c.from}→${c.to}`)\n break\n case 'renameTable':\n changed.push(`${c.from}→${c.to}`)\n break\n case 'addIndex':\n added.push(`${c.table}#${c.index.name}`)\n break\n case 'dropIndex':\n removed.push(`${c.table}#${c.index.name}`)\n break\n case 'addForeignKey':\n added.push(`${c.table}!${c.fk.name}`)\n break\n case 'dropForeignKey':\n removed.push(`${c.table}!${c.fk.name}`)\n break\n }\n }\n return { added, removed, changed }\n}\n","import path from 'node:path'\nimport { readFile } from 'node:fs/promises'\n\nimport { readJournal, computeMigrationHash } from './journal'\nimport { MigrationLockError, MigrationHashError, UnreviewedMigrationError } from './errors'\nimport { checkDrift, type DriftBehavior, type DriftLogger } from './drift'\nimport { enforceEnumDropGate } from './enum-drop-gate'\nimport type { MigrationAdapter } from './adapter'\nimport type { SchemaSnapshot } from '../snapshot/types'\n\nexport interface RunnerOptions {\n adapter: MigrationAdapter\n migrationsDir: string\n /** When true, refuse to apply migrations whose meta.json.reviewed is false. Defaults to true outside dev. */\n requireReviewed?: boolean\n /** Owner string written into the lock table for diagnostics. */\n owner?: string\n /** Drift detection mode. Default 'error'. */\n driftCheck?: DriftBehavior\n /** Logger surface for drift warnings. Defaults to console. */\n log?: DriftLogger\n /**\n * Allow migrations carrying the `-- KICK ENUM REMOVE` header to\n * apply. Default `false`. CLI exposes via `--confirm-enum-drop`.\n * Spec: docs/db/spec-enum-value-removal.md.\n */\n confirmEnumDrop?: boolean\n}\n\nexport interface AppliedSummary {\n applied: string[]\n batch: number | null\n}\n\ninterface PreparedEntry {\n id: string\n tag: string\n hash: string\n}\n\nasync function withLock<T>(opts: RunnerOptions, fn: () => Promise<T>): Promise<T> {\n const owner = opts.owner ?? `${process.pid}@${new Date().toISOString()}`\n const got = await opts.adapter.acquireLock(owner)\n if (!got) {\n throw new MigrationLockError('Another process holds the migration lock')\n }\n try {\n return await fn()\n } finally {\n await opts.adapter.releaseLock()\n }\n}\n\n/**\n * Verify pending entries: hash matches stored, meta.reviewed is true (if\n * requireReviewed). Throws MigrationHashError or UnreviewedMigrationError on\n * the first failure.\n */\nasync function verifyPending(\n pending: PreparedEntry[],\n migrationsDir: string,\n requireReviewed: boolean,\n): Promise<void> {\n for (const entry of pending) {\n const dir = path.join(migrationsDir, entry.id)\n const actualHash = await computeMigrationHash(dir)\n if (actualHash !== entry.hash) {\n throw new MigrationHashError(entry.id, entry.hash, actualHash)\n }\n if (requireReviewed) {\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8'))\n if (meta.reviewed !== true) {\n throw new UnreviewedMigrationError(entry.id)\n }\n }\n }\n}\n\nasync function applyEntry(entry: PreparedEntry, batch: number, opts: RunnerOptions): Promise<void> {\n const dir = path.join(opts.migrationsDir, entry.id)\n const upSql = await readFile(path.join(dir, 'up.sql'), 'utf8')\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8'))\n const useTx = meta.transaction !== false\n\n // Enum-drop gate runs before any DB write so the runner can refuse\n // a destructive migration without partial application.\n enforceEnumDropGate(entry.id, upSql, opts.confirmEnumDrop ?? false)\n\n if (useTx) {\n await opts.adapter.applySqlInTx(upSql)\n } else {\n await opts.adapter.applySqlNoTx(upSql)\n }\n await opts.adapter.recordApplied({\n id: entry.id,\n name: entry.tag,\n hash: entry.hash,\n batch,\n direction: 'up',\n })\n}\n\nasync function runForward(opts: RunnerOptions, pending: PreparedEntry[]): Promise<AppliedSummary> {\n if (pending.length === 0) {\n return { applied: [], batch: null }\n }\n\n const requireReviewed = opts.requireReviewed ?? process.env.NODE_ENV !== 'development'\n await verifyPending(pending, opts.migrationsDir, requireReviewed)\n\n const applied = await opts.adapter.listApplied()\n const nextBatch = (applied.length === 0 ? 0 : Math.max(...applied.map((r) => r.batch))) + 1\n\n const ids: string[] = []\n for (const entry of pending) {\n await applyEntry(entry, nextBatch, opts)\n ids.push(entry.id)\n }\n return { applied: ids, batch: nextBatch }\n}\n\nasync function listPending(opts: RunnerOptions): Promise<PreparedEntry[]> {\n const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect)\n const applied = await opts.adapter.listApplied()\n const appliedIds = new Set(applied.map((r) => r.id))\n return journal.entries\n .filter((e) => !appliedIds.has(e.id))\n .map((e) => ({ id: e.id, tag: e.tag, hash: e.hash }))\n}\n\nasync function maybeCheckDrift(opts: RunnerOptions): Promise<void> {\n const behavior = opts.driftCheck ?? 'error'\n if (behavior === 'ignore') return\n const applied = await opts.adapter.listApplied()\n if (applied.length === 0) return // nothing to compare against\n const sorted = [...applied].toSorted((a, b) =>\n a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt),\n )\n const last = sorted[sorted.length - 1]\n let expected: SchemaSnapshot\n try {\n expected = JSON.parse(\n await readFile(path.join(opts.migrationsDir, last.id, 'snapshot.json'), 'utf8'),\n )\n } catch {\n return // snapshot missing — diagnostic, not fatal here\n }\n const live = await opts.adapter.introspect()\n await checkDrift(live, expected, behavior, opts.log)\n}\n\nexport async function migrateLatest(opts: RunnerOptions): Promise<AppliedSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n await maybeCheckDrift(opts)\n const pending = await listPending(opts)\n return runForward(opts, pending)\n })\n}\n\nexport async function migrateUp(opts: RunnerOptions): Promise<AppliedSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n await maybeCheckDrift(opts)\n const pending = await listPending(opts)\n return runForward(opts, pending.slice(0, 1))\n })\n}\n\nexport interface ReversedSummary {\n reversed: string | null\n}\n\nasync function applyReverse(id: string, opts: RunnerOptions): Promise<void> {\n const dir = path.join(opts.migrationsDir, id)\n const downSql = await readFile(path.join(dir, 'down.sql'), 'utf8')\n const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8'))\n const requireReviewed = opts.requireReviewed ?? process.env.NODE_ENV !== 'development'\n if (requireReviewed && meta.reviewed !== true) {\n throw new UnreviewedMigrationError(id)\n }\n const useTx = meta.transaction !== false\n if (useTx) {\n await opts.adapter.applySqlInTx(downSql)\n } else {\n await opts.adapter.applySqlNoTx(downSql)\n }\n await opts.adapter.removeApplied(id)\n}\n\nexport async function migrateDown(opts: RunnerOptions): Promise<ReversedSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n const applied = await opts.adapter.listApplied()\n if (applied.length === 0) return { reversed: null }\n // Sort by batch then appliedAt so 'most recent' is unambiguous even if\n // two migrations share a batch number (same `migrate latest` run).\n const sorted = [...applied].toSorted((a, b) =>\n a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt),\n )\n const last = sorted[sorted.length - 1]\n await applyReverse(last.id, opts)\n return { reversed: last.id }\n })\n}\n\nexport interface RollbackSummary {\n reversed: string[]\n batch: number | null\n}\n\nexport interface StatusEntry {\n id: string\n tag: string\n hash: string\n state: 'applied' | 'pending'\n batch: number | null\n appliedAt: string | null\n reviewed: boolean\n}\n\nexport async function migrateStatus(\n opts: Pick<RunnerOptions, 'adapter' | 'migrationsDir'>,\n): Promise<StatusEntry[]> {\n await opts.adapter.ensureMigrationTables()\n const journal = await readJournal(opts.migrationsDir, opts.adapter.dialect)\n const applied = await opts.adapter.listApplied()\n const byId = new Map(applied.map((r) => [r.id, r]))\n\n const entries: StatusEntry[] = []\n for (const e of journal.entries) {\n const row = byId.get(e.id)\n let reviewed = false\n try {\n const meta = JSON.parse(\n await readFile(path.join(opts.migrationsDir, e.id, 'meta.json'), 'utf8'),\n )\n reviewed = meta.reviewed === true\n } catch {\n // Missing meta.json — treat as un-reviewed; the runner will refuse to\n // apply anyway. Don't fail status output for diagnostic purposes.\n }\n entries.push({\n id: e.id,\n tag: e.tag,\n hash: e.hash,\n state: row ? 'applied' : 'pending',\n batch: row?.batch ?? null,\n appliedAt: row?.appliedAt ?? null,\n reviewed,\n })\n }\n return entries\n}\n\nexport async function migrateRollback(opts: RunnerOptions): Promise<RollbackSummary> {\n await opts.adapter.ensureMigrationTables()\n return withLock(opts, async () => {\n const applied = await opts.adapter.listApplied()\n if (applied.length === 0) return { reversed: [], batch: null }\n\n const lastBatch = Math.max(...applied.map((r) => r.batch))\n // Reverse-applied order so teardown matches dependencies (drop FK before\n // drop table etc).\n const targets = applied\n .filter((r) => r.batch === lastBatch)\n .toSorted((a, b) => a.appliedAt.localeCompare(b.appliedAt))\n .toReversed()\n\n const reversed: string[] = []\n for (const row of targets) {\n await applyReverse(row.id, opts)\n reversed.push(row.id)\n }\n return { reversed, batch: lastBatch }\n })\n}\n","import { defineAdapter } from '@forinda/kickjs'\nimport type { InjectionToken } from '@forinda/kickjs'\n\nimport { migrateLatest, migrateStatus } from './migrate/runner'\nimport type { MigrationAdapter } from './migrate/adapter'\nimport type { DriftBehavior } from './migrate/drift'\n\nexport type MigrationsOnBoot = 'fail-if-pending' | 'apply' | 'ignore'\n\nexport interface KickDbAdapterConfig {\n /** The driver-bound MigrationAdapter — pgAdapter() in @forinda/kickjs-db-pg, etc. */\n migrationAdapter: MigrationAdapter\n /** Directory containing the generated migrations + _journal.json. */\n migrationsDir: string\n /** Boot policy. Default 'fail-if-pending' — mirror the operator-explicit philosophy. */\n migrationsOnBoot?: MigrationsOnBoot\n /** Drift detection mode. Default 'error' outside dev. */\n driftCheck?: DriftBehavior\n /** Default true outside dev. */\n requireReviewed?: boolean\n /** Optional DI token to register the migrationAdapter under, for adopters who need direct access. */\n token?: InjectionToken<MigrationAdapter>\n /**\n * Optional KickEventBus the adapter publishes migration events to.\n * When set, `db:migration-applied` fires after a successful\n * `migrateLatest()` on boot (apply policy only). Pair with\n * `DEVTOOLS_BUS` so the events surface in the DevTools panel:\n *\n * import { DEVTOOLS_BUS } from '@forinda/kickjs-devtools-kit/bus/token'\n * // Resolve only when devtools is actually wired — adopters who\n * // skip @forinda/kickjs-devtools never register the token, and\n * // resolve() throws on missing tokens.\n * const adapter = kickDbAdapter({\n * ...,\n * bus: container.has(DEVTOOLS_BUS) ? container.resolve(DEVTOOLS_BUS) : undefined,\n * })\n *\n * Type imported via `import type` so kickjs-db keeps devtools-kit\n * as an optional peer.\n */\n bus?: import('@forinda/kickjs-devtools-kit/bus').KickEventBus\n}\n\n/**\n * KickJS lifecycle adapter for kickjs-db. Three jobs:\n *\n * 1. On boot, decide what to do about pending migrations per `migrationsOnBoot`.\n * - 'fail-if-pending' (default): throw if any pending exists. Operators\n * run `kick db migrate latest` explicitly before deploys land. Avoids\n * the prisma footgun where migrations silently apply on deploy.\n * - 'apply': run migrateLatest() automatically. Useful for dev / preview\n * environments where convenience matters more than safety.\n * - 'ignore': boot regardless. Last-resort escape hatch.\n * 2. On shutdown, close the migrationAdapter (drains the pool, etc).\n * 3. Register the migrationAdapter under an optional DI token so adopters\n * can pull it for ad-hoc tooling. The KickDbClient (Task 19b) registers\n * separately under DB_PRIMARY.\n */\nexport const kickDbAdapter = defineAdapter<KickDbAdapterConfig>({\n name: 'kickjs-db',\n build: (config) => ({\n async beforeStart({ container }) {\n const policy = config.migrationsOnBoot ?? 'fail-if-pending'\n const status = await migrateStatus({\n adapter: config.migrationAdapter,\n migrationsDir: config.migrationsDir,\n })\n const pending = status.filter((s) => s.state === 'pending')\n\n if (pending.length > 0) {\n if (policy === 'fail-if-pending') {\n throw new Error(\n `kickjs-db: ${pending.length} pending migration(s); run \\`kick db migrate latest\\` before boot`,\n )\n }\n if (policy === 'apply') {\n const result = await migrateLatest({\n adapter: config.migrationAdapter,\n migrationsDir: config.migrationsDir,\n requireReviewed: config.requireReviewed,\n driftCheck: config.driftCheck,\n })\n // Republish to DevTools when a bus is wired so the panel\n // can surface \"migrations ran on boot\" without polling.\n // `applied` is the list of migration ids the runner ran;\n // `batch` is the batch number the journal stamped them with.\n if (config.bus) {\n config.bus.emit('db:migration-applied', {\n applied: result.applied,\n batch: result.batch,\n })\n }\n }\n // 'ignore' falls through.\n }\n\n if (config.token) {\n container.registerFactory(config.token, () => config.migrationAdapter)\n }\n },\n async shutdown() {\n await config.migrationAdapter.close()\n },\n }),\n})\n","import { createToken, type InjectionToken } from '@forinda/kickjs'\n\nimport type { KickDbClient } from './client/types'\n\n// First-party tokens own the reserved `kick/` namespace. Adopter-defined\n// tokens (e.g. additional shards / read replicas beyond the default pair)\n// should use the adopter's own scope (e.g. `app/db/tenants`).\nexport const DB_PRIMARY: InjectionToken<KickDbClient> = createToken<KickDbClient>('kick/db/primary')\nexport const DB_REPLICA: InjectionToken<KickDbClient> = createToken<KickDbClient>('kick/db/replica')\n\n/**\n * Alias for the default DB. Adopters who only have one database can inject\n * `DB_CLIENT` instead of remembering whether it's primary/replica.\n */\nexport const DB_CLIENT = DB_PRIMARY\n","import { EventEmitter } from 'node:events'\nimport type { KickDbClientEvents } from './types'\n\ntype Listener<E extends keyof KickDbClientEvents> = (\n e: KickDbClientEvents[E],\n) => void | Promise<void>\n\n/**\n * Per-client typed event emitter. Wraps a Node EventEmitter to keep the\n * surface narrow (no `addListener`, no `removeAllListeners`, no `setMaxListeners`).\n *\n * The Kysely query interceptor surface is intentionally minimal in M1:\n * transactionStart/Commit/Rollback fire from createDbClient's transaction()\n * wrapper. The full beforeQuery / query / queryError emit pipeline lands in\n * M2 alongside `$extends` since it requires a proper Kysely query plugin\n * with access to the compiled SQL string + parameters. The types are stable\n * now so adopter code can wire listeners; only the runtime emit is deferred.\n */\nexport class KickDbEventEmitter {\n private readonly emitter = new EventEmitter()\n\n on<E extends keyof KickDbClientEvents>(event: E, listener: Listener<E>): void {\n this.emitter.on(event, listener as (...args: unknown[]) => void)\n }\n\n off<E extends keyof KickDbClientEvents>(event: E, listener: Listener<E>): void {\n this.emitter.off(event, listener as (...args: unknown[]) => void)\n }\n\n emit<E extends keyof KickDbClientEvents>(event: E, payload: KickDbClientEvents[E]): void {\n this.emitter.emit(event, payload)\n }\n}\n","// customType<T>() — adopter-defined column type with optional driver\n// codecs. Lets a project introduce a typed column that doesn't ship\n// in the built-in DSL (encrypted strings, custom JSON shapes, citext,\n// PostGIS geometry, etc.) without forking the package.\n//\n// Schema usage:\n//\n// const encrypted = customType<EncryptedString>({\n// dataType: () => 'text',\n// toDriver: (s) => encrypt(s),\n// fromDriver: (raw) => decrypt(String(raw)),\n// })\n//\n// export const secrets = table('secrets', {\n// id: serial().primaryKey(),\n// value: encrypted().notNull(),\n// })\n//\n// `SchemaToTypes<typeof schema>` reads the phantom T from the\n// CustomColumnBuilder so `db.selectFrom('secrets').select('value')`\n// types `value: EncryptedString` (not `string`). Driver codecs flow\n// through the lifecycle plugin landing in M2.F-T19; until then they\n// are stored on the builder for the runtime hookup to pick up.\n\nimport { ColumnBuilder } from './dsl/columns/types'\n\nexport interface CustomTypeOptions<TJs, TDriver = unknown> {\n /**\n * SQL data type as it would appear in `CREATE TABLE` — `'text'`,\n * `'jsonb'`, `'citext'`, `'geometry(Point, 4326)'`, etc. Returned\n * via a thunk so adopters can compute the type from runtime config\n * (e.g. dialect-specific overrides).\n */\n dataType: () => string\n /** Optional encode hook applied at insert / update time. */\n toDriver?: (value: TJs) => TDriver\n /** Optional decode hook applied to selected rows. */\n fromDriver?: (driver: TDriver) => TJs\n}\n\n/**\n * ColumnBuilder subclass produced by `customType()`. Carries the\n * driver codecs so the (future) hooks pipeline can wire them through\n * a Kysely plugin without each consumer re-declaring its mapping.\n *\n * The phantom `T` flows through `SchemaToTypes<S>` exactly like any\n * other ColumnBuilder<T>, so adopters get full row-shape inference\n * for free.\n */\nexport class CustomColumnBuilder<TJs> extends ColumnBuilder<TJs> {\n /** Encode hook — run on values heading into the database. */\n readonly toDriver?: (value: TJs) => unknown\n /** Decode hook — run on row values coming out of the database. */\n readonly fromDriver?: (driver: unknown) => TJs\n\n constructor(opts: CustomTypeOptions<TJs>) {\n super(opts.dataType())\n this.toDriver = opts.toDriver as never\n this.fromDriver = opts.fromDriver as never\n }\n}\n\n/**\n * Build a reusable column factory for a custom type. The returned\n * function is what callers use inside `table('foo', { col: factory() })`\n * — same shape as the built-in `varchar()`, `text()`, etc.\n *\n * @example\n * ```ts\n * const ulid = customType<string>({\n * dataType: () => 'char(26)',\n * toDriver: (s) => s,\n * fromDriver: (raw) => String(raw),\n * })\n *\n * const events = table('events', {\n * id: ulid().primaryKey(),\n * ts: timestamp().notNull().defaultNow(),\n * })\n * ```\n */\nexport function customType<TJs>(opts: CustomTypeOptions<TJs>): () => CustomColumnBuilder<TJs> {\n return () => new CustomColumnBuilder<TJs>(opts)\n}\n","// Codec plugin — wires CustomColumnBuilder codecs into Kysely.\n//\n// Two transforms in one plugin:\n//\n// - `transformQuery` walks the AST for INSERT and UPDATE statements\n// and applies `toDriver(value)` to every ValueNode whose surrounding\n// ColumnNode matches a column in the encoder map. Pass-through for\n// `insert ... select`, `defaultValues`, references, and other\n// non-literal value expressions.\n//\n// - `transformResult` walks selected rows and applies `fromDriver` per\n// matching column name. Null/undefined pass through so codecs don't\n// need a nullable branch.\n//\n// Both maps are keyed by COLUMN NAME (not table.column). Two tables\n// declaring the same name share a codec — the row shape returned from\n// joins doesn't always carry table provenance, so any table-aware\n// scheme would degrade silently. Adopters using clashing column names\n// across tables with different codecs should declare distinct\n// `customType` instances or rename the column.\n\nimport type {\n KyselyPlugin,\n PluginTransformQueryArgs,\n PluginTransformResultArgs,\n QueryResult,\n RootOperationNode,\n UnknownRow,\n} from 'kysely'\nimport {\n ColumnNode,\n ColumnUpdateNode,\n InsertQueryNode,\n PrimitiveValueListNode,\n UpdateQueryNode,\n ValueListNode,\n ValueNode,\n ValuesNode,\n type OperationNode,\n type ValuesItemNode,\n} from 'kysely'\n\nimport { CustomColumnBuilder } from '../custom-type'\nimport type { ColumnBuilder } from '../dsl/columns/types'\nimport type { TableDecl } from '../dsl/table'\n\n/** Map of column name → encoder/decoder. Built once at createDbClient time. */\nexport type CodecMap = Map<string, (value: unknown) => unknown>\n\nexport class CodecPlugin implements KyselyPlugin {\n constructor(\n private encoders: CodecMap,\n private decoders: CodecMap,\n ) {}\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n if (this.encoders.size === 0) return args.node\n const node = args.node\n if (InsertQueryNode.is(node)) return this.transformInsert(node)\n if (UpdateQueryNode.is(node)) return this.transformUpdate(node)\n return node\n }\n\n async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<UnknownRow>> {\n if (this.decoders.size === 0) return args.result\n const rows = args.result.rows.map((row) => this.decodeRow(row))\n return { ...args.result, rows }\n }\n\n // ---------------------------- query side ----------------------------\n\n private transformInsert(node: InsertQueryNode): InsertQueryNode {\n const cols = node.columns\n const values = node.values\n if (!cols || !values) return node\n // Build per-position encoder lookup once. Positions without a\n // matching encoder stay null so the inner loop can early-skip\n // without re-hashing on every row.\n const positional = this.positionalEncoders(cols)\n if (!positional) return node\n\n if (ValuesNode.is(values)) {\n const items = values.values.map((item) => this.encodeValuesItem(item, positional))\n // Reference equality preserved when no item changed.\n const changed = items.some((item, i) => item !== values.values[i])\n if (!changed) return node\n // ValuesItemNode is the public union ValueListNode | PrimitiveValueListNode;\n // every encodeValuesItem path either returns the original item (already a\n // ValuesItemNode) or rebuilds via the matching factory, so the cast holds.\n return InsertQueryNode.cloneWith(node, {\n values: ValuesNode.create(items as unknown as ReadonlyArray<ValuesItemNode>),\n })\n }\n\n // SelectQueryNode (insert from select), DefaultInsertValueNode, and\n // any future shape: pass through. We can't safely transform values\n // we didn't read literally.\n return node\n }\n\n private transformUpdate(node: UpdateQueryNode): UpdateQueryNode {\n const updates = node.updates\n if (!updates || updates.length === 0) return node\n\n let changed = false\n const next = updates.map((u) => {\n const col = u.column\n if (!ColumnNode.is(col)) return u\n const encoder = this.encoders.get(col.column.name)\n if (!encoder) return u\n const encoded = this.encodeValueNode(u.value, encoder)\n if (encoded === u.value) return u\n changed = true\n return ColumnUpdateNode.create(col, encoded)\n })\n if (!changed) return node\n // Kysely's UpdateQueryNode.cloneWithUpdates APPENDS to existing\n // updates rather than replacing them — wrong semantics for our\n // mutate-in-place flow. Spread directly. `node` is already\n // narrowed to UpdateQueryNode so the override typechecks cleanly.\n return { ...node, updates: next }\n }\n\n private positionalEncoders(\n cols: ReadonlyArray<ColumnNode>,\n ): Array<((v: unknown) => unknown) | null> | null {\n const out: Array<((v: unknown) => unknown) | null> = Array.from({ length: cols.length })\n let any = false\n for (let i = 0; i < cols.length; i++) {\n const enc = this.encoders.get(cols[i].column.name) ?? null\n out[i] = enc\n if (enc) any = true\n }\n return any ? out : null\n }\n\n private encodeValuesItem(\n item: OperationNode,\n positional: Array<((v: unknown) => unknown) | null>,\n ): OperationNode {\n if (ValueListNode.is(item)) {\n const next = item.values.map((v, i) => {\n const enc = positional[i]\n if (!enc) return v\n return this.encodeValueNode(v, enc)\n })\n const changed = next.some((v, i) => v !== item.values[i])\n return changed ? ValueListNode.create(next) : item\n }\n if (PrimitiveValueListNode.is(item)) {\n const next = item.values.map((v, i) => {\n const enc = positional[i]\n if (!enc) return v\n return this.encodePrimitive(v, enc)\n })\n const changed = next.some((v, i) => v !== item.values[i])\n return changed ? PrimitiveValueListNode.create(next) : item\n }\n return item\n }\n\n private encodeValueNode(node: OperationNode, encoder: (v: unknown) => unknown): OperationNode {\n if (!ValueNode.is(node)) return node\n const value = node.value\n if (value === null || value === undefined) return node\n const encoded = encoder(value)\n if (encoded === value) return node\n return ValueNode.create(encoded)\n }\n\n private encodePrimitive(value: unknown, encoder: (v: unknown) => unknown): unknown {\n if (value === null || value === undefined) return value\n return encoder(value)\n }\n\n // ---------------------------- result side ----------------------------\n\n private decodeRow(row: UnknownRow): UnknownRow {\n let mutated = false\n const out: Record<string, unknown> = {}\n for (const key of Object.keys(row)) {\n const value = (row as Record<string, unknown>)[key]\n const decoder = this.decoders.get(key)\n if (decoder && value !== null && value !== undefined) {\n out[key] = decoder(value)\n mutated = true\n } else {\n out[key] = value\n }\n }\n return (mutated ? out : row) as UnknownRow\n }\n}\n\n/**\n * Walk a schema record and collect decoders from every column whose\n * builder is a `CustomColumnBuilder` with a `fromDriver` codec set.\n */\nexport function buildDecoderMap(schema: unknown): CodecMap {\n return collectCodecs(schema, 'fromDriver')\n}\n\n/**\n * Walk a schema record and collect encoders from every column whose\n * builder is a `CustomColumnBuilder` with a `toDriver` codec set.\n */\nexport function buildEncoderMap(schema: unknown): CodecMap {\n return collectCodecs(schema, 'toDriver')\n}\n\nfunction collectCodecs(schema: unknown, key: 'toDriver' | 'fromDriver'): CodecMap {\n const out: CodecMap = new Map()\n if (!schema || typeof schema !== 'object') return out\n\n for (const value of Object.values(schema as Record<string, unknown>)) {\n if (!isTableDecl(value)) continue\n for (const [colName, col] of Object.entries(value.__columns)) {\n if (col instanceof CustomColumnBuilder) {\n const fn = col[key]\n if (fn) out.set(colName, fn as (v: unknown) => unknown)\n }\n }\n }\n return out\n}\n\nfunction isTableDecl(value: unknown): value is TableDecl<string, Record<string, ColumnBuilder>> {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __isTable?: boolean }).__isTable === true\n )\n}\n","// ResultExtensionPlugin — Kysely plugin that powers `$extends({ result })`.\n//\n// Two halves:\n//\n// 1. transformQuery walks SelectQueryNode + identifies the table,\n// then injects ColumnNode references for every `needs` column\n// not already in the SELECT list. Selects already using `*`\n// (SelectAllNode) skip injection — the column is implicitly\n// there.\n//\n// 2. transformResult walks the rows after the driver returns them,\n// runs each compute(row) per matching table, and assigns the\n// result to row[<computedKey>]. Null/undefined rows pass through\n// untouched.\n//\n// The two halves share state via a per-queryId Map so transformResult\n// only fires for queries this plugin marked in transformQuery — joins,\n// sub-selects, multi-table FROMs, and other shapes we can't reliably\n// attribute to a single table pass through both halves untouched.\n// Aliased single-table selects (`.from('posts as p')`) ARE supported —\n// the alias unwrap walks through to the underlying TableNode.\n\nimport {\n ColumnNode,\n ReferenceNode,\n SelectAllNode,\n SelectQueryNode,\n SelectionNode,\n TableNode,\n type KyselyPlugin,\n type OperationNode,\n type PluginTransformQueryArgs,\n type PluginTransformResultArgs,\n type QueryId,\n type QueryResult,\n type RootOperationNode,\n type UnknownRow,\n} from 'kysely'\n\nimport type { ResultExtension, ResultExtensions } from './types'\n\n/** Per-table computed-field bag. */\ntype TableExtensionBag = Record<string, ResultExtension<UnknownRow>>\n\nexport class ResultExtensionPlugin implements KyselyPlugin {\n private byTable: Map<string, TableExtensionBag>\n /**\n * Map of queryId → table name the query targets. Populated in\n * transformQuery, consumed in transformResult, deleted after use so\n * it doesn't leak across long-lived clients.\n */\n private pending = new Map<QueryId, string>()\n\n constructor(extensions: ResultExtensions<unknown>) {\n this.byTable = new Map()\n for (const [tableName, bag] of Object.entries(extensions)) {\n if (!bag) continue\n const entries = Object.entries(bag) as Array<[string, ResultExtension<UnknownRow>]>\n if (entries.length === 0) continue\n this.byTable.set(tableName, Object.fromEntries(entries))\n }\n }\n\n transformQuery(args: PluginTransformQueryArgs): RootOperationNode {\n const { node, queryId } = args\n if (!SelectQueryNode.is(node)) return node\n const tableName = singleTableTarget(node)\n if (!tableName) return node\n const bag = this.byTable.get(tableName)\n if (!bag) return node\n\n // Tag the query so transformResult knows to apply computeds.\n this.pending.set(queryId, tableName)\n\n return injectNeeds(node, bag)\n }\n\n async transformResult(args: PluginTransformResultArgs): Promise<QueryResult<UnknownRow>> {\n const tableName = this.pending.get(args.queryId)\n if (!tableName) return args.result\n this.pending.delete(args.queryId)\n\n const bag = this.byTable.get(tableName)\n if (!bag) return args.result\n const computeds = Object.entries(bag) as Array<[string, ResultExtension<UnknownRow>]>\n if (computeds.length === 0) return args.result\n\n const rows = args.result.rows.map((row) => {\n if (row === null || row === undefined) return row\n const base = row as Record<string, unknown>\n const next: Record<string, unknown> = { ...base }\n // Pass `base` (the pristine row, not `next`) into compute so\n // computeds can't read each other's outputs by accident — order\n // independence keeps the contract simple. Cross-computed\n // dependencies are an explicit non-feature.\n for (const [key, ext] of computeds) {\n try {\n next[key] = ext.compute(base as UnknownRow)\n } catch {\n // A throwing compute shouldn't poison the entire row set;\n // surface as undefined so the caller still gets the\n // pre-existing columns.\n next[key] = undefined\n }\n }\n return next as UnknownRow\n })\n return { ...args.result, rows }\n }\n}\n\n/**\n * Detect the single table this select reads from. Returns the table\n * name when from has exactly one TableNode (or AliasNode wrapping\n * one); returns null for joins, sub-selects, multi-table selects,\n * and anything we can't reliably attribute. The plugin only acts on\n * single-table selects in v1.\n */\nfunction singleTableTarget(node: SelectQueryNode): string | null {\n const from = node.from\n if (!from || from.froms.length !== 1) return null\n const target = unwrapAlias(from.froms[0])\n if (!TableNode.is(target)) return null\n return target.table.identifier.name\n}\n\nfunction unwrapAlias(node: OperationNode): OperationNode {\n // AliasNode wraps a child node in `.node`; we only care about the\n // underlying TableNode. Anything else passes through.\n if (node.kind === 'AliasNode') {\n const aliased = (node as unknown as { node: OperationNode }).node\n return aliased\n }\n return node\n}\n\n/**\n * Inject every needs column not already represented in the select\n * list. SelectAllNode (the `*` wildcard) means \"all columns\", in\n * which case there's nothing to add. Specific column references are\n * deduped by name so a column already selected explicitly stays put\n * exactly once.\n */\nfunction injectNeeds(node: SelectQueryNode, bag: TableExtensionBag): SelectQueryNode {\n const selections = node.selections ?? []\n // Wildcard select — every column is implicitly present.\n if (selections.some(isSelectAll)) return node\n\n const have = new Set<string>()\n for (const sel of selections) {\n const inner = sel.selection\n if (ReferenceNode.is(inner) && ColumnNode.is(inner.column)) {\n have.add(inner.column.column.name)\n } else if (ColumnNode.is(inner as OperationNode)) {\n have.add((inner as ColumnNode).column.name)\n }\n }\n\n const allNeeded = new Set<string>()\n for (const ext of Object.values(bag)) {\n for (const col of Object.keys(ext.needs)) {\n allNeeded.add(col)\n }\n }\n\n const missing = [...allNeeded].filter((c) => !have.has(c))\n if (missing.length === 0) return node\n\n const additions: SelectionNode[] = missing.map((col) =>\n SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))),\n )\n return SelectQueryNode.cloneWithSelections(node, additions)\n}\n\nfunction isSelectAll(node: SelectionNode): boolean {\n const inner = node.selection\n if (SelectAllNode.is(inner)) return true\n if (ReferenceNode.is(inner) && SelectAllNode.is(inner.column)) return true\n return false\n}\n","// Runtime for `$extends({ model, result })`.\n//\n// Two extension surfaces, applied in order:\n//\n// 1. **result extensions** rebuild the client around a Kysely\n// instance with the ResultExtensionPlugin appended. We can't\n// mutate plugins on a live Kysely (it freezes the plugin chain\n// at construction), but `qb.withPlugin(plugin)` returns a fresh\n// Kysely with the plugin added — that's what we wrap. The new\n// client shares the same InternalContext as the parent (events\n// emitter identity stays stable across extensions, transactions\n// keep working), but routes queries through the plugin.\n//\n// 2. **model extensions** layer a Proxy over whatever client the\n// previous step produced. The Proxy's `get` returns the per-\n// table method bag for keys that match a model entry; methods\n// are pre-bound via Function.prototype.call so `this` inside\n// the method is the extended proxy. That way chaining\n// `this.<otherTable>.<method>` or `this.transaction(...)`\n// resolves naturally regardless of which extension order ran.\n//\n// Lazy proxy reference: the bound methods need to capture `proxy`\n// itself, but the proxy can't exist until its handler is built.\n// Closure over a mutable `proxy` reference solves the cycle — by the\n// time any method actually runs, the binding has landed.\n\nimport type { KickDbClient } from '../client/types'\nimport type { ExtendedClient, ExtensionDefinition, ResultExtensions } from './types'\nimport { ResultExtensionPlugin } from './result-plugin'\nimport { wrap, type InternalContext } from '../client/wrap'\n\nexport function applyExtensions<DB, E extends ExtensionDefinition<DB>>(\n client: KickDbClient<DB>,\n ctx: InternalContext,\n ext: E,\n): ExtendedClient<DB, E> {\n // 1. Result extensions — rebuild Kysely around the plugin chain.\n // `wrap` and this module form an ESM cycle (wrap calls\n // applyExtensions for the client's `$extends`; we call wrap to\n // rebuild the client). ESM live bindings handle this fine as\n // long as nothing reads the binding at module top-level — both\n // sides only call into each other inside functions.\n let baseClient: KickDbClient<DB> = client\n if (hasResultExtensions(ext.result)) {\n const plugin = new ResultExtensionPlugin(ext.result as ResultExtensions<unknown>)\n const newQb = client.qb.withPlugin(plugin)\n baseClient = wrap<DB>(newQb, ctx)\n }\n\n // 2. Model proxy — layered on top of whichever base client we got\n // so model methods see the result-augmented row types via `this`.\n let proxy: ExtendedClient<DB, E>\n\n const modelBag: Record<string, Record<string, (...args: unknown[]) => unknown>> = {}\n const model = ext.model ?? {}\n for (const tableName of Object.keys(model) as (keyof typeof model)[]) {\n const methods = model[tableName]\n if (!methods) continue\n const bound: Record<string, (...args: unknown[]) => unknown> = {}\n for (const [methodName, fn] of Object.entries(methods)) {\n bound[methodName] = (...args) => (fn as (...a: unknown[]) => unknown).call(proxy, ...args)\n }\n modelBag[tableName as string] = bound\n }\n\n proxy = new Proxy(baseClient, {\n get(target, prop) {\n // Own-property check — `prop in modelBag` would also match\n // inherited keys like `toString` / `hasOwnProperty` from\n // Object.prototype, intercepting properties we never asked to\n // own and breaking the underlying client's own equivalents.\n if (typeof prop === 'string' && Object.prototype.hasOwnProperty.call(modelBag, prop)) {\n return modelBag[prop]\n }\n // Fall through. Bound methods on the underlying KickDbClient\n // (selectFrom, transaction, etc.) keep their original `this`\n // since `wrap()` already bound them to kysely at create time.\n const value = (target as unknown as Record<PropertyKey, unknown>)[prop as PropertyKey]\n return value\n },\n }) as ExtendedClient<DB, E>\n\n return proxy\n}\n\nfunction hasResultExtensions(result: unknown): boolean {\n if (!result || typeof result !== 'object') return false\n for (const bag of Object.values(result as Record<string, unknown>)) {\n if (bag && typeof bag === 'object' && Object.keys(bag as object).length > 0) return true\n }\n return false\n}\n","/**\n * Runtime wire-up for `db.query.X.findMany({ with })`.\n *\n * `attachQueryNamespace` wraps a `KickDbClient` with a `query`\n * Proxy that materializes a `TableQueryNamespace` on first\n * property access. Each method (`findMany` / `findFirst` /\n * `findUnique`) builds a `CompiledQuery` via the dialect-specific\n * compiler, hands it to the underlying Kysely instance to execute,\n * and returns the rows.\n *\n * The compile + execute split keeps the compiler pure and testable\n * (snapshot SQL fixtures in `query-compile.test.ts`) while the\n * builder owns the I/O.\n *\n * Spec: docs/db/spec-relational-query.md §5.2.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type { CompiledQuery, Kysely } from 'kysely'\nimport type { ResolvedRelations } from './relations'\nimport type { CompileMode, CompilePgOptions } from './compile-pg'\nimport type { FindManyOptions, QueryNamespace, TableQueryNamespace } from './types'\nimport type { TableSnapshot } from '../snapshot/types'\n\n/**\n * Dialect-specific compile function. PG ships `compilePg`;\n * SQLite ships `compileSqlite`; MySQL provides a stub that throws\n * `RelationalQueryNotSupportedError`. The signature matches\n * `compilePg` so swapping compilers is a one-line change.\n *\n * `tables` is the snapshot's table-by-name map; the compiler reads\n * each target's column list to emit explicit selections inside\n * `jsonArrayFrom` / `jsonObjectFrom` (SQLite requires it; PG\n * accepts either form).\n */\nexport type CompileFn = (\n qb: Kysely<any>,\n table: string,\n options: CompilePgOptions,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n mode: CompileMode,\n) => CompiledQuery\n\n/**\n * Build the per-table query namespace. The Proxy intercepts every\n * property access — adopters writing `db.query.users` get a fresh\n * namespace bound to that table name. The methods close over the\n * shared compiler + relations + tables + Kysely instance so each\n * call is independent.\n */\nexport function buildQueryNamespace<DB>(\n qb: Kysely<DB>,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n compile: CompileFn,\n): QueryNamespace<DB> {\n return new Proxy({} as QueryNamespace<DB>, {\n get(_target, prop) {\n if (typeof prop !== 'string') return undefined\n return makeTableNamespace(qb, prop as never, relations, tables, compile)\n },\n })\n}\n\nfunction makeTableNamespace<DB, Table extends keyof DB & string>(\n qb: Kysely<DB>,\n table: Table,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n compile: CompileFn,\n): TableQueryNamespace<DB, Table> {\n return {\n async findMany(options?: unknown) {\n const compiled = compile(\n qb as Kysely<any>,\n table,\n (options ?? {}) as CompilePgOptions,\n relations,\n tables,\n 'many',\n )\n const rows = await execute(qb, compiled)\n return rows as never\n },\n\n async findFirst(options?: unknown) {\n const compiled = compile(\n qb as Kysely<any>,\n table,\n (options ?? {}) as CompilePgOptions,\n relations,\n tables,\n 'first',\n )\n const rows = await execute(qb, compiled)\n return (rows[0] ?? null) as never\n },\n\n async findUnique(options: unknown) {\n const compiled = compile(\n qb as Kysely<any>,\n table,\n options as CompilePgOptions,\n relations,\n tables,\n 'unique',\n )\n const rows = await execute(qb, compiled)\n return (rows[0] ?? null) as never\n },\n } as unknown as TableQueryNamespace<DB, Table>\n}\n\n/**\n * Execute a `CompiledQuery` through Kysely's executor. Goes through\n * the same path Kysely's `.execute()` would — events, plugins, and\n * connection pooling all keep working without bypassing the wrapper.\n */\nasync function execute<DB>(qb: Kysely<DB>, compiled: CompiledQuery): Promise<unknown[]> {\n // `executeQuery` is the documented escape hatch for compiled\n // queries — used by Kysely itself when a transaction handler\n // builds and runs SQL programmatically.\n const result = await (\n qb as unknown as {\n executeQuery: (q: CompiledQuery) => Promise<{ rows: unknown[] }>\n }\n ).executeQuery(compiled)\n return result.rows\n}\n\n/**\n * Type alias used by the client wrap to declare the optional `query`\n * field without importing every helper individually.\n */\nexport type AttachedQuery<DB> = QueryNamespace<DB>\n\n/**\n * Per-options passthrough type — re-exported for contributors who\n * want to wrap the namespace (testing helpers, query loggers). Most\n * adopters never reach for this.\n */\nexport type AttachedFindManyOptions<DB, Table extends keyof DB & string> = FindManyOptions<\n DB,\n Table\n>\n","// Wraps a Kysely<DB> + InternalContext into a KickDbClient<DB>.\n//\n// Lives in its own module so consumers that need to rebuild the\n// client around a new Kysely instance — `$extends({ result })` adds a\n// result-extension Kysely plugin via `qb.withPlugin(...)`, then wraps\n// the new instance back into a client — can do so without an import\n// cycle through `client/create.ts`. Both `create.ts` and\n// `extend/apply.ts` import from here.\n//\n// `InternalContext` carries everything the wrap needs that lives\n// outside the Kysely instance itself: the lifecycle event emitter,\n// the cached dialect tag, and the savepoint counter. Sharing the same\n// ctx across re-wraps keeps the event listener identity stable —\n// adopters who attached `db.on('slowQuery', ...)` continue receiving\n// events from the rebuilt-after-`$extends` client.\n\nimport { Kysely, sql } from 'kysely'\n\nimport type { KickDbClient, TransactionEvent } from './types'\nimport { applyExtensions } from '../extend/apply'\nimport type { KickDbEventEmitter } from './events'\nimport type { CompileFn } from '../query/builder'\nimport { buildQueryNamespace } from '../query/builder'\nimport type { ResolvedRelations } from '../query/relations'\nimport type { TableSnapshot } from '../snapshot/types'\n\nexport interface InternalContext {\n events: KickDbEventEmitter | null\n dialect: KickDbClient['dialect']\n /** Increments per savepoint open inside this client; used for SP_<n> names. */\n savepointCounter: { value: number }\n /**\n * Resolved relation graph + per-table column metadata + dialect-\n * specific compiler for the relational-query namespace. Always\n * present after `createDbClient` runs — the compiler may be a\n * throw-stub for unsupported dialects (MySQL until M4.A.3).\n */\n query: {\n relations: ResolvedRelations\n tables: Record<string, TableSnapshot>\n compile: CompileFn\n }\n}\n\nexport function wrap<DB>(qb: Kysely<DB>, ctx: InternalContext): KickDbClient<DB> {\n const client: KickDbClient<DB> = {\n qb,\n dialect: ctx.dialect,\n query: buildQueryNamespace<DB>(qb, ctx.query.relations, ctx.query.tables, ctx.query.compile),\n\n selectFrom: qb.selectFrom.bind(qb),\n insertInto: qb.insertInto.bind(qb),\n updateTable: qb.updateTable.bind(qb),\n deleteFrom: qb.deleteFrom.bind(qb),\n\n on(event, listener) {\n ctx.events?.on(event, listener)\n return client\n },\n off(event, listener) {\n ctx.events?.off(event, listener)\n return client\n },\n\n transaction: ((\n a: TransactionEvent | ((tx: KickDbClient<DB>) => Promise<unknown>),\n b?: (tx: KickDbClient<DB>) => Promise<unknown>,\n ) => {\n const txOpts = typeof a === 'function' ? {} : a\n const fn = (typeof a === 'function' ? a : b) as (tx: KickDbClient<DB>) => Promise<unknown>\n\n const run = async () => {\n ctx.events?.emit('transactionStart', { isolation: txOpts.isolation })\n try {\n const result = await qb.transaction().execute(async (tx) => {\n if (txOpts.isolation) {\n const level = txOpts.isolation.toUpperCase()\n await sql.raw(`SET TRANSACTION ISOLATION LEVEL ${level}`).execute(tx)\n }\n const child = wrap<DB>(tx as unknown as Kysely<DB>, ctx)\n return await fn(child)\n })\n ctx.events?.emit('transactionCommit', { isolation: txOpts.isolation })\n return result\n } catch (err) {\n ctx.events?.emit('transactionRollback', {\n isolation: txOpts.isolation,\n error: err,\n })\n throw err\n }\n }\n return run()\n }) as KickDbClient<DB>['transaction'],\n\n $extends(ext) {\n return applyExtensions(client, ctx, ext)\n },\n\n async savepoint(fn) {\n const name = `sp_${++ctx.savepointCounter.value}`\n // Savepoints only make sense inside a transaction. The query\n // builder's transaction proxies route SQL through the same\n // connection; sql.raw() against the wrapper lands on that\n // connection's tx context.\n await sql.raw(`SAVEPOINT ${name}`).execute(qb)\n try {\n const result = await fn(wrap<DB>(qb, ctx))\n await sql.raw(`RELEASE SAVEPOINT ${name}`).execute(qb)\n return result\n } catch (err) {\n await sql.raw(`ROLLBACK TO SAVEPOINT ${name}`).execute(qb)\n throw err\n }\n },\n\n async destroy() {\n await qb.destroy()\n },\n }\n return client\n}\n","/**\n * Dialect-agnostic compile traversal for `db.query.X.findMany({ with })`.\n *\n * The compile algorithm is identical across PostgreSQL, SQLite, and\n * MySQL — only the JSON-aggregation primitives differ. Each dialect-\n * specific entry point (`compilePg`, `compileSqlite`, `compileMysql`)\n * passes its own `jsonArrayFrom` / `jsonObjectFrom` from the matching\n * `kysely/helpers/<dialect>` module into `runCompile`, which then\n * walks the `with` clause using shared helpers.\n *\n * Spec: docs/db/spec-relational-query-other-dialects.md §4.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport { type Kysely, type ExpressionBuilder, type Expression, type CompiledQuery } from 'kysely'\nimport { RelationalQueryDepthError, RelationalQueryUnknownRelationError } from './errors'\nimport type { ResolvedRelation, ResolvedRelations } from './relations'\nimport type { TableSnapshot } from '../snapshot/types'\n\nexport type CompileMode = 'many' | 'first' | 'unique'\n\nexport interface CompileOptions {\n where?: (table: any, ops: ExpressionBuilder<any, any>) => Expression<unknown>\n orderBy?: (\n table: any,\n ops: ExpressionBuilder<any, any>,\n ) => Expression<unknown> | Array<Expression<unknown>>\n limit?: number\n offset?: number\n maxDepth?: number\n with?: Record<string, true | CompileOptions>\n}\n\nconst DEFAULT_MAX_DEPTH = 5\n\n/**\n * Helper bag passed in from each dialect entry point. Same shape as\n * Kysely's per-dialect helpers — the only thing that varies between\n * `kysely/helpers/postgres`, `kysely/helpers/sqlite`, and\n * `kysely/helpers/mysql`.\n */\nexport interface JsonHelpers {\n jsonArrayFrom: (expr: Expression<unknown>) => Expression<unknown>\n jsonObjectFrom: (expr: Expression<unknown>) => Expression<unknown>\n}\n\n/**\n * Build a Proxy that maps property reads to Kysely column refs.\n * Adopters can write `(u, eb) => eb('id', '=', u.id)` and the runtime\n * resolves `u.id` to `eb.ref('users_0.id')`. Most call sites use the\n * underscored form (`(_u, eb) => eb('id', '=', x)`) and this Proxy\n * silently no-ops.\n */\nfunction makeTableRefProxy(eb: ExpressionBuilder<any, any>, alias: string): unknown {\n return new Proxy({} as Record<string, unknown>, {\n get(_target, prop) {\n if (typeof prop !== 'string') return undefined\n return eb.ref(`${alias}.${prop}`)\n },\n })\n}\n\n/**\n * Build a stable alias from a table name + depth index. The depth\n * suffix disambiguates self-referencing or cyclic relations. Outer\n * is `${name}_0`; nested levels increment.\n */\nfunction makeAlias(name: string, depth: number): string {\n return `${name}_${depth}`\n}\n\n/**\n * Top-level entry — dialect-specific compilers (`compilePg`,\n * `compileSqlite`, `compileMysql`) call this with the right Kysely\n * helper bag. Returns the compiled `{ sql, parameters }`.\n *\n * `tables` carries each target table's column list so inner\n * `jsonArrayFrom` / `jsonObjectFrom` subqueries can emit explicit\n * `.select([col1, col2, ...])` calls. SQLite's helper requires\n * this (the runtime can't infer the JSON object keys from\n * `.selectAll()`); PG's helper accepts either form.\n */\nexport function runCompile<DB>(\n db: Kysely<DB>,\n table: string,\n options: CompileOptions,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n mode: CompileMode,\n helpers: JsonHelpers,\n): CompiledQuery {\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH\n\n const outerAlias = makeAlias(table, 0)\n // Outer `.selectAll()` is fine — the helpers only restrict inner\n // subqueries passed to jsonArrayFrom / jsonObjectFrom.\n let query: any = (db.selectFrom(`${table} as ${outerAlias}` as any) as any).selectAll()\n\n if (options.with) {\n query = applyWithSelects(\n query,\n table,\n outerAlias,\n options.with,\n relations,\n tables,\n maxDepth,\n [outerAlias],\n helpers,\n )\n }\n\n query = applyWhereOrderLimit(query, outerAlias, options, mode)\n\n return query.compile() as CompiledQuery\n}\n\nfunction applyWithSelects(\n query: any,\n source: string,\n sourceAlias: string,\n withClause: Record<string, true | CompileOptions>,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n maxDepth: number,\n trace: readonly string[],\n helpers: JsonHelpers,\n): any {\n if (trace.length > maxDepth) {\n throw new RelationalQueryDepthError(maxDepth, trace)\n }\n\n return query.select((eb: ExpressionBuilder<any, any>) => {\n const out: unknown[] = []\n for (const [key, value] of Object.entries(withClause)) {\n const rel = relations[source]?.[key]\n if (!rel) {\n throw new RelationalQueryUnknownRelationError(source, key)\n }\n\n const subOptions: CompileOptions = value === true ? {} : value\n const innerAlias = makeAlias(rel.target, trace.length)\n const inner = buildInnerSelect(\n eb,\n sourceAlias,\n rel,\n innerAlias,\n subOptions,\n relations,\n tables,\n maxDepth,\n trace,\n helpers,\n )\n\n if (rel.kind === 'many') {\n out.push((helpers.jsonArrayFrom(inner as Expression<unknown>) as any).as(key))\n } else {\n out.push((helpers.jsonObjectFrom(inner as Expression<unknown>) as any).as(key))\n }\n }\n return out\n })\n}\n\nfunction buildInnerSelect(\n eb: ExpressionBuilder<any, any>,\n sourceAlias: string,\n rel: ResolvedRelation,\n innerAlias: string,\n subOptions: CompileOptions,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n maxDepth: number,\n trace: readonly string[],\n helpers: JsonHelpers,\n): any {\n // Explicit column list rather than `.selectAll()` — SQLite's\n // jsonArrayFrom / jsonObjectFrom helpers require it. PG's\n // helpers accept either form, so emitting columns explicitly\n // keeps a single dialect-agnostic code path here.\n const targetTable = tables[rel.target]\n const columns = targetTable\n ? Object.keys(targetTable.columns).map((c) => `${innerAlias}.${c}`)\n : null\n\n let sub: any = eb.selectFrom(`${rel.target} as ${innerAlias}` as any) as any\n if (columns && columns.length > 0) {\n sub = sub.select(columns)\n } else {\n // Fallback only when the table isn't in the snapshot (e.g.\n // tests passing a hand-rolled relations map without a\n // matching tables entry). PG accepts selectAll(); SQLite\n // would throw with a clear Kysely error.\n sub = sub.selectAll()\n }\n\n for (let i = 0; i < rel.sourceColumns.length; i++) {\n sub = sub.whereRef(\n `${innerAlias}.${rel.targetColumns[i]}`,\n '=',\n `${sourceAlias}.${rel.sourceColumns[i]}`,\n )\n }\n\n const nextTrace = [...trace, innerAlias]\n\n if (subOptions.with) {\n sub = applyWithSelects(\n sub,\n rel.target,\n innerAlias,\n subOptions.with,\n relations,\n tables,\n maxDepth,\n nextTrace,\n helpers,\n )\n }\n\n sub = applyWhereOrderLimit(sub, innerAlias, subOptions, 'many')\n\n if (rel.kind === 'one') {\n sub = sub.limit(1)\n }\n\n return sub\n}\n\nfunction applyWhereOrderLimit(\n query: any,\n alias: string,\n options: CompileOptions,\n mode: CompileMode,\n): any {\n let q = query\n\n if (options.where) {\n q = q.where((eb: ExpressionBuilder<any, any>) =>\n options.where!(makeTableRefProxy(eb, alias), eb),\n )\n }\n\n if (options.orderBy) {\n q = q.orderBy((eb: ExpressionBuilder<any, any>) =>\n options.orderBy!(makeTableRefProxy(eb, alias), eb),\n )\n }\n\n if (typeof options.limit === 'number') {\n q = q.limit(options.limit)\n } else if (mode === 'first' || mode === 'unique') {\n q = q.limit(1)\n }\n\n if (typeof options.offset === 'number') {\n q = q.offset(options.offset)\n }\n\n return q\n}\n","/**\n * PostgreSQL compiler for `db.query.X.findMany({ with })`.\n *\n * Strategy locked in `docs/db/spec-relational-query.md` §4.1:\n *\n * - Each `many` relation becomes a Kysely `jsonArrayFrom(...)`\n * select expression (PG: `coalesce((select json_agg(agg) from\n * (...) as agg), '[]')`). Empty inner result aggregates to `[]`,\n * not `null`.\n * - Each `one` relation becomes `jsonObjectFrom(...)` (PG:\n * `(select to_json(obj) from (...) as obj)`). Empty inner result\n * is `null`.\n *\n * After M4.A.2, the traversal logic lives in `compile-shared.ts`\n * and is shared with the SQLite + MySQL compilers. This file is a\n * thin wrapper that hands `kysely/helpers/postgres`'s helpers to\n * the shared runner.\n */\n\nimport { type Kysely, type CompiledQuery } from 'kysely'\nimport { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/postgres'\nimport {\n runCompile,\n type CompileMode,\n type CompileOptions,\n type JsonHelpers,\n} from './compile-shared'\nimport type { ResolvedRelations } from './relations'\nimport type { TableSnapshot } from '../snapshot/types'\n\nexport type { CompileMode, CompileOptions as CompilePgOptions }\n\nconst PG_HELPERS: JsonHelpers = {\n jsonArrayFrom: jsonArrayFrom as unknown as JsonHelpers['jsonArrayFrom'],\n jsonObjectFrom: jsonObjectFrom as unknown as JsonHelpers['jsonObjectFrom'],\n}\n\nexport function compilePg<DB>(\n db: Kysely<DB>,\n table: string,\n options: CompileOptions,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n mode: CompileMode = 'many',\n): CompiledQuery {\n return runCompile(db, table, options, relations, tables, mode, PG_HELPERS)\n}\n","/**\n * SQLite compiler for `db.query.X.findMany({ with })`.\n *\n * Strategy locked in `docs/db/spec-relational-query-other-dialects.md`\n * §3.1: each `many` relation becomes a Kysely `jsonArrayFrom(...)`\n * select expression that compiles to\n * `coalesce(json_group_array(json_object(...)), '[]')`. Each `one`\n * becomes `jsonObjectFrom(...)`, compiling to a `json_object(...)`\n * call with `LIMIT 1`. The traversal logic is shared with the PG +\n * MySQL compilers via `runCompile`.\n *\n * Result-decoding: SQLite drivers return JSON columns as TEXT;\n * `createDbClient` auto-attaches `ParseJSONResultsPlugin` for the\n * SQLite dialect so the nested JSON round-trips back to JS objects\n * before the codec / row-handler chain runs.\n */\n\nimport { type Kysely, type CompiledQuery } from 'kysely'\nimport { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/sqlite'\nimport {\n runCompile,\n type CompileMode,\n type CompileOptions,\n type JsonHelpers,\n} from './compile-shared'\nimport type { ResolvedRelations } from './relations'\nimport type { TableSnapshot } from '../snapshot/types'\n\nconst SQLITE_HELPERS: JsonHelpers = {\n jsonArrayFrom: jsonArrayFrom as unknown as JsonHelpers['jsonArrayFrom'],\n jsonObjectFrom: jsonObjectFrom as unknown as JsonHelpers['jsonObjectFrom'],\n}\n\nexport function compileSqlite<DB>(\n db: Kysely<DB>,\n table: string,\n options: CompileOptions,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n mode: CompileMode = 'many',\n): CompiledQuery {\n return runCompile(db, table, options, relations, tables, mode, SQLITE_HELPERS)\n}\n","/**\n * MySQL compiler for `db.query.X.findMany({ with })`.\n *\n * Strategy locked in `docs/db/spec-relational-query-other-dialects.md`\n * §3.2: each `many` relation becomes a Kysely `jsonArrayFrom(...)`\n * select expression that compiles to\n * `cast(coalesce(json_arrayagg(json_object(...)), '[]') as json)`.\n * Each `one` becomes `jsonObjectFrom(...)`, compiling to a\n * `JSON_OBJECT(...)` call with `LIMIT 1`. The traversal logic is\n * shared with the PG + SQLite compilers via `runCompile`.\n *\n * Result-decoding: MySQL drivers return JSON columns as TEXT (or\n * Buffers for older mysql2 configs); `createDbClient` auto-attaches\n * `ParseJSONResultsPlugin` for the MySQL dialect so the nested JSON\n * round-trips back to JS objects before the codec / row-handler\n * chain runs.\n *\n * MySQL minimum version: **8.0+**. `JSON_ARRAYAGG` shipped in 8.0;\n * earlier versions don't have it. The version check fires at the\n * adapter layer (`mysqlAdapter()` — M4.A.5) on first connection so\n * adopters get a clear error before any query reaches this\n * compiler. Spec R-1.\n */\n\nimport { type Kysely, type CompiledQuery } from 'kysely'\nimport { jsonArrayFrom, jsonObjectFrom } from 'kysely/helpers/mysql'\nimport {\n runCompile,\n type CompileMode,\n type CompileOptions,\n type JsonHelpers,\n} from './compile-shared'\nimport type { ResolvedRelations } from './relations'\nimport type { TableSnapshot } from '../snapshot/types'\n\nconst MYSQL_HELPERS: JsonHelpers = {\n jsonArrayFrom: jsonArrayFrom as unknown as JsonHelpers['jsonArrayFrom'],\n jsonObjectFrom: jsonObjectFrom as unknown as JsonHelpers['jsonObjectFrom'],\n}\n\nexport function compileMysql<DB>(\n db: Kysely<DB>,\n table: string,\n options: CompileOptions,\n relations: ResolvedRelations,\n tables: Record<string, TableSnapshot>,\n mode: CompileMode = 'many',\n): CompiledQuery {\n return runCompile(db, table, options, relations, tables, mode, MYSQL_HELPERS)\n}\n","/**\n * Dispatch helper that selects the right relational-query compiler\n * for the runtime dialect detected by `createDbClient`. After M4.A.3\n * all three dialects ship real compilers — the throw-stub is\n * retired.\n *\n * - PG → `compilePg` (kysely/helpers/postgres)\n * - SQLite → `compileSqlite` (kysely/helpers/sqlite)\n * - MySQL → `compileMysql` (kysely/helpers/mysql)\n *\n * Spec: docs/db/spec-relational-query.md §4.3 +\n * docs/db/spec-relational-query-other-dialects.md §4.\n */\n\nimport { compilePg } from './compile-pg'\nimport { compileSqlite } from './compile-sqlite'\nimport { compileMysql } from './compile-mysql'\nimport type { CompileFn } from './builder'\n\n/**\n * Pick a compiler by dialect tag. Used by `createDbClient` after it\n * detects the dialect from the Kysely instance's class name.\n */\nexport function pickCompiler(dialect: 'postgres' | 'sqlite' | 'mysql'): CompileFn {\n switch (dialect) {\n case 'postgres':\n return compilePg as CompileFn\n case 'sqlite':\n return compileSqlite as CompileFn\n case 'mysql':\n return compileMysql as CompileFn\n }\n}\n","import {\n Kysely,\n ParseJSONResultsPlugin,\n type Dialect as KyselyDialect,\n type KyselyPlugin,\n} from 'kysely'\n\nimport type { CreateDbClientOptions, KickDbClient } from './types'\nimport type { SchemaToTypes } from './schema-types'\nimport { KickDbEventEmitter } from './events'\nimport { CodecPlugin, buildDecoderMap, buildEncoderMap } from './codec-plugin'\nimport { wrap, type InternalContext } from './wrap'\nimport { extractRelations } from '../query/extract-relations'\nimport { pickCompiler } from '../query/compilers'\nimport { extractSnapshot } from '../snapshot/extract'\n\n// DB defaults to SchemaToTypes<TSchema> so the returned client is typed\n// directly from the schema parameter — no KickDbRegister lookup at the call\n// site. This breaks the `dbClient → RegisteredDB → KickDbRegister['db'] →\n// typeof dbClient` cycle that would otherwise resolve to `unknown`.\n// KickDbRegister is only consulted when consumers reference `KickDbClient`\n// with no explicit generic.\nexport function createDbClient<TSchema, DB = SchemaToTypes<TSchema>>(\n opts: CreateDbClientOptions<TSchema, DB>,\n): KickDbClient<DB> {\n // `slowQueryThresholdMs` and `bus` both imply events — listeners can't\n // subscribe to slowQuery / queryError, and the bus republisher can't\n // observe them, without the emitter being live.\n const eventsEnabled = opts.events || opts.slowQueryThresholdMs != null || opts.bus != null\n const events = eventsEnabled ? new KickDbEventEmitter() : null\n const slowThreshold = opts.slowQueryThresholdMs ?? null\n const bus = opts.bus ?? null\n\n // Republish to the DevTools event bus when wired. Mirror the local\n // event names under a `db:` namespace so adopter tabs / cross-cutting\n // log consumers know they came from kickjs-db.\n if (events && bus) {\n events.on('slowQuery', (payload) => {\n bus.emit('db:slow-query', payload)\n })\n events.on('queryError', (payload) => {\n bus.emit('db:query-error', payload)\n })\n }\n\n // Kysely's `log` config fires on every query — both success\n // (level 'query') and failure (level 'error') — with the compiled\n // SQL, params, and timing. Cleanest hook for the lifecycle events;\n // a full KyselyPlugin (transformQuery / transformResult) is heavier\n // and only worth it when we need to mutate the SQL tree.\n // Build customType codec maps once. Both transforms short-circuit\n // when their map is empty so the plugin is free of per-row /\n // per-query cost when no customType is in play. Plugin only\n // attached when at least one side has work to do.\n const decoders = buildDecoderMap(opts.schema)\n const encoders = buildEncoderMap(opts.schema)\n const codecPlugin =\n decoders.size > 0 || encoders.size > 0 ? new CodecPlugin(encoders, decoders) : null\n\n // Detect dialect early — needed both to pick the relational query\n // compiler (below) and to decide whether the JSON-results plugin\n // ships in the Kysely plugin chain.\n //\n // SQLite + MySQL drivers return JSON columns as TEXT, so the\n // kysely/helpers/<dialect> jsonArrayFrom / jsonObjectFrom won't\n // round-trip without ParseJSONResultsPlugin. PG decodes JSON\n // natively — skip the plugin there to keep the chain minimal.\n // Spec: docs/db/spec-relational-query-other-dialects.md §5.\n const dialectTag = detectDialect(opts.dialect)\n\n const plugins: KyselyPlugin[] = []\n if (codecPlugin) plugins.push(codecPlugin)\n if (dialectTag === 'sqlite' || dialectTag === 'mysql') {\n plugins.push(new ParseJSONResultsPlugin())\n }\n\n const kysely = new Kysely<DB>({\n dialect: opts.dialect,\n plugins: plugins.length > 0 ? plugins : undefined,\n log: events\n ? (event) => {\n if (event.level === 'query') {\n const durationMs = event.queryDurationMillis\n const payload = {\n sql: event.query.sql,\n parameters: event.query.parameters,\n durationMs,\n }\n events.emit('query', payload)\n if (slowThreshold != null && durationMs >= slowThreshold) {\n events.emit('slowQuery', { ...payload, thresholdMs: slowThreshold })\n }\n } else if (event.level === 'error') {\n events.emit('queryError', {\n sql: event.query.sql,\n parameters: event.query.parameters,\n error: event.error,\n })\n }\n }\n : undefined,\n })\n\n // Resolve `relations()` declarations into the JSON-serializable\n // sidecar consumed by the query compiler. Schemas without any\n // `relations()` get an empty record — the compiler still works\n // (errors clearly on `with` keys when nothing is declared).\n const tables = extractSnapshot(opts.schema as Record<string, unknown>, dialectTag).tables\n const relations = extractRelations(opts.schema as Record<string, unknown>, tables) ?? {}\n\n const ctx: InternalContext = {\n events,\n dialect: dialectTag,\n savepointCounter: { value: 0 },\n query: {\n relations,\n tables,\n compile: pickCompiler(dialectTag),\n },\n }\n return wrap<DB>(kysely, ctx)\n}\n\nfunction detectDialect(dialect: KyselyDialect): KickDbClient['dialect'] {\n // Kysely's dialects have ctor names like PostgresDialect /\n // SqliteDialect / MysqlDialect. Adopters who hand-roll the\n // KyselyDialect interface (`{ createAdapter, ... }` literals)\n // bypass that ctor — fall back to inspecting the adapter class\n // returned by `createAdapter()`, which is the real kysely\n // PostgresAdapter / SqliteAdapter / MysqlAdapter.\n const dialectCtor = (dialect.constructor as { name?: string })?.name ?? ''\n const adapterCtor = (dialect.createAdapter().constructor as { name?: string })?.name ?? ''\n const tag = `${dialectCtor} ${adapterCtor}`\n if (/Postgres/i.test(tag)) return 'postgres'\n if (/Mysql/i.test(tag)) return 'mysql'\n return 'sqlite'\n}\n","import path from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport type { Dialect } from '../snapshot/types'\nimport type { MigrationAdapter } from '../migrate/adapter'\n\nexport type MigrationAdapterFactory = () => MigrationAdapter | Promise<MigrationAdapter>\n\nexport interface DbConfig {\n schemaPath: string\n migrationsDir: string\n dialect: Dialect\n /**\n * Postgres connection string for the built-in pgAdapter path. Read from\n * `db.connectionString` in kick.config.ts, or falls back to the\n * DATABASE_URL env var. The CLI uses this when no `adapter` factory is\n * provided.\n */\n connectionString?: string\n /**\n * Escape hatch: a factory returning a fully-constructed MigrationAdapter.\n * Takes precedence over `connectionString` when both are set. Use this\n * for non-default adapter wiring (custom pool, neon-serverless, etc).\n */\n adapter?: MigrationAdapterFactory\n}\n\nexport async function resolveDbConfig(opts: { configPath: string }): Promise<DbConfig> {\n const abs = path.resolve(opts.configPath)\n const mod = await import(pathToFileURL(abs).href)\n const cfg = mod.default ?? mod\n const db = cfg?.db ?? {}\n return {\n schemaPath: db.schemaPath ?? 'src/db/schema.ts',\n migrationsDir: db.migrationsDir ?? 'db/migrations',\n dialect: db.dialect ?? 'postgres',\n connectionString: db.connectionString ?? process.env.DATABASE_URL,\n adapter: db.adapter,\n }\n}\n","import path from 'node:path'\nimport { mkdir, readFile, writeFile, readdir } from 'node:fs/promises'\nimport { pathToFileURL } from 'node:url'\nimport { existsSync } from 'node:fs'\n\nimport { extractSnapshot } from '../snapshot/extract'\nimport { diff } from '../diff/engine'\nimport { invertChanges, hasAmbiguousReverse } from '../diff/invert'\nimport { emitPg } from '../emit/pg'\nimport { appendJournalEntry, computeMigrationHash } from '../migrate/journal'\nimport type { DbConfig } from './config'\nimport type { SchemaSnapshot } from '../snapshot/types'\n\nexport interface GenerateOptions {\n name: string\n config: DbConfig\n cwd: string\n now?: () => Date\n /**\n * When true, skip the schema diff and emit an empty migration shell\n * (up.sql / down.sql with just the REVIEWED header, snapshot.json copying\n * the prior schema state). Used for data migrations, seed inserts, or any\n * change the diff engine can't author. Matches knex's `migrate:make`.\n */\n empty?: boolean\n}\n\nexport interface GenerateResult {\n status: 'created' | 'no-changes'\n migrationDir?: string\n changeCount: number\n empty?: boolean\n}\n\nexport async function generate(opts: GenerateOptions): Promise<GenerateResult> {\n const migrationsAbs = path.resolve(opts.cwd, opts.config.migrationsDir)\n const { snapshot: prev, id: previousId } = await readLatestSnapshotEntry(migrationsAbs)\n\n if (opts.empty) {\n return await writeMigration({\n opts,\n migrationsAbs,\n previousId,\n // Empty migrations don't change schema state — keep the prior snapshot\n // so the next diff-based generate stays consistent.\n target: prev,\n upBody: '',\n downBody: '',\n changeCount: 0,\n draft: false,\n empty: true,\n })\n }\n\n const schemaAbs = path.resolve(opts.cwd, opts.config.schemaPath)\n const schemaModule = await import(pathToFileURL(schemaAbs).href)\n const target = extractSnapshot(schemaModule, opts.config.dialect)\n const changes = diff(prev, target)\n\n if (changes.length === 0) {\n return { status: 'no-changes', changeCount: 0 }\n }\n\n return await writeMigration({\n opts,\n migrationsAbs,\n previousId,\n target,\n upBody: emitPg(changes),\n downBody: emitPg(invertChanges(changes)),\n changeCount: changes.length,\n draft: hasAmbiguousReverse(changes),\n empty: false,\n })\n}\n\ninterface WriteMigrationParams {\n opts: GenerateOptions\n migrationsAbs: string\n previousId: string | null\n target: SchemaSnapshot\n upBody: string\n downBody: string\n changeCount: number\n draft: boolean\n empty: boolean\n}\n\nasync function writeMigration(p: WriteMigrationParams): Promise<GenerateResult> {\n const id = formatId(p.opts.now?.() ?? new Date(), p.opts.name)\n const dir = path.join(p.migrationsAbs, id)\n await mkdir(dir, { recursive: true })\n\n const upHeader = '-- REVIEWED: false\\n'\n const upHint = p.empty\n ? '-- Empty migration — author SQL below (data migration, seed, etc).\\n'\n : ''\n const upSql = upHeader + upHint + p.upBody + (p.upBody ? '\\n' : '')\n await writeFile(path.join(dir, 'up.sql'), upSql, 'utf8')\n\n const downHeader = '-- REVIEWED: false\\n'\n const downDraft = p.draft\n ? '-- DRAFT: ambiguous reverses present (drop column / drop table / type change). Audit before applying.\\n'\n : ''\n const downHint = p.empty ? '-- Empty migration — author the reverse SQL here.\\n' : ''\n const downSql = downHeader + downDraft + downHint + p.downBody + (p.downBody ? '\\n' : '')\n await writeFile(path.join(dir, 'down.sql'), downSql, 'utf8')\n\n await writeFile(path.join(dir, 'snapshot.json'), JSON.stringify(p.target, null, 2) + '\\n', 'utf8')\n\n await writeFile(\n path.join(dir, 'meta.json'),\n JSON.stringify(\n {\n id,\n name: p.opts.name,\n createdAt: (p.opts.now?.() ?? new Date()).toISOString(),\n reviewed: false,\n dialect: p.opts.config.dialect,\n previousId: p.previousId,\n downIsDraft: p.draft,\n empty: p.empty,\n },\n null,\n 2,\n ) + '\\n',\n 'utf8',\n )\n\n // Append to _journal.json so the runner has the canonical applied-order\n // and integrity hash. Hash includes up + down + snapshot, so any later\n // hand-edit of those files will surface as a MigrationHashError at apply.\n const hash = await computeMigrationHash(dir)\n await appendJournalEntry(p.migrationsAbs, p.opts.config.dialect, {\n id,\n tag: p.opts.name,\n hash,\n createdAt: (p.opts.now?.() ?? new Date()).toISOString(),\n })\n\n return { status: 'created', migrationDir: dir, changeCount: p.changeCount, empty: p.empty }\n}\n\ninterface LatestEntry {\n snapshot: SchemaSnapshot\n id: string | null\n}\n\nasync function readLatestSnapshotEntry(migrationsDir: string): Promise<LatestEntry> {\n const empty: SchemaSnapshot = { version: 1, dialect: 'postgres', tables: {} }\n if (!existsSync(migrationsDir)) {\n return { snapshot: empty, id: null }\n }\n const entries = await readdir(migrationsDir)\n const dirs = entries.filter((e) => /^\\d{8}_\\d{6}_/.test(e)).toSorted()\n if (dirs.length === 0) {\n return { snapshot: empty, id: null }\n }\n const latest = dirs[dirs.length - 1]\n const file = path.join(migrationsDir, latest, 'snapshot.json')\n const snapshot = JSON.parse(await readFile(file, 'utf8')) as SchemaSnapshot\n return { snapshot, id: latest }\n}\n\nfunction formatId(date: Date, name: string): string {\n const pad = (n: number) => n.toString().padStart(2, '0')\n const ts =\n date.getUTCFullYear().toString() +\n pad(date.getUTCMonth() + 1) +\n pad(date.getUTCDate()) +\n '_' +\n pad(date.getUTCHours()) +\n pad(date.getUTCMinutes()) +\n pad(date.getUTCSeconds())\n const slug = name.replace(/[^a-z0-9]+/gi, '_').toLowerCase()\n return `${ts}_${slug}`\n}\n","import { ColumnBuilder, type GeneratedBrand, type NotNullBrand } from './types'\n\n// ── helpers ───────────────────────────────────────────────────────────────\n\n/**\n * Type-level brand stamps. Runtime is identity; the cast attaches the\n * relevant brand so `SchemaToTypes<S>` reads them per column.\n */\nfunction brandGenerated<C>(col: C): C & GeneratedBrand {\n return col as C & GeneratedBrand\n}\n\nfunction brandNotNull<C>(col: C): C & NotNullBrand {\n return col as C & NotNullBrand\n}\n\nfunction formatNumeric(base: string, precision?: number, scale?: number): string {\n if (precision === undefined) return base\n if (scale === undefined) return `${base}(${precision})`\n return `${base}(${precision}, ${scale})`\n}\n\n// ── auto-assigned identity columns (DB picks the value) ───────────────────\n//\n// Auto-identity columns are always NOT NULL by SQL semantics, so we stamp\n// both NotNullBrand (drop the `| null`) and GeneratedBrand (wrap in\n// Generated<T>) at the constructor.\n\nexport function serial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<number>('serial', { nullable: false })))\n}\n\nexport function bigSerial(): ColumnBuilder<bigint> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<bigint>('bigserial', { nullable: false })))\n}\n\nexport function smallSerial(): ColumnBuilder<number> & GeneratedBrand & NotNullBrand {\n return brandNotNull(brandGenerated(new ColumnBuilder<number>('smallserial', { nullable: false })))\n}\n\n// ── numeric ───────────────────────────────────────────────────────────────\n\nexport function integer(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('integer')\n}\n\nexport function bigint(): ColumnBuilder<bigint> {\n return new ColumnBuilder<bigint>('bigint')\n}\n\nexport function smallint(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('smallint')\n}\n\nexport function decimal(precision?: number, scale?: number): ColumnBuilder<string> {\n return new ColumnBuilder<string>(formatNumeric('decimal', precision, scale))\n}\n\nexport function numeric(precision?: number, scale?: number): ColumnBuilder<string> {\n return new ColumnBuilder<string>(formatNumeric('numeric', precision, scale))\n}\n\nexport function real(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('real')\n}\n\nexport function doublePrecision(): ColumnBuilder<number> {\n return new ColumnBuilder<number>('double precision')\n}\n\n// ── string-shaped ─────────────────────────────────────────────────────────\n\nexport function varchar(length = 255): ColumnBuilder<string> {\n return new ColumnBuilder<string>(`varchar(${length})`)\n}\n\nexport function char(length = 1): ColumnBuilder<string> {\n return new ColumnBuilder<string>(`char(${length})`)\n}\n\nexport function text(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('text')\n}\n\n// ── boolean ───────────────────────────────────────────────────────────────\n\nexport function boolean(): ColumnBuilder<boolean> {\n return new ColumnBuilder<boolean>('boolean')\n}\n\n// ── date / time ───────────────────────────────────────────────────────────\n\n/**\n * Subtype builder so `defaultNow()` can mark the resulting column as\n * generated — when the DB will fill in `CURRENT_TIMESTAMP` if the adopter\n * omits the column on insert. Returns `this & GeneratedBrand` so the\n * subclass identity is preserved through the chain.\n */\nexport class TimestampBuilder extends ColumnBuilder<Date> {\n constructor(typeName: string = 'timestamp') {\n super(typeName)\n }\n\n defaultNow(): this & GeneratedBrand {\n this.state.default = 'CURRENT_TIMESTAMP'\n return brandGenerated(this)\n }\n}\n\nexport function timestamp(): TimestampBuilder {\n return new TimestampBuilder('timestamp')\n}\n\nexport function timestamptz(): TimestampBuilder {\n return new TimestampBuilder('timestamptz')\n}\n\nexport function date(): ColumnBuilder<Date> {\n return new ColumnBuilder<Date>('date')\n}\n\nexport function time(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('time')\n}\n\nexport function interval(): ColumnBuilder<string> {\n return new ColumnBuilder<string>('interval')\n}\n\n// ── identity-shaped (uuid) ────────────────────────────────────────────────\n\n/**\n * Subtype builder so `defaultRandom()` can mark the resulting column as\n * generated — when the DB fills in `gen_random_uuid()` for omitted columns.\n * Returns `this & GeneratedBrand` so chaining works in either order:\n * uuid().defaultRandom().primaryKey()\n * uuid().primaryKey().defaultRandom() ← also works\n */\nexport class UuidBuilder extends ColumnBuilder<string> {\n constructor() {\n super('uuid')\n }\n\n defaultRandom(): this & GeneratedBrand {\n this.state.default = 'gen_random_uuid()'\n return brandGenerated(this)\n }\n}\n\nexport function uuid(): UuidBuilder {\n return new UuidBuilder()\n}\n\n// ── structured / binary ───────────────────────────────────────────────────\n\n/**\n * The `T` generic exists so adopters can declare their JSON shape:\n *\n * meta: jsonb<{ tags: string[] }>()\n *\n * `SchemaToTypes<S>` then sees `ColumnBuilder<{ tags: string[] }>` and the\n * row type narrows to `{ tags: string[] } | null`.\n */\nexport function json<T = unknown>(): ColumnBuilder<T> {\n return new ColumnBuilder<T>('json')\n}\n\nexport function jsonb<T = unknown>(): ColumnBuilder<T> {\n return new ColumnBuilder<T>('jsonb')\n}\n\nexport function bytea(): ColumnBuilder<Uint8Array> {\n return new ColumnBuilder<Uint8Array>('bytea')\n}\n","import type { ColumnBuilder, ColumnRef } from './columns/types'\nimport type { IndexDecl } from './constraints'\n\nexport type { ColumnRef }\n\nexport interface TableDecl<\n TName extends string = string,\n C extends Record<string, ColumnBuilder> = Record<string, ColumnBuilder>,\n> {\n __isTable: true\n __name: TName\n __columns: C\n __indexes: IndexDecl[]\n}\n\ntype TableRefs<TName extends string, C extends Record<string, ColumnBuilder>> = TableDecl<\n TName,\n C\n> & {\n [K in keyof C]: ColumnRef\n}\n\ntype ConstraintBuilder<C extends Record<string, ColumnBuilder>> = (refs: {\n [K in keyof C]: ColumnRef\n}) => Record<string, IndexDecl>\n\n/**\n * Declare a typed table. The `TName extends string` generic narrows to the\n * literal table name so `SchemaToTypes<S>` can index by it without losing\n * the constant — `table('users', …)` widens to `TableDecl<'users', …>`,\n * not `TableDecl<string, …>`.\n */\nexport function table<TName extends string, C extends Record<string, ColumnBuilder>>(\n name: TName,\n columns: C,\n constraints?: ConstraintBuilder<C>,\n): TableRefs<TName, C> {\n const decl: TableDecl<TName, C> = {\n __isTable: true,\n __name: name,\n __columns: columns,\n __indexes: [],\n }\n\n const refs = {} as { [K in keyof C]: ColumnRef }\n for (const [key, builder] of Object.entries(columns) as [keyof C, ColumnBuilder][]) {\n refs[key] = {\n __tableName: name,\n __name: key as string,\n __builder: builder,\n __state: () => builder.__state(),\n }\n }\n\n if (constraints) {\n const declared = constraints(refs)\n decl.__indexes = Object.values(declared)\n }\n\n return Object.assign(decl, refs)\n}\n","export interface IndexDecl {\n name: string\n columns: string[]\n unique: boolean\n}\n\ninterface ColRef {\n __name: string\n}\n\nexport function index(name: string) {\n return {\n on(...cols: ColRef[]): IndexDecl {\n return { name, columns: cols.map((c) => c.__name), unique: false }\n },\n }\n}\n\nexport function unique(name: string) {\n return {\n on(...cols: ColRef[]): IndexDecl {\n return { name, columns: cols.map((c) => c.__name), unique: true }\n },\n }\n}\n","import type { ColumnBuilder } from './columns/types'\nimport type { ColumnRef, TableDecl } from './table'\n\n/**\n * Generic over the target table so the typegen plugin can pull\n * `target['__name']` without losing the literal string at the type\n * level. Existing callers that only read `kind` / `fields` /\n * `references` see the same surface.\n */\nexport interface RelationOne<\n TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<\n string,\n Record<string, ColumnBuilder>\n >,\n> {\n kind: 'one'\n target: TTarget\n fields: ColumnRef[]\n references: ColumnRef[]\n /**\n * Disambiguates this relation from sibling `one` relations on the\n * same source table that point at the same target. Pair with the\n * matching `relationName` on the inverse `many` side. See\n * docs/db/spec-relation-name.md.\n */\n relationName?: string\n}\n\nexport interface RelationMany<\n TTarget extends TableDecl<string, Record<string, ColumnBuilder>> = TableDecl<\n string,\n Record<string, ColumnBuilder>\n >,\n> {\n kind: 'many'\n target: TTarget\n /**\n * Pairs with the matching `relationName` on the inverse `one`\n * declaration. Required when the source table has multiple FKs\n * to the same target; resolver throws\n * `RelationalQueryMissingInverseError` otherwise.\n */\n relationName?: string\n}\n\nexport type Relation = RelationOne | RelationMany\n\n/**\n * Generic so the typegen plugin can read the source table name and\n * the per-relation kind/target via `RelationsDecl['__sourceTable']`\n * and `RelationsDecl['__relations']`. The runtime shape is\n * unchanged; the generic parameters narrow the type at call sites.\n */\nexport interface RelationsDecl<\n TSource extends string = string,\n TRelations extends Record<string, Relation> = Record<string, Relation>,\n> {\n __isRelations: true\n __sourceTable: TSource\n __relations: TRelations\n}\n\ninterface Helpers {\n one: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(\n target: T,\n opts: { fields: ColumnRef[]; references: ColumnRef[]; relationName?: string },\n ) => RelationOne<T>\n many: <T extends TableDecl<string, Record<string, ColumnBuilder>>>(\n target: T,\n opts?: { relationName?: string },\n ) => RelationMany<T>\n}\n\n/**\n * Declare a typed relation set for `source`. The return type\n * preserves `source.__name` and the literal `kind`/`target` of every\n * helper-built entry so `SchemaToRelationsRegister<S>` (re-exported\n * from `@forinda/kickjs-db`) can walk the schema barrel and emit a\n * matching `KickDbRelationsRegister` augmentation at typegen time.\n */\nexport function relations<\n T extends TableDecl<string, Record<string, ColumnBuilder>>,\n R extends Record<string, Relation>,\n>(source: T, builder: (h: Helpers) => R): RelationsDecl<T['__name'], R> {\n const helpers: Helpers = {\n one: (target, opts) => ({\n kind: 'one',\n target,\n fields: opts.fields,\n references: opts.references,\n ...(opts.relationName !== undefined ? { relationName: opts.relationName } : {}),\n }),\n many: (target, opts) => ({\n kind: 'many',\n target,\n ...(opts?.relationName !== undefined ? { relationName: opts.relationName } : {}),\n }),\n }\n return {\n __isRelations: true,\n __sourceTable: source.__name,\n __relations: builder(helpers),\n } as RelationsDecl<T['__name'], R>\n}\n"],"mappings":";;;;;;;;;;23BAAA,IAAa,YAAb,cAAiC,KAAM,CACrC,KAEA,YAAY,KAAc,QAAiB,CACzC,MAAM,QAAQ,CACd,KAAK,KAAO,KAAK,YAAY,KAC7B,KAAK,KAAO,OCSH,oCAAb,cAAyD,WAAY,CACnE,YACA,YACA,YAAY,YAAqB,YAAqB,CACpD,MACE,sCACA,sBAAsB,YAAY,GAAG,YAAY,8EACJ,YAAY,wBAC1D,CACD,KAAK,YAAc,YACnB,KAAK,YAAc,cASV,0BAAb,cAA+C,WAAY,CACzD,SACA,MACA,YAAY,SAAkB,MAA0B,CACtD,MACE,oCACA,qCAAqC,SAAS,UAAU,MAAM,KAAK,MAAM,CAAC,sEAE3E,CACD,KAAK,SAAW,SAChB,KAAK,MAAQ,QAUJ,mCAAb,cAAwD,WAAY,CAClE,YACA,gBACA,YAAY,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