@forinda/kickjs-db 6.0.0 → 6.1.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.
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Standalone `kickjs-db` CLI — run the database command tree without
4
+ * installing `@forinda/kickjs-cli`.
5
+ *
6
+ * npx kickjs-db migrate latest
7
+ * npx kickjs-db generate add_users
8
+ *
9
+ * Config resolution (later wins, vite-style merge):
10
+ * 1. `kick.config.{ts,js,mjs,json}` → its `db` block, if present.
11
+ * 2. `kickjs-db.config.{ts,js,mjs,json}` → its default export.
12
+ *
13
+ * `.ts` / `.mjs` configs load through jiti; `.json` is read directly.
14
+ */
15
+ import path from 'node:path'
16
+ import { existsSync } from 'node:fs'
17
+ import { pathToFileURL } from 'node:url'
18
+ import { Command } from 'commander'
19
+
20
+ import { registerDbCommands, resolveKickDbConfig, mergeKickDbConfig } from '../dist/cli.mjs'
21
+
22
+ const CONFIG_EXTS = ['ts', 'mts', 'js', 'mjs', 'json']
23
+
24
+ function findConfig(baseName, cwd) {
25
+ for (const ext of CONFIG_EXTS) {
26
+ const p = path.join(cwd, `${baseName}.${ext}`)
27
+ if (existsSync(p)) return p
28
+ }
29
+ return null
30
+ }
31
+
32
+ async function importConfig(file) {
33
+ if (file.endsWith('.json')) {
34
+ const { readFile } = await import('node:fs/promises')
35
+ return JSON.parse(await readFile(file, 'utf8'))
36
+ }
37
+ if (file.endsWith('.ts') || file.endsWith('.mts')) {
38
+ // jiti handles extensionless relative TS imports a config may use.
39
+ const { createJiti } = await import('jiti').catch(() => {
40
+ throw new Error(
41
+ `kickjs-db: reading a TypeScript config (${path.basename(file)}) needs jiti. ` +
42
+ `Install it (\`npm i -D jiti\`) or use a .js/.mjs/.json config.`,
43
+ )
44
+ })
45
+ const jiti = createJiti(import.meta.url)
46
+ return await jiti.import(file, { default: true })
47
+ }
48
+ const mod = await import(pathToFileURL(file).href)
49
+ return mod.default ?? mod
50
+ }
51
+
52
+ async function resolveConfig() {
53
+ const cwd = process.cwd()
54
+
55
+ const kickConfigFile = findConfig('kick.config', cwd)
56
+ const dbConfigFile = findConfig('kickjs-db.config', cwd)
57
+
58
+ let kickDbBlock
59
+ if (kickConfigFile) {
60
+ const cfg = await importConfig(kickConfigFile)
61
+ kickDbBlock = cfg?.db
62
+ }
63
+ let standaloneBlock
64
+ if (dbConfigFile) {
65
+ standaloneBlock = await importConfig(dbConfigFile)
66
+ }
67
+
68
+ if (!kickDbBlock && !standaloneBlock) {
69
+ throw new Error(
70
+ 'kickjs-db: no config found — add a `kickjs-db.config.ts` (export default ' +
71
+ 'defineKickDbConfig({...})) or a `db` block to `kick.config.ts`.',
72
+ )
73
+ }
74
+ // Standalone config layers over the kick.config db block.
75
+ return resolveKickDbConfig(mergeKickDbConfig(kickDbBlock, standaloneBlock))
76
+ }
77
+
78
+ const program = new Command()
79
+ program.name('kickjs-db').description('KickJS database CLI (standalone)')
80
+
81
+ registerDbCommands(program, resolveConfig)
82
+
83
+ program.showHelpAfterError()
84
+ program.parseAsync(process.argv).catch((err) => {
85
+ console.error(err instanceof Error ? err.message : err)
86
+ process.exitCode = 1
87
+ })
package/dist/cli.d.mts ADDED
@@ -0,0 +1,71 @@
1
+
2
+ import { Ft as DriftBehavior, J as DbConfig, Kn as Dialect, Y as MigrationAdapterFactory } from "./index-B1r7mcA1.mjs";
3
+ import { CliTypegen, KickCliPlugin } from "@forinda/kickjs-cli-kit";
4
+ import { Command } from "commander";
5
+
6
+ //#region src/cli-typegen.d.ts
7
+ declare const kickDbTypegen: () => CliTypegen;
8
+ //#endregion
9
+ //#region src/cli.d.ts
10
+ /**
11
+ * Authoring shape for the db config — every field optional, defaults
12
+ * applied by {@link resolveKickDbConfig}. This is the same shape as the
13
+ * `db` block in `kick.config.ts`, so a config authored with
14
+ * `defineKickDbConfig` drops straight into either place.
15
+ */
16
+ interface KickDbConfigInput {
17
+ schemaPath?: string;
18
+ migrationsDir?: string;
19
+ dialect?: Dialect;
20
+ connectionString?: string;
21
+ adapter?: MigrationAdapterFactory;
22
+ /**
23
+ * How `migrate` reacts to out-of-band schema (drift): `'error'`
24
+ * (default), `'warn'`, or `'ignore'`. The check is dialect-normalised,
25
+ * so SQLite/MySQL's lossy introspection doesn't false-positive.
26
+ */
27
+ driftCheck?: DriftBehavior;
28
+ }
29
+ /**
30
+ * Identity helper for type inference — mirrors vite's `defineConfig`.
31
+ * Use it in a standalone `kickjs-db.config.ts` (`export default
32
+ * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s
33
+ * `db` field. Both resolve through {@link resolveKickDbConfig}.
34
+ */
35
+ declare function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput;
36
+ /**
37
+ * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).
38
+ * Lets a standalone `kickjs-db.config.ts` layer over a project's
39
+ * `kick.config.ts` `db` block, or vice versa.
40
+ */
41
+ declare function mergeKickDbConfig(...configs: (KickDbConfigInput | undefined)[]): KickDbConfigInput;
42
+ /** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */
43
+ declare function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig;
44
+ /** A config source — resolved lazily so each command reads fresh config. */
45
+ type DbConfigResolver = () => DbConfig | Promise<DbConfig>;
46
+ /**
47
+ * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a
48
+ * commander command. `parent` is the command they hang off — the plugin
49
+ * passes a `db` subcommand (so `kick db generate`), the standalone bin
50
+ * passes the root program (so `kickjs-db generate`). `getConfig` supplies
51
+ * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,
52
+ * standalone from `kickjs-db.config.ts`.
53
+ */
54
+ declare function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void;
55
+ /**
56
+ * The database CLI plugin. Mount it in `kick.config.ts`:
57
+ *
58
+ * ```ts
59
+ * import { defineConfig } from '@forinda/kickjs-cli'
60
+ * import { dbCliPlugin } from '@forinda/kickjs-db/cli'
61
+ *
62
+ * export default defineConfig({ plugins: [dbCliPlugin] })
63
+ * ```
64
+ *
65
+ * `kick db generate|migrate|introspect` then read config from the
66
+ * `db` block of the same `kick.config.ts`.
67
+ */
68
+ declare const dbCliPlugin: KickCliPlugin;
69
+ //#endregion
70
+ export { DbConfigResolver, KickDbConfigInput, dbCliPlugin, defineKickDbConfig, kickDbTypegen, mergeKickDbConfig, registerDbCommands, resolveKickDbConfig };
71
+ //# sourceMappingURL=cli.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.mts","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"mappings":";;;;;;cA4Ba,aAAA,QAAoB,UAiC/B;;;;;;;;;UCbe,iBAAA;EACf,UAAA;EACA,aAAA;EACA,OAAA,GAAU,OAAA;EACV,gBAAA;EACA,OAAA,GAAU,uBAAA;;;;;;EAMV,UAAA,GAAa,aAAA;AAAA;AAkBf;;;;;;AAAA,iBATgB,kBAAA,CAAmB,GAAA,EAAK,iBAAA,GAAoB,iBAAiB;;AAWzD;AAKpB;;;iBAPgB,iBAAA,IACX,OAAA,GAAU,iBAAA,kBACZ,iBAAiB;;iBAKJ,mBAAA,CAAoB,KAAA,EAAO,iBAAA,eAAgC,QAAQ;;KAuFvE,gBAAA,SAAyB,QAAA,GAAW,OAAA,CAAQ,QAAA;AAvF2B;AAuFnF;;;;;;;AAvFmF,iBAiGnE,kBAAA,CAAmB,MAAA,EAAQ,OAAA,EAAS,SAAA,EAAW,gBAAgB;;;;;AAVf;AAUhE;;;;;;;;cAiNa,WAAA,EAAa,aASxB"}
package/dist/cli.mjs ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @forinda/kickjs-db v6.1.1
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import{A as generate,G as migrateLatest,J as migrateUp,K as migrateRollback,M as reviewMigration,Tt as renderSchemaSource,W as migrateDown,q as migrateStatus,xt as detectCompositeReferences}from"./src-Dpz7lQYB.mjs";import{writeFile}from"node:fs/promises";import{existsSync}from"node:fs";import path from"node:path";import{defineCliPlugin}from"@forinda/kickjs-cli-kit";const DEFAULT_SCHEMA_PATHS=[`src/db/schema.ts`,`src/db/schema/index.ts`,`src/db/schema`],kickDbTypegen=()=>({id:`kick/db`,inputs:[`src/db/schema.ts`,`src/db/schema/**/*.ts`],async generate(ctx){let schemaAbs=resolveSchema(ctx.cwd);if(!schemaAbs)return null;let typesDir=path.resolve(ctx.cwd,`.kickjs/types`);return[`import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,`import type * as appSchema from '${posix(path.relative(typesDir,schemaAbs)).replace(/\.ts$/,``).replace(/\/index$/,``)}'`,``,`declare global {`,` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,`}`,``,`declare module '@forinda/kickjs-db' {`,` interface KickDbRegister {`,` db: KickDbClient<KickDbSchema>`,` }`,``,` interface KickDbRelationsRegister {`,` db: SchemaToRelationsRegister<typeof appSchema>`,` }`,`}`].join(`
12
+ `)}});function resolveSchema(cwd){for(let candidate of DEFAULT_SCHEMA_PATHS){let abs=path.resolve(cwd,candidate);if(candidate.endsWith(`.ts`)){if(existsSync(abs))return abs}else{let idx=path.join(abs,`index.ts`);if(existsSync(idx))return idx}}return null}function posix(p){return p.replace(/\\/g,`/`)}function defineKickDbConfig(cfg){return cfg}function mergeKickDbConfig(...configs){return Object.assign({},...configs.filter(Boolean))}function resolveKickDbConfig(block){let db=block??{};return{schemaPath:db.schemaPath??`src/db/schema.ts`,migrationsDir:db.migrationsDir??`db/migrations`,dialect:db.dialect??`postgres`,connectionString:db.connectionString??process.env.DATABASE_URL,adapter:db.adapter,driftCheck:db.driftCheck}}async function resolveAdapter(config){if(config.adapter){let adapter=await config.adapter();return{adapter,cleanup:async()=>adapter.close()}}if(!config.connectionString)throw Error(`kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory`);let dialect=config.dialect??`postgres`;if(dialect!==`postgres`)throw Error(`kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`);let[{pgAdapter},pg]=await Promise.all([import(`./pg.mjs`),import(`pg`)]),pool=new pg.default.Pool({connectionString:config.connectionString}),adapter=pgAdapter({pool});return{adapter,cleanup:async()=>{await adapter.close(),await pool.end()}}}async function tryResolvePgQueryRunner(config){if(config.adapter||(config.dialect??`postgres`)!==`postgres`||!config.connectionString)return null;let pool=new(await(import(`pg`))).default.Pool({connectionString:config.connectionString});return{runner:pool,cleanup:async()=>void await pool.end()}}function printStatusTable(status){if(status.length===0){console.log(`No migrations.`);return}console.table(status.map(s=>({id:s.id,state:s.state,batch:s.batch??`-`,reviewed:s.reviewed,applied:s.appliedAt??`-`})))}function registerDbCommands(parent,getConfig){parent.command(`generate <name>`).description(`Generate a new migration from schema diff`).option(`-e, --empty`,`Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)`).action(async(name,opts)=>{let cwd=process.cwd(),config=await getConfig(),probe=await tryResolvePgQueryRunner(config),detectCompositeRefs=probe?enumName=>detectCompositeReferences(probe.runner,enumName):void 0;try{let result=await generate({name,config,cwd,empty:opts.empty,detectCompositeRefs});if(result.status===`no-changes`){console.log(`No schema changes detected.`);return}if(result.empty){console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`);return}let plural=result.changeCount===1?``:`s`;console.log(`Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`)}finally{await probe?.cleanup()}});let migrate=parent.command(`migrate`).description(`Migration runner subcommands`);migrate.command(`latest`).description(`Apply all pending migrations in a new batch`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateLatest({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied batch ${r.batch}: ${r.applied.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`up`).description(`Apply the next single pending migration`).option(`--confirm-enum-drop`,"Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply",!1).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateUp({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck,confirmEnumDrop:opts.confirmEnumDrop});console.log(r.applied.length===0?`No pending migrations.`:`Applied ${r.applied[0]} (batch ${r.batch})`)}finally{await cleanup()}}),migrate.command(`down`).description(`Reverse the most recent applied migration`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateDown({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed?`Reversed ${r.reversed}.`:`Nothing to reverse.`)}finally{await cleanup()}}),migrate.command(`rollback`).description(`Reverse the entire last batch as a single unit`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let r=await migrateRollback({adapter,migrationsDir:config.migrationsDir,driftCheck:config.driftCheck});console.log(r.reversed.length===0?`Nothing to roll back.`:`Rolled back batch ${r.batch}: ${r.reversed.join(`, `)}`)}finally{await cleanup()}}),migrate.command(`status`).description(`Print applied + pending migrations`).action(async()=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{printStatusTable(await migrateStatus({adapter,migrationsDir:config.migrationsDir}))}finally{await cleanup()}}),migrate.command(`review <id>`).description(`Mark a migration reviewed (flips meta.json + the -- REVIEWED markers)`).action(async id=>{let r=await reviewMigration((await getConfig()).migrationsDir,id);console.log(r.alreadyReviewed?`${r.id} was already reviewed.`:`Reviewed ${r.id} — it can now be applied.`)}),parent.command(`introspect`).description(`Generate a TypeScript schema file from a live database`).option(`--out <path>`,`Output file (defaults to db.schemaPath from config)`).option(`--json`,`Print the raw SchemaSnapshot JSON to stdout instead of writing TS source`).action(async opts=>{let config=await getConfig(),{adapter,cleanup}=await resolveAdapter(config);try{let snapshot=await adapter.introspect();if(opts.json){console.log(JSON.stringify(snapshot,null,2));return}let out=opts.out??config.schemaPath;await writeFile(out,renderSchemaSource(snapshot),`utf8`);let n=Object.keys(snapshot.tables).length;console.log(`Wrote ${out} (${n} table${n===1?``:`s`}).`)}finally{await cleanup()}})}function dbBlockOf(config){return config?.db}const dbCliPlugin=defineCliPlugin({name:`kick/db`,register(program,ctx){registerDbCommands(program.command(`db`).description(`Database commands (kickjs-db)`),()=>resolveKickDbConfig(dbBlockOf(ctx.config)))},typegens:[kickDbTypegen()]});export{dbCliPlugin,defineKickDbConfig,kickDbTypegen,mergeKickDbConfig,registerDbCommands,resolveKickDbConfig};
13
+ //# sourceMappingURL=cli.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.mjs","names":[],"sources":["../src/cli-typegen.ts","../src/cli.ts"],"sourcesContent":["/**\n * `kick/db` typegen — reads the adopter's schema (`src/db/schema.ts` or a\n * `src/db/schema/` barrel) and emits `.kickjs/types/kick__db.d.ts` with\n * three augmentations:\n *\n * 1. global `KickDbSchema = SchemaToTypes<typeof appSchema>` — column\n * shapes computed at type-check time, no runtime cost.\n * 2. `KickDbRegister.db = KickDbClient<KickDbSchema>` — bare\n * `KickDbClient` widens automatically.\n * 3. `KickDbRelationsRegister.db = SchemaToRelationsRegister<typeof\n * appSchema>` — typed `with` keys for `db.query.X.findMany`.\n *\n * Shipped on {@link dbCliPlugin} (`typegens`) so mounting the db plugin\n * brings both the `kick db` commands and this type generation. Typed\n * against the `@forinda/kickjs-cli-kit` `CliTypegen` contract so it needs\n * no kickjs-cli internals — it only reads `ctx.cwd`.\n */\nimport path from 'node:path'\nimport { existsSync } from 'node:fs'\n\nimport type { CliTypegen } from '@forinda/kickjs-cli-kit'\n\nconst DEFAULT_SCHEMA_PATHS = [\n 'src/db/schema.ts',\n 'src/db/schema/index.ts',\n 'src/db/schema',\n] as const\n\nexport const kickDbTypegen = (): CliTypegen => ({\n id: 'kick/db',\n inputs: ['src/db/schema.ts', 'src/db/schema/**/*.ts'],\n async generate(ctx: { cwd: string }) {\n const schemaAbs = resolveSchema(ctx.cwd)\n if (!schemaAbs) return null\n\n // Strip the `.ts` extension and any trailing `/index` so the import\n // specifier stays stable across single-file vs barrel-folder layouts.\n const typesDir = path.resolve(ctx.cwd, '.kickjs/types')\n const rel = posix(path.relative(typesDir, schemaAbs))\n .replace(/\\.ts$/, '')\n .replace(/\\/index$/, '')\n\n return [\n `import type { SchemaToTypes, SchemaToRelationsRegister, KickDbClient } from '@forinda/kickjs-db'`,\n `import type * as appSchema from '${rel}'`,\n ``,\n `declare global {`,\n ` interface KickDbSchema extends SchemaToTypes<typeof appSchema> {}`,\n `}`,\n ``,\n `declare module '@forinda/kickjs-db' {`,\n ` interface KickDbRegister {`,\n ` db: KickDbClient<KickDbSchema>`,\n ` }`,\n ``,\n ` interface KickDbRelationsRegister {`,\n ` db: SchemaToRelationsRegister<typeof appSchema>`,\n ` }`,\n `}`,\n ].join('\\n')\n },\n})\n\nfunction resolveSchema(cwd: string): string | null {\n for (const candidate of DEFAULT_SCHEMA_PATHS) {\n const abs = path.resolve(cwd, candidate)\n if (candidate.endsWith('.ts')) {\n if (existsSync(abs)) return abs\n } else {\n const idx = path.join(abs, 'index.ts')\n if (existsSync(idx)) return idx\n }\n }\n return null\n}\n\nfunction posix(p: string): string {\n return p.replace(/\\\\/g, '/')\n}\n","/**\n * `@forinda/kickjs-db/cli` — the database command tree as a mountable CLI\n * plugin + the building blocks for a standalone `kickjs-db` bin.\n *\n * Two ways to use it:\n * 1. **As a kickjs-cli plugin** — add `dbCliPlugin` to `kick.config.ts`\n * `plugins: []`. The host CLI calls `register(program, ctx)` and the\n * db config is read from `ctx.config.db` (already loaded — no re-parse).\n * 2. **Standalone** — the `kickjs-db` bin builds a commander program,\n * resolves config from `kickjs-db.config.ts` (or a `kick.config.ts`\n * `db` block), and calls {@link registerDbCommands} directly. Lets\n * `npx kickjs-db migrate latest` work without installing kickjs-cli.\n *\n * @module @forinda/kickjs-db/cli\n */\n\nimport { writeFile } from 'node:fs/promises'\nimport type { Command } from 'commander'\n\nimport { defineCliPlugin, type KickCliPlugin } from '@forinda/kickjs-cli-kit'\nimport { kickDbTypegen } from './cli-typegen'\n\nexport { kickDbTypegen } from './cli-typegen'\n\nimport {\n detectCompositeReferences,\n generate,\n migrateLatest,\n migrateUp,\n migrateDown,\n migrateRollback,\n migrateStatus,\n reviewMigration,\n renderSchemaSource,\n type CompositeQueryRunner,\n type DbConfig,\n type MigrationAdapter,\n} from './index'\nimport type { Dialect } from './snapshot/types'\nimport type { MigrationAdapterFactory } from './cli/config'\nimport type { DriftBehavior } from './migrate/drift'\n\n/**\n * Authoring shape for the db config — every field optional, defaults\n * applied by {@link resolveKickDbConfig}. This is the same shape as the\n * `db` block in `kick.config.ts`, so a config authored with\n * `defineKickDbConfig` drops straight into either place.\n */\nexport interface KickDbConfigInput {\n schemaPath?: string\n migrationsDir?: string\n dialect?: Dialect\n connectionString?: string\n adapter?: MigrationAdapterFactory\n /**\n * How `migrate` reacts to out-of-band schema (drift): `'error'`\n * (default), `'warn'`, or `'ignore'`. The check is dialect-normalised,\n * so SQLite/MySQL's lossy introspection doesn't false-positive.\n */\n driftCheck?: DriftBehavior\n}\n\n/**\n * Identity helper for type inference — mirrors vite's `defineConfig`.\n * Use it in a standalone `kickjs-db.config.ts` (`export default\n * defineKickDbConfig({ ... })`) or as the value of `kick.config.ts`'s\n * `db` field. Both resolve through {@link resolveKickDbConfig}.\n */\nexport function defineKickDbConfig(cfg: KickDbConfigInput): KickDbConfigInput {\n return cfg\n}\n\n/**\n * Shallow-merge db configs, later wins (vite's `mergeConfig` spirit).\n * Lets a standalone `kickjs-db.config.ts` layer over a project's\n * `kick.config.ts` `db` block, or vice versa.\n */\nexport function mergeKickDbConfig(\n ...configs: (KickDbConfigInput | undefined)[]\n): KickDbConfigInput {\n return Object.assign({}, ...configs.filter(Boolean))\n}\n\n/** Apply defaults to a {@link KickDbConfigInput}, yielding a resolved {@link DbConfig}. */\nexport function resolveKickDbConfig(block: KickDbConfigInput | undefined): DbConfig {\n const db = block ?? {}\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 driftCheck: db.driftCheck,\n }\n}\n\n/**\n * Resolve a MigrationAdapter from config:\n * 1. config.adapter() — explicit factory wins.\n * 2. config.connectionString — built-in pgAdapter path; dynamically\n * imports `./pg` + `pg` so non-PG workflows don't pull pg.\n */\nasync function resolveAdapter(config: DbConfig): Promise<{\n adapter: MigrationAdapter\n cleanup: () => Promise<void>\n}> {\n if (config.adapter) {\n const adapter = await config.adapter()\n return { adapter, cleanup: async () => adapter.close() }\n }\n if (!config.connectionString) {\n throw new Error(\n 'kickjs-db: no adapter resolved — set db.connectionString (or DATABASE_URL), or supply a db.adapter() factory',\n )\n }\n const dialect = config.dialect ?? 'postgres'\n if (dialect !== 'postgres') {\n throw new Error(\n `kickjs-db: the built-in CLI adapter only supports postgres (dialect=${dialect}); supply a db.adapter() factory for other dialects`,\n )\n }\n // Dynamic import so we don't hard-require pg unless this path runs.\n const [{ pgAdapter }, pg] = await Promise.all([import('./pg'), import('pg')])\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n const adapter = pgAdapter({ pool })\n return {\n adapter,\n cleanup: async () => {\n await adapter.close()\n await pool.end()\n },\n }\n}\n\ninterface PgQueryRunnerProbe {\n runner: CompositeQueryRunner\n cleanup: () => Promise<void>\n}\n\n/**\n * Resolve a pg-protocol query runner for the composite-type check at\n * `generate` time. Only fires for the built-in pgAdapter path\n * (dialect=postgres + connection string, no custom adapter factory).\n */\nasync function tryResolvePgQueryRunner(config: DbConfig): Promise<PgQueryRunnerProbe | null> {\n if (config.adapter) return null\n if ((config.dialect ?? 'postgres') !== 'postgres') return null\n if (!config.connectionString) return null\n\n const pg = await import('pg')\n const pool = new pg.default.Pool({ connectionString: config.connectionString })\n return { runner: pool, cleanup: async () => void (await pool.end()) }\n}\n\nfunction printStatusTable(status: Awaited<ReturnType<typeof migrateStatus>>): void {\n if (status.length === 0) {\n console.log('No migrations.')\n return\n }\n console.table(\n status.map((s) => ({\n id: s.id,\n state: s.state,\n batch: s.batch ?? '-',\n reviewed: s.reviewed,\n applied: s.appliedAt ?? '-',\n })),\n )\n}\n\n/** A config source — resolved lazily so each command reads fresh config. */\nexport type DbConfigResolver = () => DbConfig | Promise<DbConfig>\n\n/**\n * Attach the db commands (`generate`, `migrate *`, `introspect`) onto a\n * commander command. `parent` is the command they hang off — the plugin\n * passes a `db` subcommand (so `kick db generate`), the standalone bin\n * passes the root program (so `kickjs-db generate`). `getConfig` supplies\n * the resolved {@link DbConfig} — under kickjs-cli from `ctx.config.db`,\n * standalone from `kickjs-db.config.ts`.\n */\nexport function registerDbCommands(parent: Command, getConfig: DbConfigResolver): void {\n parent\n .command('generate <name>')\n .description('Generate a new migration from schema diff')\n .option(\n '-e, --empty',\n 'Skip schema diff and create an empty migration shell (data migration, seed, freeform SQL)',\n )\n .action(async (name: string, opts: { empty?: boolean }) => {\n const cwd = process.cwd()\n const config = await getConfig()\n\n const probe = await tryResolvePgQueryRunner(config)\n const detectCompositeRefs = probe\n ? (enumName: string) => detectCompositeReferences(probe.runner, enumName)\n : undefined\n\n try {\n const result = await generate({ name, config, cwd, empty: opts.empty, detectCompositeRefs })\n if (result.status === 'no-changes') {\n console.log('No schema changes detected.')\n return\n }\n if (result.empty) {\n console.log(`Created empty migration ${result.migrationDir} (author up.sql + down.sql).`)\n return\n }\n const plural = result.changeCount === 1 ? '' : 's'\n console.log(\n `Created migration ${result.migrationDir} (${result.changeCount} change${plural}).`,\n )\n } finally {\n await probe?.cleanup()\n }\n })\n\n // ── migrate runner subcommands ─────────────────────────────────────────\n const migrate = parent.command('migrate').description('Migration runner subcommands')\n\n migrate\n .command('latest')\n .description('Apply all pending migrations in a new batch')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateLatest({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied batch ${r.batch}: ${r.applied.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('up')\n .description('Apply the next single pending migration')\n .option(\n '--confirm-enum-drop',\n 'Allow migrations carrying the `-- KICK ENUM REMOVE` header to apply',\n false,\n )\n .action(async (opts: { confirmEnumDrop?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateUp({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n confirmEnumDrop: opts.confirmEnumDrop,\n })\n console.log(\n r.applied.length === 0\n ? 'No pending migrations.'\n : `Applied ${r.applied[0]} (batch ${r.batch})`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('down')\n .description('Reverse the most recent applied migration')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateDown({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(r.reversed ? `Reversed ${r.reversed}.` : 'Nothing to reverse.')\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('rollback')\n .description('Reverse the entire last batch as a single unit')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const r = await migrateRollback({\n adapter,\n migrationsDir: config.migrationsDir,\n driftCheck: config.driftCheck,\n })\n console.log(\n r.reversed.length === 0\n ? 'Nothing to roll back.'\n : `Rolled back batch ${r.batch}: ${r.reversed.join(', ')}`,\n )\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('status')\n .description('Print applied + pending migrations')\n .action(async () => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n printStatusTable(await migrateStatus({ adapter, migrationsDir: config.migrationsDir }))\n } finally {\n await cleanup()\n }\n })\n\n migrate\n .command('review <id>')\n .description('Mark a migration reviewed (flips meta.json + the -- REVIEWED markers)')\n .action(async (id: string) => {\n // No adapter/DB needed — review only touches the migration files.\n const config = await getConfig()\n const r = await reviewMigration(config.migrationsDir, id)\n console.log(\n r.alreadyReviewed\n ? `${r.id} was already reviewed.`\n : `Reviewed ${r.id} — it can now be applied.`,\n )\n })\n\n // ── kick db introspect ─────────────────────────────────────────────────\n parent\n .command('introspect')\n .description('Generate a TypeScript schema file from a live database')\n .option('--out <path>', 'Output file (defaults to db.schemaPath from config)')\n .option('--json', 'Print the raw SchemaSnapshot JSON to stdout instead of writing TS source')\n .action(async (opts: { out?: string; json?: boolean }) => {\n const config = await getConfig()\n const { adapter, cleanup } = await resolveAdapter(config)\n try {\n const snapshot = await adapter.introspect()\n if (opts.json) {\n console.log(JSON.stringify(snapshot, null, 2))\n return\n }\n const out = opts.out ?? config.schemaPath\n await writeFile(out, renderSchemaSource(snapshot), 'utf8')\n const n = Object.keys(snapshot.tables).length\n console.log(`Wrote ${out} (${n} table${n === 1 ? '' : 's'}).`)\n } finally {\n await cleanup()\n }\n })\n}\n\n/**\n * Read the `db` block off a host CLI config object. The kit types\n * `ctx.config` as `unknown`; the db block is structurally a\n * {@link KickDbConfigInput}.\n */\nfunction dbBlockOf(config: unknown): KickDbConfigInput | undefined {\n return (config as { db?: KickDbConfigInput } | null)?.db\n}\n\n/**\n * The database CLI plugin. Mount it in `kick.config.ts`:\n *\n * ```ts\n * import { defineConfig } from '@forinda/kickjs-cli'\n * import { dbCliPlugin } from '@forinda/kickjs-db/cli'\n *\n * export default defineConfig({ plugins: [dbCliPlugin] })\n * ```\n *\n * `kick db generate|migrate|introspect` then read config from the\n * `db` block of the same `kick.config.ts`.\n */\nexport const dbCliPlugin: KickCliPlugin = defineCliPlugin({\n name: 'kick/db',\n register(program, ctx) {\n const db = program.command('db').description('Database commands (kickjs-db)')\n registerDbCommands(db, () => resolveKickDbConfig(dbBlockOf(ctx.config)))\n },\n // Mounting the plugin also wires `.kickjs/types/kick__db.d.ts` generation\n // into `kick typegen` — db commands + db types from one opt-in plugin.\n typegens: [kickDbTypegen()],\n})\n"],"mappings":";;;;;;;;;;gXAsBA,MAAM,qBAAuB,CAC3B,mBACA,yBACA,eACF,EAEa,mBAAmC,CAC9C,GAAI,UACJ,OAAQ,CAAC,mBAAoB,uBAAuB,EACpD,MAAM,SAAS,IAAsB,CACnC,IAAM,UAAY,cAAc,IAAI,GAAG,EACvC,GAAI,CAAC,UAAW,OAAO,KAIvB,IAAM,SAAW,KAAK,QAAQ,IAAI,IAAK,eAAe,EAKtD,MAAO,CACL,mGACA,oCANU,MAAM,KAAK,SAAS,SAAU,SAAS,CAAC,CAAC,CAClD,QAAQ,QAAS,EAAE,CAAC,CACpB,QAAQ,WAAY,EAIiB,EAAE,GACxC,GACA,mBACA,sEACA,IACA,GACA,wCACA,+BACA,qCACA,MACA,GACA,wCACA,sDACA,MACA,GACF,CAAC,CAAC,KAAK;CAAI,CACb,CACF,GAEA,SAAS,cAAc,IAA4B,CACjD,IAAK,IAAM,aAAa,qBAAsB,CAC5C,IAAM,IAAM,KAAK,QAAQ,IAAK,SAAS,EACvC,GAAI,UAAU,SAAS,KAAK,MACtB,WAAW,GAAG,EAAG,OAAO,GAAA,KACvB,CACL,IAAM,IAAM,KAAK,KAAK,IAAK,UAAU,EACrC,GAAI,WAAW,GAAG,EAAG,OAAO,GAC9B,CACF,CACA,OAAO,IACT,CAEA,SAAS,MAAM,EAAmB,CAChC,OA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