prisma-next 0.11.0-dev.3 → 0.11.0-dev.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/dist/cli-errors-DFF1LlfU.mjs +215 -0
  2. package/dist/cli-errors-DFF1LlfU.mjs.map +1 -0
  3. package/dist/cli.mjs +8 -9
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/{client-oXO2WCPD.mjs → client-a5NJce0-.mjs} +5 -5
  6. package/dist/{client-oXO2WCPD.mjs.map → client-a5NJce0-.mjs.map} +1 -1
  7. package/dist/{command-helpers-DtavI0wJ.mjs → command-helpers-BnqwTptC.mjs} +380 -6
  8. package/dist/command-helpers-BnqwTptC.mjs.map +1 -0
  9. package/dist/commands/contract-emit.d.mts.map +1 -1
  10. package/dist/commands/contract-emit.mjs +1 -1
  11. package/dist/commands/contract-infer.d.mts.map +1 -1
  12. package/dist/commands/contract-infer.mjs +1 -1
  13. package/dist/commands/db-init.d.mts.map +1 -1
  14. package/dist/commands/db-init.mjs +33 -7
  15. package/dist/commands/db-init.mjs.map +1 -1
  16. package/dist/commands/db-schema.d.mts.map +1 -1
  17. package/dist/commands/db-schema.mjs +3 -4
  18. package/dist/commands/db-schema.mjs.map +1 -1
  19. package/dist/commands/db-sign.d.mts.map +1 -1
  20. package/dist/commands/db-sign.mjs +6 -7
  21. package/dist/commands/db-sign.mjs.map +1 -1
  22. package/dist/commands/db-update.d.mts.map +1 -1
  23. package/dist/commands/db-update.mjs +36 -8
  24. package/dist/commands/db-update.mjs.map +1 -1
  25. package/dist/commands/db-verify.d.mts.map +1 -1
  26. package/dist/commands/db-verify.mjs +1 -1
  27. package/dist/commands/migrate.d.mts +5 -1
  28. package/dist/commands/migrate.d.mts.map +1 -1
  29. package/dist/commands/migrate.mjs +44 -9
  30. package/dist/commands/migrate.mjs.map +1 -1
  31. package/dist/commands/migration-check.d.mts.map +1 -1
  32. package/dist/commands/migration-check.mjs +2 -3
  33. package/dist/commands/migration-check.mjs.map +1 -1
  34. package/dist/commands/migration-graph.d.mts.map +1 -1
  35. package/dist/commands/migration-graph.mjs +2 -3
  36. package/dist/commands/migration-graph.mjs.map +1 -1
  37. package/dist/commands/migration-list.d.mts +57 -13
  38. package/dist/commands/migration-list.d.mts.map +1 -1
  39. package/dist/commands/migration-list.mjs +2 -103
  40. package/dist/commands/migration-log.d.mts.map +1 -1
  41. package/dist/commands/migration-log.mjs +3 -4
  42. package/dist/commands/migration-log.mjs.map +1 -1
  43. package/dist/commands/migration-new.d.mts.map +1 -1
  44. package/dist/commands/migration-new.mjs +3 -4
  45. package/dist/commands/migration-new.mjs.map +1 -1
  46. package/dist/commands/migration-plan.d.mts +1 -0
  47. package/dist/commands/migration-plan.d.mts.map +1 -1
  48. package/dist/commands/migration-plan.mjs +1 -1
  49. package/dist/commands/migration-show.d.mts +1 -1
  50. package/dist/commands/migration-show.d.mts.map +1 -1
  51. package/dist/commands/migration-show.mjs +6 -7
  52. package/dist/commands/migration-show.mjs.map +1 -1
  53. package/dist/commands/migration-status.d.mts.map +1 -1
  54. package/dist/commands/migration-status.mjs +6 -7
  55. package/dist/commands/migration-status.mjs.map +1 -1
  56. package/dist/commands/ref.d.mts +1 -1
  57. package/dist/commands/ref.d.mts.map +1 -1
  58. package/dist/commands/ref.mjs +34 -9
  59. package/dist/commands/ref.mjs.map +1 -1
  60. package/dist/config-loader-B6sJjXTv.mjs.map +1 -1
  61. package/dist/config-loader.d.mts.map +1 -1
  62. package/dist/{contract-emit-bcrpT-wD.mjs → contract-emit-DYBHfZqL.mjs} +8 -7
  63. package/dist/contract-emit-DYBHfZqL.mjs.map +1 -0
  64. package/dist/{contract-emit-uwT-Mj8-.mjs → contract-emit-aFcOi3aw.mjs} +20 -14
  65. package/dist/contract-emit-aFcOi3aw.mjs.map +1 -0
  66. package/dist/{contract-enrichment-Dani0mMW.mjs → contract-enrichment-XmUPhmsS.mjs} +4 -25
  67. package/dist/contract-enrichment-XmUPhmsS.mjs.map +1 -0
  68. package/dist/{contract-infer-pKkiCt7C.mjs → contract-infer-BpJeg-Eu.mjs} +3 -4
  69. package/dist/{contract-infer-pKkiCt7C.mjs.map → contract-infer-BpJeg-Eu.mjs.map} +1 -1
  70. package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs → contract-space-aggregate-loader-EVU3n9YE.mjs} +2 -2
  71. package/dist/{contract-space-aggregate-loader-BmNQwlws.mjs.map → contract-space-aggregate-loader-EVU3n9YE.mjs.map} +1 -1
  72. package/dist/{db-verify-AoIUriL4.mjs → db-verify-CxtdGiL3.mjs} +6 -7
  73. package/dist/{db-verify-AoIUriL4.mjs.map → db-verify-CxtdGiL3.mjs.map} +1 -1
  74. package/dist/exports/control-api.d.mts +1 -1
  75. package/dist/exports/control-api.d.mts.map +1 -1
  76. package/dist/exports/control-api.mjs +3 -3
  77. package/dist/exports/index.d.mts.map +1 -1
  78. package/dist/exports/index.mjs +1 -1
  79. package/dist/exports/index.mjs.map +1 -1
  80. package/dist/exports/init-output.d.mts.map +1 -1
  81. package/dist/exports/init-output.mjs +1 -1
  82. package/dist/{framework-components-65gOHkHB.mjs → framework-components-DTcjouhS.mjs} +2 -2
  83. package/dist/{framework-components-65gOHkHB.mjs.map → framework-components-DTcjouhS.mjs.map} +1 -1
  84. package/dist/global-flags-CdE7M0d9.d.mts.map +1 -1
  85. package/dist/graph-render-DJVv0_uf.mjs.map +1 -1
  86. package/dist/{init-YX6lCJpG.mjs → init-eGkSo7hi.mjs} +5 -5
  87. package/dist/{init-YX6lCJpG.mjs.map → init-eGkSo7hi.mjs.map} +1 -1
  88. package/dist/{inspect-live-schema-LeWvkZVz.mjs → inspect-live-schema-B1GCyjAJ.mjs} +5 -5
  89. package/dist/{inspect-live-schema-LeWvkZVz.mjs.map → inspect-live-schema-B1GCyjAJ.mjs.map} +1 -1
  90. package/dist/migration-cli.d.mts.map +1 -1
  91. package/dist/migration-cli.mjs.map +1 -1
  92. package/dist/{migration-command-scaffold-BtkunvFQ.mjs → migration-command-scaffold-CNdZl60X.mjs} +5 -5
  93. package/dist/{migration-command-scaffold-BtkunvFQ.mjs.map → migration-command-scaffold-CNdZl60X.mjs.map} +1 -1
  94. package/dist/migration-list-CnYiHrNV.mjs +288 -0
  95. package/dist/migration-list-CnYiHrNV.mjs.map +1 -0
  96. package/dist/{migration-plan-C2jeH1J5.mjs → migration-plan-BnmP_yNz.mjs} +346 -88
  97. package/dist/migration-plan-BnmP_yNz.mjs.map +1 -0
  98. package/dist/{migrations-CwZMa1Ck.mjs → migrations-C7YTBnLy.mjs} +11 -2
  99. package/dist/migrations-C7YTBnLy.mjs.map +1 -0
  100. package/dist/{output-BlsrGMEF.mjs → output-CUIdfYo5.mjs} +1 -1
  101. package/dist/{output-BlsrGMEF.mjs.map → output-CUIdfYo5.mjs.map} +1 -1
  102. package/dist/{progress-adapter-DFfvZcYL.mjs → progress-adapter-xASh41wr.mjs} +1 -1
  103. package/dist/{progress-adapter-DFfvZcYL.mjs.map → progress-adapter-xASh41wr.mjs.map} +1 -1
  104. package/dist/ref-advancement-CHJ_8HxQ.mjs +50 -0
  105. package/dist/ref-advancement-CHJ_8HxQ.mjs.map +1 -0
  106. package/dist/{types--CqjMdk0.d.mts → types-UWB2-rrw.d.mts} +12 -4
  107. package/dist/types-UWB2-rrw.d.mts.map +1 -0
  108. package/dist/{verify-Bom75OYI.mjs → verify-DX4RQwq4.mjs} +2 -2
  109. package/dist/{verify-Bom75OYI.mjs.map → verify-DX4RQwq4.mjs.map} +1 -1
  110. package/package.json +12 -12
  111. package/dist/cli-errors-Czmx92Zy.d.mts +0 -3
  112. package/dist/cli-errors-Djtz98Vm.mjs +0 -71
  113. package/dist/cli-errors-Djtz98Vm.mjs.map +0 -1
  114. package/dist/command-helpers-DtavI0wJ.mjs.map +0 -1
  115. package/dist/commands/migration-list.mjs.map +0 -1
  116. package/dist/contract-emit-bcrpT-wD.mjs.map +0 -1
  117. package/dist/contract-emit-uwT-Mj8-.mjs.map +0 -1
  118. package/dist/contract-enrichment-Dani0mMW.mjs.map +0 -1
  119. package/dist/migration-plan-C2jeH1J5.mjs.map +0 -1
  120. package/dist/migrations-CwZMa1Ck.mjs.map +0 -1
  121. package/dist/terminal-ui-BiB_8KNo.mjs +0 -379
  122. package/dist/terminal-ui-BiB_8KNo.mjs.map +0 -1
  123. package/dist/types--CqjMdk0.d.mts.map +0 -1
@@ -1,8 +1,8 @@
1
1
  import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
- import { c as errorDriverRequired, o as errorDatabaseConnectionRequired, t as CliStructuredError, y as errorUnexpected } from "./cli-errors-Djtz98Vm.mjs";
3
- import { S as formatStyledHeader, o as maskConnectionUrl, u as sanitizeErrorMessage } from "./command-helpers-DtavI0wJ.mjs";
4
- import { t as createProgressAdapter } from "./progress-adapter-DFfvZcYL.mjs";
5
- import { t as createControlClient } from "./client-oXO2WCPD.mjs";
2
+ import { O as errorUnexpected, c as errorDriverRequired, o as errorDatabaseConnectionRequired, t as CliStructuredError } from "./cli-errors-DFF1LlfU.mjs";
3
+ import { D as formatStyledHeader, o as maskConnectionUrl, u as sanitizeErrorMessage } from "./command-helpers-BnqwTptC.mjs";
4
+ import { t as createProgressAdapter } from "./progress-adapter-xASh41wr.mjs";
5
+ import { t as createControlClient } from "./client-a5NJce0-.mjs";
6
6
  import { notOk, ok } from "@prisma-next/utils/result";
7
7
  import { relative, resolve } from "pathe";
8
8
  //#region src/commands/inspect-live-schema.ts
@@ -87,4 +87,4 @@ async function inspectLiveSchema(options, flags, ui, startTime, context) {
87
87
  //#endregion
88
88
  export { inspectLiveSchema as t };
89
89
 
90
- //# sourceMappingURL=inspect-live-schema-LeWvkZVz.mjs.map
90
+ //# sourceMappingURL=inspect-live-schema-B1GCyjAJ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"inspect-live-schema-LeWvkZVz.mjs","names":[],"sources":["../src/commands/inspect-live-schema.ts"],"sourcesContent":["import type { CoreSchemaView } from '@prisma-next/framework-components/control';\nimport type { PslDocumentAst } from '@prisma-next/framework-components/psl-ast';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { maskConnectionUrl, sanitizeErrorMessage } from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions, GlobalFlags } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport type { TerminalUI } from '../utils/terminal-ui';\n\nexport interface InspectLiveSchemaOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n}\n\ninterface InspectLiveSchemaContext {\n readonly commandName: string;\n readonly description: string;\n readonly url: string;\n}\n\ntype LoadedCliConfig = Awaited<ReturnType<typeof loadConfig>>;\n\nexport interface InspectLiveSchemaResult {\n readonly config: LoadedCliConfig;\n readonly schema: unknown;\n readonly schemaView: CoreSchemaView | undefined;\n /**\n * PSL AST inferred from the introspected schema, when the configured family\n * implements `PslContractInferCapable`. `undefined` for families that do not\n * support inference (e.g. Mongo today).\n */\n readonly pslContractAst: PslDocumentAst | undefined;\n readonly target: {\n readonly familyId: string;\n readonly id: string;\n };\n readonly meta: {\n readonly configPath?: string;\n readonly dbUrl?: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nexport async function inspectLiveSchema(\n options: InspectLiveSchemaOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n context: InspectLiveSchemaContext,\n): Promise<Result<InspectLiveSchemaResult, CliStructuredError>> {\n let config: LoadedCliConfig;\n try {\n config = await loadConfig(options.config);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: 'Failed to load config',\n }),\n );\n }\n\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n ];\n\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n } else if (config.db?.connection && typeof config.db.connection === 'string') {\n details.push({ label: 'database', value: maskConnectionUrl(config.db.connection) });\n }\n\n ui.stderr(\n formatStyledHeader({\n command: context.commandName,\n description: context.description,\n url: context.url,\n details,\n flags,\n }),\n );\n }\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for ${context.commandName} (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: context.commandName,\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: `Config.driver is required for ${context.commandName}`,\n }),\n );\n }\n\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n const schema = await client.introspect({\n connection: dbConnection,\n onProgress,\n });\n const schemaView = client.toSchemaView(schema);\n const pslContractAst = client.inferPslContract(schema);\n\n const dbUrl = typeof dbConnection === 'string' ? maskConnectionUrl(dbConnection) : undefined;\n\n return ok({\n config,\n schema,\n schemaView,\n pslContractAst,\n target: {\n familyId: config.family.familyId,\n id: config.target.targetId,\n },\n meta: {\n configPath,\n ...(dbUrl ? { dbUrl } : {}),\n },\n timings: {\n total: Date.now() - startTime,\n },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during ${context.commandName}: ${safeMessage}`,\n }),\n );\n } finally {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AAgB,OAAO,kBAAkB,EAAE;EAC5C,CAAC;CACF,MAAM,aAAa,sBAAsB;EAAE;EAAI;EAAO,CAAC;CAEvD,IAAI;EACF,MAAM,SAAS,MAAM,OAAO,WAAW;GACrC,YAAY;GACZ;GACD,CAAC;EACF,MAAM,aAAa,OAAO,aAAa,OAAO;EAC9C,MAAM,iBAAiB,OAAO,iBAAiB,OAAO;EAEtD,MAAM,QAAQ,OAAO,iBAAiB,WAAW,kBAAkB,aAAa,GAAG,KAAA;EAEnF,OAAO,GAAG;GACR;GACA;GACA;GACA;GACA,QAAQ;IACN,UAAU,OAAO,OAAO;IACxB,IAAI,OAAO,OAAO;IACnB;GACD,MAAM;IACJ;IACA,GAAI,QAAQ,EAAE,OAAO,GAAG,EAAE;IAC3B;GACD,SAAS,EACP,OAAO,KAAK,KAAK,GAAG,WACrB;GACF,CAAC;UACK,OAAO;EACd,IAAI,mBAAmB,GAAG,MAAM,EAC9B,OAAO,MAAM,MAAM;EAIrB,MAAM,cAAc,qBADD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAGvE,OAAO,iBAAiB,WAAW,eAAe,KAAA,EACnD;EACD,OAAO,MACL,gBAAgB,aAAa,EAC3B,KAAK,2BAA2B,QAAQ,YAAY,IAAI,eACzD,CAAC,CACH;WACO;EACR,MAAM,OAAO,OAAO"}
1
+ {"version":3,"file":"inspect-live-schema-B1GCyjAJ.mjs","names":[],"sources":["../src/commands/inspect-live-schema.ts"],"sourcesContent":["import type { CoreSchemaView } from '@prisma-next/framework-components/control';\nimport type { PslDocumentAst } from '@prisma-next/framework-components/psl-ast';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport {\n CliStructuredError,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorUnexpected,\n} from '../utils/cli-errors';\nimport { maskConnectionUrl, sanitizeErrorMessage } from '../utils/command-helpers';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions, GlobalFlags } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport type { TerminalUI } from '../utils/terminal-ui';\n\nexport interface InspectLiveSchemaOptions extends CommonCommandOptions {\n readonly db?: string;\n readonly config?: string;\n}\n\ninterface InspectLiveSchemaContext {\n readonly commandName: string;\n readonly description: string;\n readonly url: string;\n}\n\ntype LoadedCliConfig = Awaited<ReturnType<typeof loadConfig>>;\n\nexport interface InspectLiveSchemaResult {\n readonly config: LoadedCliConfig;\n readonly schema: unknown;\n readonly schemaView: CoreSchemaView | undefined;\n /**\n * PSL AST inferred from the introspected schema, when the configured family\n * implements `PslContractInferCapable`. `undefined` for families that do not\n * support inference (e.g. Mongo today).\n */\n readonly pslContractAst: PslDocumentAst | undefined;\n readonly target: {\n readonly familyId: string;\n readonly id: string;\n };\n readonly meta: {\n readonly configPath?: string;\n readonly dbUrl?: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\nexport async function inspectLiveSchema(\n options: InspectLiveSchemaOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n context: InspectLiveSchemaContext,\n): Promise<Result<InspectLiveSchemaResult, CliStructuredError>> {\n let config: LoadedCliConfig;\n try {\n config = await loadConfig(options.config);\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: 'Failed to load config',\n }),\n );\n }\n\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n ];\n\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n } else if (config.db?.connection && typeof config.db.connection === 'string') {\n details.push({ label: 'database', value: maskConnectionUrl(config.db.connection) });\n }\n\n ui.stderr(\n formatStyledHeader({\n command: context.commandName,\n description: context.description,\n url: context.url,\n details,\n flags,\n }),\n );\n }\n\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for ${context.commandName} (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: context.commandName,\n }),\n );\n }\n\n if (!config.driver) {\n return notOk(\n errorDriverRequired({\n why: `Config.driver is required for ${context.commandName}`,\n }),\n );\n }\n\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n const schema = await client.introspect({\n connection: dbConnection,\n onProgress,\n });\n const schemaView = client.toSchemaView(schema);\n const pslContractAst = client.inferPslContract(schema);\n\n const dbUrl = typeof dbConnection === 'string' ? maskConnectionUrl(dbConnection) : undefined;\n\n return ok({\n config,\n schema,\n schemaView,\n pslContractAst,\n target: {\n familyId: config.family.familyId,\n id: config.target.targetId,\n },\n meta: {\n configPath,\n ...(dbUrl ? { dbUrl } : {}),\n },\n timings: {\n total: Date.now() - startTime,\n },\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n const rawMessage = error instanceof Error ? error.message : String(error);\n const safeMessage = sanitizeErrorMessage(\n rawMessage,\n typeof dbConnection === 'string' ? dbConnection : undefined,\n );\n return notOk(\n errorUnexpected(safeMessage, {\n why: `Unexpected error during ${context.commandName}: ${safeMessage}`,\n }),\n );\n } finally {\n await client.close();\n }\n}\n"],"mappings":";;;;;;;;AAsDA,eAAsB,kBACpB,SACA,OACA,IACA,WACA,SAC8D;CAC9D,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,WAAW,QAAQ,MAAM;CAC1C,SAAS,OAAO;EACd,IAAI,mBAAmB,GAAG,KAAK,GAC7B,OAAO,MAAM,KAAK;EAGpB,OAAO,MACL,gBAAgB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,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AiB,WAAW,kBAAkB,YAAY,IAAI,KAAA;EAEnF,OAAO,GAAG;GACR;GACA;GACA;GACA;GACA,QAAQ;IACN,UAAU,OAAO,OAAO;IACxB,IAAI,OAAO,OAAO;GACpB;GACA,MAAM;IACJ;IACA,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;GAC3B;GACA,SAAS,EACP,OAAO,KAAK,IAAI,IAAI,UACtB;EACF,CAAC;CACH,SAAS,OAAO;EACd,IAAI,mBAAmB,GAAG,KAAK,GAC7B,OAAO,MAAM,KAAK;EAIpB,MAAM,cAAc,qBADD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAGtE,OAAO,iBAAiB,WAAW,eAAe,KAAA,CACpD;EACA,OAAO,MACL,gBAAgB,aAAa,EAC3B,KAAK,2BAA2B,QAAQ,YAAY,IAAI,cAC1D,CAAC,CACH;CACF,UAAU;EACR,MAAM,OAAO,MAAM;CACrB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"migration-cli.d.mts","names":[],"sources":["../src/migration-cli.ts"],"mappings":";;;;;;;;;;;;;;;;;;;KA6EY,oBAAA,WAA+B,IAAA,YAAgB,SAAA;;;;;;;;;;;;;;KAe/C,oBAAA,GAAuB,QAAA;;;;;;;;;;;;;cAuEtB,YAAA;;;;;;;;;;;;;;;;;;;;;;;;SAwBE,GAAA,CACX,aAAA,UACA,cAAA,EAAgB,oBAAA,EAChB,OAAA;IAAA,SACW,IAAA;IAAA,SACA,MAAA,GAAS,oBAAA;IAAA,SACT,MAAA,GAAS,oBAAA;EAAA,IAEnB,OAAA;AAAA"}
1
+ {"version":3,"file":"migration-cli.d.mts","names":[],"sources":["../src/migration-cli.ts"],"mappings":";;;;;;;;;;;;;;;;;;;KA6EY,oBAAA,WAA+B,IAAA,YAAgB,SAAS;;;;;;;;;;;;;;KAexD,oBAAA,GAAuB,QAAQ;;;;;;;;;;;;;cAuE9B,YAAA;;;;;;;;;;;;;;;;;;;;;;;;SAwBE,GAAA,CACX,aAAA,UACA,cAAA,EAAgB,oBAAA,EAChB,OAAA;IAAA,SACW,IAAA;IAAA,SACA,MAAA,GAAS,oBAAA;IAAA,SACT,MAAA,GAAS,oBAAA;EAAA,IAEnB,OAAA;AAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"migration-cli.mjs","names":[],"sources":["../src/migration-cli.ts"],"sourcesContent":["/**\n * The migration-file CLI interface: the actor invoked when the author runs\n * `node migration.ts` directly.\n *\n * Naming: this is *not* a \"migration runner\" in the apply-time sense. The\n * apply-time runner is the thing `prisma-next migrate` uses to\n * execute migration JSON ops against a database. `MigrationCLI` is the\n * tiny CLI surface owned by an authored `migration.ts` file: parse the\n * file's argv, load the project's `prisma-next.config.ts`, assemble a\n * `ControlStack`, instantiate the migration class, and serialize.\n *\n * The user authors a migration class, then calls\n * `MigrationCLI.run(import.meta.url, MigrationClass)` at module scope\n * after the class definition. When the file is invoked as a node\n * entrypoint (`node migration.ts`), the CLI:\n *\n * 1. Detects whether the file is the direct entrypoint (no-op when imported).\n * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via\n * [clipanion](https://github.com/arcanis/clipanion).\n * 3. Loads the project's `prisma-next.config.ts` via the same `loadConfig`\n * the CLI commands use, walking up from the migration file's directory.\n * 4. Probe-instantiates the migration class without a stack so it can read\n * `targetId` and verify it matches `config.target.targetId`\n * (`PN-MIG-2006` on mismatch) before any stack-driven adapter\n * construction runs.\n * 5. Assembles a `ControlStack` from the loaded config descriptors and\n * constructs the migration with that stack.\n * 6. Reads any previously-scaffolded `migration.json`, then calls\n * `buildMigrationArtifacts` from `@prisma-next/migration-tools` to\n * produce in-memory `ops.json` + `migration.json` content. Persists\n * the result to disk (or prints in dry-run mode).\n *\n * File I/O lives here, in `@prisma-next/cli`: this is the only place\n * that legitimately combines config loading, stack assembly, and\n * on-disk persistence. `@prisma-next/migration-tools` owns the pure\n * conversion from a `Migration` instance to artifact strings; `Migration`\n * stays a pure abstract class.\n *\n * Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`\n * for its in-process testability and runtime-agnostic execution surface; see\n * `docs/architecture docs/research/commander-friction-points.md` for the\n * evaluation rubric and the durable rationale that drove the choice).\n */\n\nimport { readFileSync, realpathSync, writeFileSync } from 'node:fs';\nimport type { Writable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\nimport {\n CliStructuredError,\n errorMigrationCliInvalidConfigArg,\n errorMigrationCliUnknownFlag,\n} from '@prisma-next/errors/control';\nimport { errorMigrationTargetMismatch } from '@prisma-next/errors/migration';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { errorInvalidJson, MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport { buildMigrationArtifacts, type Migration } from '@prisma-next/migration-tools/migration';\nimport { Cli, Command, Option, UsageError } from 'clipanion';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from './config-loader';\n\n/**\n * Constructor shape accepted by `MigrationCLI.run`. `Migration` subclasses\n * accept an optional `ControlStack` in their constructor (each subclass\n * narrows the stack to its own family/target generics); the CLI always\n * passes one assembled from the loaded config. We use a rest-args `any[]`\n * constructor signature so that subclass constructors with narrower\n * parameter types remain assignable - constructor type compatibility in\n * TS is contravariant in the parameter, and a wider `unknown` parameter\n * on the alias side would reject any narrower subclass signature.\n *\n * The CLI only ever passes one argument (`new MigrationClass(stack)`);\n * the rest-arity is purely a type-compatibility concession for subclass\n * constructors that declare narrower parameter types, not an extension\n * point for additional construction arguments.\n */\n// biome-ignore lint/suspicious/noExplicitAny: see JSDoc - rest args with any are the idiomatic TS pattern for accepting arbitrary subclass constructor signatures\nexport type MigrationConstructor = new (...args: any[]) => Migration;\n\n/**\n * Stream surface accepted by `MigrationCLI.run`'s `options.stdout` /\n * `options.stderr`. Aliases node's `Writable` because clipanion's\n * `BaseContext.stdout`/`stderr` are typed as `Writable`, and the CLI\n * forwards the injected streams into clipanion's context.\n *\n * `process.stdout` and `process.stderr` are `Writable`-shaped, so the\n * default-fallback path remains a no-op for existing two-argument\n * callers like `MigrationCLI.run(import.meta.url, MyMigration)`.\n *\n * Tests inject a `Writable` subclass that captures chunks for\n * assertions.\n */\nexport type MigrationCliWritable = Writable;\n\n/**\n * Flags exposed by the migration-file CLI.\n *\n * Must stay in sync with the `Option` declarations on\n * `MigrationFileCommand` below. This list is rendered in the\n * `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,\n * so order matters for user-visible output (declaration order is the\n * order users see when they run `--help`).\n */\nconst KNOWN_FLAGS: readonly string[] = ['--help', '--dry-run', '--config'];\n\n/**\n * The clipanion command that owns the migration-file CLI's option\n * declarations. The class is internal — `MigrationCLI.run` is the\n * stable public surface. Adding a flag here automatically updates\n * `--help` rendering and the `KNOWN_FLAGS` list (the latter must be\n * updated in tandem).\n */\nclass MigrationFileCommand extends Command {\n static override paths = [Command.Default];\n\n static override usage = Command.Usage({\n description: 'Self-emit ops.json and migration.json from a class-flow migration',\n details: `\n Loads the project's prisma-next.config.ts, assembles a ControlStack\n from the configured target/adapter/extensions, and serializes the\n migration's operations + metadata next to this file.\n `,\n examples: [\n ['Self-emit ops.json + migration.json next to migration.ts', '$0'],\n ['Preview without writing files', '$0 --dry-run'],\n ['Use a non-default config path', '$0 --config ./custom.config.ts'],\n ],\n });\n\n dryRun = Option.Boolean('--dry-run', false, {\n description: 'Print operations to stdout without writing files',\n });\n\n config = Option.String('--config', {\n description: 'Path to prisma-next.config.ts',\n });\n\n /**\n * Unused: orchestration runs inside `MigrationCLI.run` so error\n * routing stays under our control (clipanion's `cli.run` writes\n * error output to `context.stdout`, but our contract requires\n * structured errors on stderr). `cli.process` is used to parse\n * argv into a populated `MigrationFileCommand` instance whose\n * fields drive the orchestration directly.\n */\n override async execute(): Promise<number> {\n return 0;\n }\n}\n\n/**\n * The CLI surface invoked by an authored `migration.ts` file. Exposed as\n * a class with a static `run` method (rather than a free function) to\n * give the concept a stable identity in the ubiquitous language: this is\n * the \"migration-file CLI\", distinct from the apply-time runner that\n * executes migration JSON ops.\n *\n * Currently a single static method. Future surface (e.g. a programmatic\n * `MigrationCLI.serializeOnly(...)` for tests, or extra subcommands) can\n * land here without changing the import shape used by every authored\n * migration.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: see JSDoc - intentional class facade for the migration-file CLI surface; future methods will share state derived from argv/config.\nexport class MigrationCLI {\n /**\n * Orchestrates a class-flow `migration.ts` script run.\n *\n * The third argument is the in-process testability surface: callers\n * (and tests) may inject `argv`, `stdout`, and `stderr` instead of\n * relying on `process.argv` / `process.stdout` / `process.stderr`.\n * Each option defaults to its `process` global when omitted, so\n * existing two-argument call sites\n * (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to\n * compile and behave identically.\n *\n * Returns the exit code so the caller can branch on it. Also writes\n * the same code to `process.exitCode` so script-style callers that\n * don't await the return value still surface a non-zero exit when\n * something fails.\n *\n * Exit codes:\n * - 0 — success, or `--help`, or imported-not-entrypoint no-op.\n * - 1 — runtime/orchestration error (config not found, target\n * mismatch, etc.).\n * - 2 — usage error (unknown flag, malformed `--config`). Aligns\n * with `docs/CLI Style Guide.md` § Exit Codes.\n */\n static async run(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n options: {\n readonly argv?: readonly string[];\n readonly stdout?: MigrationCliWritable;\n readonly stderr?: MigrationCliWritable;\n } = {},\n ): Promise<number> {\n if (!importMetaUrl) {\n return 0;\n }\n\n const argv = options.argv ?? process.argv;\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n\n if (!isDirectEntrypoint(importMetaUrl, argv)) {\n return 0;\n }\n\n const exitCode = await orchestrate(importMetaUrl, MigrationClass, {\n argv,\n stdout,\n stderr,\n });\n // Preserve any pre-existing non-zero `process.exitCode` set by code\n // running alongside `MigrationCLI.run` (an unhandled rejection\n // upstream, an explicit `process.exitCode = N` from another\n // module). Overwriting it with our success would mask the upstream\n // failure for script-style callers that don't await the return\n // value. Failures we return here are still surfaced — non-zero\n // codes always win over the prior status — but successes never\n // clear it.\n if (exitCode !== 0 || !process.exitCode) {\n process.exitCode = exitCode;\n }\n return exitCode;\n }\n}\n\n/**\n * Argv-aware variant of the entrypoint guard. The shared\n * `@prisma-next/migration-tools` helper of the same name reads\n * `process.argv[1]` directly, which doesn't compose with the new\n * in-process testability surface (tests inject `argv` without mutating\n * the process global). Inlined here so the migration-file CLI's check\n * follows the injected `argv[1]` consistently.\n */\nfunction isDirectEntrypoint(importMetaUrl: string, argv: readonly string[]): boolean {\n const argv1 = argv[1];\n if (!argv1) {\n return false;\n }\n try {\n return realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);\n } catch {\n return false;\n }\n}\n\n/**\n * Argv-and-stream-driven orchestration body. Pulled out of the static\n * method so the entrypoint guard / process-default plumbing stays\n * separate from the parse + load + serialize steps.\n */\nasync function orchestrate(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n ctx: {\n readonly argv: readonly string[];\n readonly stdout: MigrationCliWritable;\n readonly stderr: MigrationCliWritable;\n },\n): Promise<number> {\n const cli = Cli.from([MigrationFileCommand], {\n binaryName: 'migration.ts',\n binaryLabel: 'Migration file CLI',\n });\n\n const input = ctx.argv.slice(2);\n\n // Pre-scan for malformed `--config` (no value, or value-shaped-as-flag)\n // before delegating to clipanion. The legacy parser surfaced both as\n // `errorMigrationCliInvalidConfigArg` (`PN-CLI-4012`); pre-scanning\n // here keeps that contract independent of how clipanion classifies\n // the error internally (it variably throws `UnknownSyntaxError` or\n // accepts the flag-shaped token as the value depending on what other\n // options are registered).\n const configError = detectInvalidConfig(input);\n if (configError) {\n writeStructuredError(ctx.stderr, configError);\n return 2;\n }\n\n let parsed: MigrationFileCommand;\n try {\n const command = cli.process({\n input: [...input],\n context: { stdout: ctx.stdout, stderr: ctx.stderr },\n });\n if (!(command instanceof MigrationFileCommand)) {\n // The only registered command class is `MigrationFileCommand`;\n // any other concrete type indicates clipanion emitted its\n // built-in `HelpCommand`. Render usage directly so we don't\n // depend on calling `cli.run` (which routes errors to stdout —\n // wrong stream for our contract).\n ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n return 0;\n }\n parsed = command;\n } catch (err) {\n return renderParseError(err, input, ctx.stderr);\n }\n\n if (parsed.help) {\n ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n return 0;\n }\n\n try {\n await runMigration(importMetaUrl, MigrationClass, parsed, ctx);\n return 0;\n } catch (err) {\n if (CliStructuredError.is(err)) {\n writeStructuredError(ctx.stderr, err);\n } else if (MigrationToolsError.is(err)) {\n // Migration-tools errors (e.g. `errorInvalidJson` thrown by\n // `readExistingMetadata` when migration.json is malformed) carry\n // their own `code`/`why`/`fix` shape. Render them with the same\n // visual structure as `CliStructuredError` so consumers grepping\n // for `MIGRATION.<CODE>` see consistent output across surfaces.\n const fix = err.fix ? `\\n${err.fix}` : '';\n ctx.stderr.write(`${err.code}: ${err.message}\\n${err.why}${fix}\\n`);\n } else {\n ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n }\n return 1;\n }\n}\n\n/**\n * Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`\n * contains a malformed `--config`:\n *\n * - `--config` as the last token (no value follows).\n * - `--config <flag>` where `<flag>` starts with `-` (silently\n * consuming the next flag would either drop the flag or serialize\n * against the wrong project).\n * - `--config <empty>` where the value is the empty string. Shells\n * expand `--config \"\"` (or `--config \"$UNSET_VAR\"`) into a real\n * empty argv token; treating that as a usage error here surfaces\n * `PN-CLI-4012` instead of a less actionable loader error on an\n * empty path.\n * - `--config=` (the equals form with an empty value). Same shape as\n * the empty-string case above; the user expressed intent to override\n * the config path but the override is empty.\n *\n * `--config=<value>` and `--config <value>` with a non-empty value are\n * both valid (and the equals form's value is allowed to start with\n * `-` — the `=` makes the binding explicit).\n */\nfunction detectInvalidConfig(input: readonly string[]): CliStructuredError | null {\n for (let i = 0; i < input.length; i++) {\n const token = input[i];\n if (token === '--config') {\n const next = input[i + 1];\n if (next === undefined || next === '') {\n return errorMigrationCliInvalidConfigArg();\n }\n if (next.startsWith('-')) {\n return errorMigrationCliInvalidConfigArg({ nextToken: next });\n }\n continue;\n }\n if (token === '--config=') {\n return errorMigrationCliInvalidConfigArg();\n }\n }\n return null;\n}\n\n/**\n * Translate clipanion's parse-time errors into the project's structured\n * error envelopes.\n *\n * - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and\n * the bare-trailing `--config` case (where arity-1 needs a value but\n * none was supplied). Distinguished by inspecting the input array.\n * - `UsageError` covers schema/validator failures from typanion. None\n * of the migration-file CLI's options have validators today, but we\n * still translate it as a usage error (exit 2) for forward-compat.\n * - Anything else re-throws — caller's outer catch will surface it as\n * exit 1 (runtime error).\n */\nfunction renderParseError(\n err: unknown,\n input: readonly string[],\n stderr: MigrationCliWritable,\n): number {\n if (isUnknownSyntaxError(err)) {\n const flag = findOffendingFlag(input);\n writeStructuredError(stderr, errorMigrationCliUnknownFlag({ flag, knownFlags: KNOWN_FLAGS }));\n return 2;\n }\n if (err instanceof UsageError) {\n // typanion validator failures and similar usage errors. None of\n // the migration-file CLI's options have validators today, so this\n // branch is forward-compat scaffolding — kept so that a future\n // option declaration with a validator routes through the same PN\n // envelope path rather than escaping as exit 1.\n writeStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));\n return 2;\n }\n throw err;\n}\n\n/**\n * Duck-type check for clipanion's `UnknownSyntaxError`: the class is\n * thrown by the parser but is not re-exported from the package's main\n * entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).\n * Identified by `name === 'UnknownSyntaxError'` and the\n * `clipanion.type === 'none'` discriminator that clipanion's\n * `ErrorWithMeta` interface guarantees.\n */\nfunction isUnknownSyntaxError(err: unknown): err is Error {\n if (!(err instanceof Error) || err.name !== 'UnknownSyntaxError') {\n return false;\n }\n // clipanion's `ErrorWithMeta` interface guarantees a `clipanion` field with\n // a `type` discriminator on every error it throws. Read it via a structural\n // shape rather than importing the class (it's not re-exported from the\n // package main).\n const meta = (err as { clipanion?: { type?: string } }).clipanion;\n return typeof meta === 'object' && meta !== null && meta.type === 'none';\n}\n\n/**\n * Best-effort: pull the first input token that doesn't match a known\n * flag. Falls back to the first token when we can't pinpoint it. The\n * returned name is rendered into the user-visible PN-CLI-4013 envelope\n * (`Unknown flag \\`<name>\\``) and round-tripped via `meta.flag` so\n * agent consumers can render their own \"did you mean\" suggestions.\n */\nfunction findOffendingFlag(input: readonly string[]): string {\n for (const token of input) {\n if (!token.startsWith('-')) {\n continue;\n }\n const head = token.split('=', 1)[0] ?? token;\n if (!KNOWN_FLAGS.includes(head) && head !== '-h') {\n return head;\n }\n }\n return input[0] ?? '';\n}\n\n/**\n * Write a `CliStructuredError` envelope to the given stream. Format\n * matches the legacy hand-rolled writer (`message: why`) so the rest of\n * the project's error rendering stays consistent across surfaces. The\n * full PN code (`PN-<domain>-<code>`) is included so consumers can\n * grep for stable identifiers.\n */\nfunction writeStructuredError(stream: MigrationCliWritable, err: CliStructuredError): void {\n const envelope = err.toEnvelope();\n const why = envelope.why ?? envelope.summary;\n const fix = envelope.fix ? `\\n${envelope.fix}` : '';\n stream.write(`${envelope.code}: ${envelope.summary}\\n${why}${fix}\\n`);\n}\n\n/**\n * Read a previously-scaffolded `migration.json` from disk, returning\n * `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`\n * when the file is present but cannot be parsed as JSON. The CLI feeds\n * this into `buildMigrationArtifacts` so the pure builder can preserve\n * fields owned by `migration plan` (contract bookends, hints, labels,\n * `createdAt`) across re-emits.\n *\n * Author-time path: this loader still does not verify the manifest hash\n * or schema — that is the apply-time loader's job. Hash mismatch is the\n * *expected* outcome of a re-author (the developer's source changes\n * invalidate the prior hash by construction), and verification here\n * would block legitimate regenerations. Syntactic JSON-parse failure,\n * however, is now surfaced rather than swallowed: a malformed\n * `migration.json` indicates either a hand-edit gone wrong or partial\n * write, and silently rebuilding from `describe()` would discard the\n * user's on-disk content (preserved bookends, hints, labels,\n * `createdAt`) without any indication something was wrong on disk.\n * Apply-time consumers always route through the verifying\n * `readMigrationPackage` in `@prisma-next/migration-tools/io` instead.\n */\nfunction readExistingMetadata(metadataPath: string): Partial<MigrationMetadata> | null {\n let raw: string;\n try {\n raw = readFileSync(metadataPath, 'utf-8');\n } catch {\n return null;\n }\n try {\n return JSON.parse(raw) as Partial<MigrationMetadata>;\n } catch (e) {\n throw errorInvalidJson(metadataPath, e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Persist a migration instance's artifacts to `migrationDir`. In\n * `dryRun` mode the artifacts are printed to stdout (with the same\n * `--- migration.json --- / --- ops.json ---` framing the legacy\n * `serializeMigration` helper used) and no files are written. Otherwise\n * `ops.json` and `migration.json` are written next to `migration.ts` and\n * a confirmation line is printed.\n *\n * File I/O lives in the CLI rather than `@prisma-next/migration-tools`\n * so the migration-tools package stays focused on the pure\n * `Migration` → in-memory artifact conversion. The CLI is the only\n * legitimate site for combining config loading, stack assembly, and\n * filesystem persistence.\n */\nfunction serializeMigrationToDisk(\n instance: Migration,\n migrationDir: string,\n dryRun: boolean,\n stdout: MigrationCliWritable,\n): void {\n const metadataPath = join(migrationDir, 'migration.json');\n const existing = readExistingMetadata(metadataPath);\n const { opsJson, metadataJson } = buildMigrationArtifacts(instance, existing);\n\n if (dryRun) {\n stdout.write(`--- migration.json ---\\n${metadataJson}\\n`);\n stdout.write('--- ops.json ---\\n');\n stdout.write(`${opsJson}\\n`);\n return;\n }\n\n writeFileSync(join(migrationDir, 'ops.json'), opsJson);\n writeFileSync(metadataPath, metadataJson);\n\n stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\\n`);\n}\n\n/**\n * Inner orchestration: load config, probe-construct the migration,\n * verify target, assemble the stack, construct with the stack, persist.\n *\n * Throws `CliStructuredError` for known failure modes (config not\n * found, target mismatch); the outer `orchestrate` translates those to\n * exit 1.\n */\nasync function runMigration(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n parsed: MigrationFileCommand,\n ctx: {\n readonly stdout: MigrationCliWritable;\n readonly stderr: MigrationCliWritable;\n },\n): Promise<void> {\n const migrationFile = fileURLToPath(importMetaUrl);\n const migrationDir = dirname(migrationFile);\n\n const config = await loadConfig(parsed.config);\n\n // Probe-instantiate without a stack so we can read `targetId` before\n // any target-specific constructor side effects (e.g.\n // `PostgresMigration`'s `stack.adapter.create(stack)`) run. Concrete\n // subclasses are required to accept the no-arg form; the abstract\n // `Migration` constructor declares `stack?` and target subclasses\n // (Postgres, Mongo) propagate that optionality. This makes the\n // target-mismatch guard fail fast with `PN-MIG-2006` before any\n // stack-driven adapter construction begins, even if the wrong-target\n // adapter's `create` would otherwise succeed and silently misshapen\n // the stored adapter cast.\n const probe = new MigrationClass();\n\n if (probe.targetId !== config.target.targetId) {\n throw errorMigrationTargetMismatch({\n migrationTargetId: probe.targetId,\n configTargetId: config.target.targetId,\n });\n }\n\n const stack = createControlStack(config);\n const instance = new MigrationClass(stack);\n\n serializeMigrationToDisk(instance, migrationDir, parsed.dryRun, ctx.stdout);\n void ctx.stderr;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAM,cAAiC;CAAC;CAAU;CAAa;CAAW;;;;;;;;AAS1E,IAAM,uBAAN,cAAmC,QAAQ;CACzC,OAAgB,QAAQ,CAAC,QAAQ,QAAQ;CAEzC,OAAgB,QAAQ,QAAQ,MAAM;EACpC,aAAa;EACb,SAAS;;;;;EAKT,UAAU;GACR,CAAC,4DAA4D,KAAK;GAClE,CAAC,iCAAiC,eAAe;GACjD,CAAC,iCAAiC,iCAAiC;GACpE;EACF,CAAC;CAEF,SAAS,OAAO,QAAQ,aAAa,OAAO,EAC1C,aAAa,oDACd,CAAC;CAEF,SAAS,OAAO,OAAO,YAAY,EACjC,aAAa,iCACd,CAAC;;;;;;;;;CAUF,MAAe,UAA2B;EACxC,OAAO;;;;;;;;;;;;;;;AAiBX,IAAa,eAAb,MAA0B;;;;;;;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Ac,aAAa;CAEzC,OAAO,MAAM,sCAAsC,aAAa,IAAI;;;;;;;;;;AAWtE,eAAe,aACb,eACA,gBACA,QACA,KAIe;CAEf,MAAM,eAAe,QADC,cAAc,cACM,CAAC;CAE3C,MAAM,SAAS,MAAM,WAAW,OAAO,OAAO;CAY9C,MAAM,QAAQ,IAAI,gBAAgB;CAElC,IAAI,MAAM,aAAa,OAAO,OAAO,UACnC,MAAM,6BAA6B;EACjC,mBAAmB,MAAM;EACzB,gBAAgB,OAAO,OAAO;EAC/B,CAAC;CAMJ,yBAAyB,IAFJ,eADP,mBAAmB,OACQ,CAER,EAAE,cAAc,OAAO,QAAQ,IAAI,OAAO;CAC3E,IAAS"}
1
+ {"version":3,"file":"migration-cli.mjs","names":[],"sources":["../src/migration-cli.ts"],"sourcesContent":["/**\n * The migration-file CLI interface: the actor invoked when the author runs\n * `node migration.ts` directly.\n *\n * Naming: this is *not* a \"migration runner\" in the apply-time sense. The\n * apply-time runner is the thing `prisma-next migrate` uses to\n * execute migration JSON ops against a database. `MigrationCLI` is the\n * tiny CLI surface owned by an authored `migration.ts` file: parse the\n * file's argv, load the project's `prisma-next.config.ts`, assemble a\n * `ControlStack`, instantiate the migration class, and serialize.\n *\n * The user authors a migration class, then calls\n * `MigrationCLI.run(import.meta.url, MigrationClass)` at module scope\n * after the class definition. When the file is invoked as a node\n * entrypoint (`node migration.ts`), the CLI:\n *\n * 1. Detects whether the file is the direct entrypoint (no-op when imported).\n * 2. Parses CLI args (`--help`, `--dry-run`, `--config <path>`) via\n * [clipanion](https://github.com/arcanis/clipanion).\n * 3. Loads the project's `prisma-next.config.ts` via the same `loadConfig`\n * the CLI commands use, walking up from the migration file's directory.\n * 4. Probe-instantiates the migration class without a stack so it can read\n * `targetId` and verify it matches `config.target.targetId`\n * (`PN-MIG-2006` on mismatch) before any stack-driven adapter\n * construction runs.\n * 5. Assembles a `ControlStack` from the loaded config descriptors and\n * constructs the migration with that stack.\n * 6. Reads any previously-scaffolded `migration.json`, then calls\n * `buildMigrationArtifacts` from `@prisma-next/migration-tools` to\n * produce in-memory `ops.json` + `migration.json` content. Persists\n * the result to disk (or prints in dry-run mode).\n *\n * File I/O lives here, in `@prisma-next/cli`: this is the only place\n * that legitimately combines config loading, stack assembly, and\n * on-disk persistence. `@prisma-next/migration-tools` owns the pure\n * conversion from a `Migration` instance to artifact strings; `Migration`\n * stays a pure abstract class.\n *\n * Parser library: clipanion (chosen over Commander/citty/`node:util.parseArgs`\n * for its in-process testability and runtime-agnostic execution surface; see\n * `docs/architecture docs/research/commander-friction-points.md` for the\n * evaluation rubric and the durable rationale that drove the choice).\n */\n\nimport { readFileSync, realpathSync, writeFileSync } from 'node:fs';\nimport type { Writable } from 'node:stream';\nimport { fileURLToPath } from 'node:url';\nimport {\n CliStructuredError,\n errorMigrationCliInvalidConfigArg,\n errorMigrationCliUnknownFlag,\n} from '@prisma-next/errors/control';\nimport { errorMigrationTargetMismatch } from '@prisma-next/errors/migration';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { errorInvalidJson, MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type { MigrationMetadata } from '@prisma-next/migration-tools/metadata';\nimport { buildMigrationArtifacts, type Migration } from '@prisma-next/migration-tools/migration';\nimport { Cli, Command, Option, UsageError } from 'clipanion';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from './config-loader';\n\n/**\n * Constructor shape accepted by `MigrationCLI.run`. `Migration` subclasses\n * accept an optional `ControlStack` in their constructor (each subclass\n * narrows the stack to its own family/target generics); the CLI always\n * passes one assembled from the loaded config. We use a rest-args `any[]`\n * constructor signature so that subclass constructors with narrower\n * parameter types remain assignable - constructor type compatibility in\n * TS is contravariant in the parameter, and a wider `unknown` parameter\n * on the alias side would reject any narrower subclass signature.\n *\n * The CLI only ever passes one argument (`new MigrationClass(stack)`);\n * the rest-arity is purely a type-compatibility concession for subclass\n * constructors that declare narrower parameter types, not an extension\n * point for additional construction arguments.\n */\n// biome-ignore lint/suspicious/noExplicitAny: see JSDoc - rest args with any are the idiomatic TS pattern for accepting arbitrary subclass constructor signatures\nexport type MigrationConstructor = new (...args: any[]) => Migration;\n\n/**\n * Stream surface accepted by `MigrationCLI.run`'s `options.stdout` /\n * `options.stderr`. Aliases node's `Writable` because clipanion's\n * `BaseContext.stdout`/`stderr` are typed as `Writable`, and the CLI\n * forwards the injected streams into clipanion's context.\n *\n * `process.stdout` and `process.stderr` are `Writable`-shaped, so the\n * default-fallback path remains a no-op for existing two-argument\n * callers like `MigrationCLI.run(import.meta.url, MyMigration)`.\n *\n * Tests inject a `Writable` subclass that captures chunks for\n * assertions.\n */\nexport type MigrationCliWritable = Writable;\n\n/**\n * Flags exposed by the migration-file CLI.\n *\n * Must stay in sync with the `Option` declarations on\n * `MigrationFileCommand` below. This list is rendered in the\n * `errorMigrationCliUnknownFlag` envelope's `fix` text and `meta`,\n * so order matters for user-visible output (declaration order is the\n * order users see when they run `--help`).\n */\nconst KNOWN_FLAGS: readonly string[] = ['--help', '--dry-run', '--config'];\n\n/**\n * The clipanion command that owns the migration-file CLI's option\n * declarations. The class is internal — `MigrationCLI.run` is the\n * stable public surface. Adding a flag here automatically updates\n * `--help` rendering and the `KNOWN_FLAGS` list (the latter must be\n * updated in tandem).\n */\nclass MigrationFileCommand extends Command {\n static override paths = [Command.Default];\n\n static override usage = Command.Usage({\n description: 'Self-emit ops.json and migration.json from a class-flow migration',\n details: `\n Loads the project's prisma-next.config.ts, assembles a ControlStack\n from the configured target/adapter/extensions, and serializes the\n migration's operations + metadata next to this file.\n `,\n examples: [\n ['Self-emit ops.json + migration.json next to migration.ts', '$0'],\n ['Preview without writing files', '$0 --dry-run'],\n ['Use a non-default config path', '$0 --config ./custom.config.ts'],\n ],\n });\n\n dryRun = Option.Boolean('--dry-run', false, {\n description: 'Print operations to stdout without writing files',\n });\n\n config = Option.String('--config', {\n description: 'Path to prisma-next.config.ts',\n });\n\n /**\n * Unused: orchestration runs inside `MigrationCLI.run` so error\n * routing stays under our control (clipanion's `cli.run` writes\n * error output to `context.stdout`, but our contract requires\n * structured errors on stderr). `cli.process` is used to parse\n * argv into a populated `MigrationFileCommand` instance whose\n * fields drive the orchestration directly.\n */\n override async execute(): Promise<number> {\n return 0;\n }\n}\n\n/**\n * The CLI surface invoked by an authored `migration.ts` file. Exposed as\n * a class with a static `run` method (rather than a free function) to\n * give the concept a stable identity in the ubiquitous language: this is\n * the \"migration-file CLI\", distinct from the apply-time runner that\n * executes migration JSON ops.\n *\n * Currently a single static method. Future surface (e.g. a programmatic\n * `MigrationCLI.serializeOnly(...)` for tests, or extra subcommands) can\n * land here without changing the import shape used by every authored\n * migration.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: see JSDoc - intentional class facade for the migration-file CLI surface; future methods will share state derived from argv/config.\nexport class MigrationCLI {\n /**\n * Orchestrates a class-flow `migration.ts` script run.\n *\n * The third argument is the in-process testability surface: callers\n * (and tests) may inject `argv`, `stdout`, and `stderr` instead of\n * relying on `process.argv` / `process.stdout` / `process.stderr`.\n * Each option defaults to its `process` global when omitted, so\n * existing two-argument call sites\n * (`MigrationCLI.run(import.meta.url, MyMigration)`) continue to\n * compile and behave identically.\n *\n * Returns the exit code so the caller can branch on it. Also writes\n * the same code to `process.exitCode` so script-style callers that\n * don't await the return value still surface a non-zero exit when\n * something fails.\n *\n * Exit codes:\n * - 0 — success, or `--help`, or imported-not-entrypoint no-op.\n * - 1 — runtime/orchestration error (config not found, target\n * mismatch, etc.).\n * - 2 — usage error (unknown flag, malformed `--config`). Aligns\n * with `docs/CLI Style Guide.md` § Exit Codes.\n */\n static async run(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n options: {\n readonly argv?: readonly string[];\n readonly stdout?: MigrationCliWritable;\n readonly stderr?: MigrationCliWritable;\n } = {},\n ): Promise<number> {\n if (!importMetaUrl) {\n return 0;\n }\n\n const argv = options.argv ?? process.argv;\n const stdout = options.stdout ?? process.stdout;\n const stderr = options.stderr ?? process.stderr;\n\n if (!isDirectEntrypoint(importMetaUrl, argv)) {\n return 0;\n }\n\n const exitCode = await orchestrate(importMetaUrl, MigrationClass, {\n argv,\n stdout,\n stderr,\n });\n // Preserve any pre-existing non-zero `process.exitCode` set by code\n // running alongside `MigrationCLI.run` (an unhandled rejection\n // upstream, an explicit `process.exitCode = N` from another\n // module). Overwriting it with our success would mask the upstream\n // failure for script-style callers that don't await the return\n // value. Failures we return here are still surfaced — non-zero\n // codes always win over the prior status — but successes never\n // clear it.\n if (exitCode !== 0 || !process.exitCode) {\n process.exitCode = exitCode;\n }\n return exitCode;\n }\n}\n\n/**\n * Argv-aware variant of the entrypoint guard. The shared\n * `@prisma-next/migration-tools` helper of the same name reads\n * `process.argv[1]` directly, which doesn't compose with the new\n * in-process testability surface (tests inject `argv` without mutating\n * the process global). Inlined here so the migration-file CLI's check\n * follows the injected `argv[1]` consistently.\n */\nfunction isDirectEntrypoint(importMetaUrl: string, argv: readonly string[]): boolean {\n const argv1 = argv[1];\n if (!argv1) {\n return false;\n }\n try {\n return realpathSync(fileURLToPath(importMetaUrl)) === realpathSync(argv1);\n } catch {\n return false;\n }\n}\n\n/**\n * Argv-and-stream-driven orchestration body. Pulled out of the static\n * method so the entrypoint guard / process-default plumbing stays\n * separate from the parse + load + serialize steps.\n */\nasync function orchestrate(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n ctx: {\n readonly argv: readonly string[];\n readonly stdout: MigrationCliWritable;\n readonly stderr: MigrationCliWritable;\n },\n): Promise<number> {\n const cli = Cli.from([MigrationFileCommand], {\n binaryName: 'migration.ts',\n binaryLabel: 'Migration file CLI',\n });\n\n const input = ctx.argv.slice(2);\n\n // Pre-scan for malformed `--config` (no value, or value-shaped-as-flag)\n // before delegating to clipanion. The legacy parser surfaced both as\n // `errorMigrationCliInvalidConfigArg` (`PN-CLI-4012`); pre-scanning\n // here keeps that contract independent of how clipanion classifies\n // the error internally (it variably throws `UnknownSyntaxError` or\n // accepts the flag-shaped token as the value depending on what other\n // options are registered).\n const configError = detectInvalidConfig(input);\n if (configError) {\n writeStructuredError(ctx.stderr, configError);\n return 2;\n }\n\n let parsed: MigrationFileCommand;\n try {\n const command = cli.process({\n input: [...input],\n context: { stdout: ctx.stdout, stderr: ctx.stderr },\n });\n if (!(command instanceof MigrationFileCommand)) {\n // The only registered command class is `MigrationFileCommand`;\n // any other concrete type indicates clipanion emitted its\n // built-in `HelpCommand`. Render usage directly so we don't\n // depend on calling `cli.run` (which routes errors to stdout —\n // wrong stream for our contract).\n ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n return 0;\n }\n parsed = command;\n } catch (err) {\n return renderParseError(err, input, ctx.stderr);\n }\n\n if (parsed.help) {\n ctx.stdout.write(cli.usage(MigrationFileCommand, { detailed: true }));\n return 0;\n }\n\n try {\n await runMigration(importMetaUrl, MigrationClass, parsed, ctx);\n return 0;\n } catch (err) {\n if (CliStructuredError.is(err)) {\n writeStructuredError(ctx.stderr, err);\n } else if (MigrationToolsError.is(err)) {\n // Migration-tools errors (e.g. `errorInvalidJson` thrown by\n // `readExistingMetadata` when migration.json is malformed) carry\n // their own `code`/`why`/`fix` shape. Render them with the same\n // visual structure as `CliStructuredError` so consumers grepping\n // for `MIGRATION.<CODE>` see consistent output across surfaces.\n const fix = err.fix ? `\\n${err.fix}` : '';\n ctx.stderr.write(`${err.code}: ${err.message}\\n${err.why}${fix}\\n`);\n } else {\n ctx.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`);\n }\n return 1;\n }\n}\n\n/**\n * Returns an `errorMigrationCliInvalidConfigArg` envelope when `input`\n * contains a malformed `--config`:\n *\n * - `--config` as the last token (no value follows).\n * - `--config <flag>` where `<flag>` starts with `-` (silently\n * consuming the next flag would either drop the flag or serialize\n * against the wrong project).\n * - `--config <empty>` where the value is the empty string. Shells\n * expand `--config \"\"` (or `--config \"$UNSET_VAR\"`) into a real\n * empty argv token; treating that as a usage error here surfaces\n * `PN-CLI-4012` instead of a less actionable loader error on an\n * empty path.\n * - `--config=` (the equals form with an empty value). Same shape as\n * the empty-string case above; the user expressed intent to override\n * the config path but the override is empty.\n *\n * `--config=<value>` and `--config <value>` with a non-empty value are\n * both valid (and the equals form's value is allowed to start with\n * `-` — the `=` makes the binding explicit).\n */\nfunction detectInvalidConfig(input: readonly string[]): CliStructuredError | null {\n for (let i = 0; i < input.length; i++) {\n const token = input[i];\n if (token === '--config') {\n const next = input[i + 1];\n if (next === undefined || next === '') {\n return errorMigrationCliInvalidConfigArg();\n }\n if (next.startsWith('-')) {\n return errorMigrationCliInvalidConfigArg({ nextToken: next });\n }\n continue;\n }\n if (token === '--config=') {\n return errorMigrationCliInvalidConfigArg();\n }\n }\n return null;\n}\n\n/**\n * Translate clipanion's parse-time errors into the project's structured\n * error envelopes.\n *\n * - `UnknownSyntaxError` covers both unknown flags (`--frobnicate`) and\n * the bare-trailing `--config` case (where arity-1 needs a value but\n * none was supplied). Distinguished by inspecting the input array.\n * - `UsageError` covers schema/validator failures from typanion. None\n * of the migration-file CLI's options have validators today, but we\n * still translate it as a usage error (exit 2) for forward-compat.\n * - Anything else re-throws — caller's outer catch will surface it as\n * exit 1 (runtime error).\n */\nfunction renderParseError(\n err: unknown,\n input: readonly string[],\n stderr: MigrationCliWritable,\n): number {\n if (isUnknownSyntaxError(err)) {\n const flag = findOffendingFlag(input);\n writeStructuredError(stderr, errorMigrationCliUnknownFlag({ flag, knownFlags: KNOWN_FLAGS }));\n return 2;\n }\n if (err instanceof UsageError) {\n // typanion validator failures and similar usage errors. None of\n // the migration-file CLI's options have validators today, so this\n // branch is forward-compat scaffolding — kept so that a future\n // option declaration with a validator routes through the same PN\n // envelope path rather than escaping as exit 1.\n writeStructuredError(stderr, errorMigrationCliInvalidConfigArg({ nextToken: err.message }));\n return 2;\n }\n throw err;\n}\n\n/**\n * Duck-type check for clipanion's `UnknownSyntaxError`: the class is\n * thrown by the parser but is not re-exported from the package's main\n * entry (only `UsageError` is — see clipanion's `advanced/index.d.ts`).\n * Identified by `name === 'UnknownSyntaxError'` and the\n * `clipanion.type === 'none'` discriminator that clipanion's\n * `ErrorWithMeta` interface guarantees.\n */\nfunction isUnknownSyntaxError(err: unknown): err is Error {\n if (!(err instanceof Error) || err.name !== 'UnknownSyntaxError') {\n return false;\n }\n // clipanion's `ErrorWithMeta` interface guarantees a `clipanion` field with\n // a `type` discriminator on every error it throws. Read it via a structural\n // shape rather than importing the class (it's not re-exported from the\n // package main).\n const meta = (err as { clipanion?: { type?: string } }).clipanion;\n return typeof meta === 'object' && meta !== null && meta.type === 'none';\n}\n\n/**\n * Best-effort: pull the first input token that doesn't match a known\n * flag. Falls back to the first token when we can't pinpoint it. The\n * returned name is rendered into the user-visible PN-CLI-4013 envelope\n * (`Unknown flag \\`<name>\\``) and round-tripped via `meta.flag` so\n * agent consumers can render their own \"did you mean\" suggestions.\n */\nfunction findOffendingFlag(input: readonly string[]): string {\n for (const token of input) {\n if (!token.startsWith('-')) {\n continue;\n }\n const head = token.split('=', 1)[0] ?? token;\n if (!KNOWN_FLAGS.includes(head) && head !== '-h') {\n return head;\n }\n }\n return input[0] ?? '';\n}\n\n/**\n * Write a `CliStructuredError` envelope to the given stream. Format\n * matches the legacy hand-rolled writer (`message: why`) so the rest of\n * the project's error rendering stays consistent across surfaces. The\n * full PN code (`PN-<domain>-<code>`) is included so consumers can\n * grep for stable identifiers.\n */\nfunction writeStructuredError(stream: MigrationCliWritable, err: CliStructuredError): void {\n const envelope = err.toEnvelope();\n const why = envelope.why ?? envelope.summary;\n const fix = envelope.fix ? `\\n${envelope.fix}` : '';\n stream.write(`${envelope.code}: ${envelope.summary}\\n${why}${fix}\\n`);\n}\n\n/**\n * Read a previously-scaffolded `migration.json` from disk, returning\n * `null` when the file is missing and throwing `MIGRATION.INVALID_JSON`\n * when the file is present but cannot be parsed as JSON. The CLI feeds\n * this into `buildMigrationArtifacts` so the pure builder can preserve\n * fields owned by `migration plan` (contract bookends, hints, labels,\n * `createdAt`) across re-emits.\n *\n * Author-time path: this loader still does not verify the manifest hash\n * or schema — that is the apply-time loader's job. Hash mismatch is the\n * *expected* outcome of a re-author (the developer's source changes\n * invalidate the prior hash by construction), and verification here\n * would block legitimate regenerations. Syntactic JSON-parse failure,\n * however, is now surfaced rather than swallowed: a malformed\n * `migration.json` indicates either a hand-edit gone wrong or partial\n * write, and silently rebuilding from `describe()` would discard the\n * user's on-disk content (preserved bookends, hints, labels,\n * `createdAt`) without any indication something was wrong on disk.\n * Apply-time consumers always route through the verifying\n * `readMigrationPackage` in `@prisma-next/migration-tools/io` instead.\n */\nfunction readExistingMetadata(metadataPath: string): Partial<MigrationMetadata> | null {\n let raw: string;\n try {\n raw = readFileSync(metadataPath, 'utf-8');\n } catch {\n return null;\n }\n try {\n return JSON.parse(raw) as Partial<MigrationMetadata>;\n } catch (e) {\n throw errorInvalidJson(metadataPath, e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Persist a migration instance's artifacts to `migrationDir`. In\n * `dryRun` mode the artifacts are printed to stdout (with the same\n * `--- migration.json --- / --- ops.json ---` framing the legacy\n * `serializeMigration` helper used) and no files are written. Otherwise\n * `ops.json` and `migration.json` are written next to `migration.ts` and\n * a confirmation line is printed.\n *\n * File I/O lives in the CLI rather than `@prisma-next/migration-tools`\n * so the migration-tools package stays focused on the pure\n * `Migration` → in-memory artifact conversion. The CLI is the only\n * legitimate site for combining config loading, stack assembly, and\n * filesystem persistence.\n */\nfunction serializeMigrationToDisk(\n instance: Migration,\n migrationDir: string,\n dryRun: boolean,\n stdout: MigrationCliWritable,\n): void {\n const metadataPath = join(migrationDir, 'migration.json');\n const existing = readExistingMetadata(metadataPath);\n const { opsJson, metadataJson } = buildMigrationArtifacts(instance, existing);\n\n if (dryRun) {\n stdout.write(`--- migration.json ---\\n${metadataJson}\\n`);\n stdout.write('--- ops.json ---\\n');\n stdout.write(`${opsJson}\\n`);\n return;\n }\n\n writeFileSync(join(migrationDir, 'ops.json'), opsJson);\n writeFileSync(metadataPath, metadataJson);\n\n stdout.write(`Wrote ops.json + migration.json to ${migrationDir}\\n`);\n}\n\n/**\n * Inner orchestration: load config, probe-construct the migration,\n * verify target, assemble the stack, construct with the stack, persist.\n *\n * Throws `CliStructuredError` for known failure modes (config not\n * found, target mismatch); the outer `orchestrate` translates those to\n * exit 1.\n */\nasync function runMigration(\n importMetaUrl: string,\n MigrationClass: MigrationConstructor,\n parsed: MigrationFileCommand,\n ctx: {\n readonly stdout: MigrationCliWritable;\n readonly stderr: MigrationCliWritable;\n },\n): Promise<void> {\n const migrationFile = fileURLToPath(importMetaUrl);\n const migrationDir = dirname(migrationFile);\n\n const config = await loadConfig(parsed.config);\n\n // Probe-instantiate without a stack so we can read `targetId` before\n // any target-specific constructor side effects (e.g.\n // `PostgresMigration`'s `stack.adapter.create(stack)`) run. Concrete\n // subclasses are required to accept the no-arg form; the abstract\n // `Migration` constructor declares `stack?` and target subclasses\n // (Postgres, Mongo) propagate that optionality. This makes the\n // target-mismatch guard fail fast with `PN-MIG-2006` before any\n // stack-driven adapter construction begins, even if the wrong-target\n // adapter's `create` would otherwise succeed and silently misshapen\n // the stored adapter cast.\n const probe = new MigrationClass();\n\n if (probe.targetId !== config.target.targetId) {\n throw errorMigrationTargetMismatch({\n migrationTargetId: probe.targetId,\n configTargetId: config.target.targetId,\n });\n }\n\n const stack = createControlStack(config);\n const instance = new MigrationClass(stack);\n\n serializeMigrationToDisk(instance, migrationDir, parsed.dryRun, ctx.stdout);\n void ctx.stderr;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuGA,MAAM,cAAiC;CAAC;CAAU;CAAa;AAAU;;;;;;;;AASzE,IAAM,uBAAN,cAAmC,QAAQ;CACzC,OAAgB,QAAQ,CAAC,QAAQ,OAAO;CAExC,OAAgB,QAAQ,QAAQ,MAAM;EACpC,aAAa;EACb,SAAS;;;;;EAKT,UAAU;GACR,CAAC,4DAA4D,IAAI;GACjE,CAAC,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AAE,UAAU,OAAO,CAAC,CAAC;CACjF;AACF;;;;;;;;;;;;;;;AAgBA,SAAS,yBACP,UACA,cACA,QACA,QACM;CACN,MAAM,eAAe,KAAK,cAAc,gBAAgB;CAExD,MAAM,EAAE,SAAS,iBAAiB,wBAAwB,UADzC,qBAAqB,YACqC,CAAC;CAE5E,IAAI,QAAQ;EACV,OAAO,MAAM,2BAA2B,aAAa,GAAG;EACxD,OAAO,MAAM,oBAAoB;EACjC,OAAO,MAAM,GAAG,QAAQ,GAAG;EAC3B;CACF;CAEA,cAAc,KAAK,cAAc,UAAU,GAAG,OAAO;CACrD,cAAc,cAAc,YAAY;CAExC,OAAO,MAAM,sCAAsC,aAAa,GAAG;AACrE;;;;;;;;;AAUA,eAAe,aACb,eACA,gBACA,QACA,KAIe;CAEf,MAAM,eAAe,QADC,cAAc,aACK,CAAC;CAE1C,MAAM,SAAS,MAAM,WAAW,OAAO,MAAM;CAY7C,MAAM,QAAQ,IAAI,eAAe;CAEjC,IAAI,MAAM,aAAa,OAAO,OAAO,UACnC,MAAM,6BAA6B;EACjC,mBAAmB,MAAM;EACzB,gBAAgB,OAAO,OAAO;CAChC,CAAC;CAMH,yBAAyB,IAFJ,eADP,mBAAmB,MACO,CAER,GAAG,cAAc,OAAO,QAAQ,IAAI,MAAM;CAC1E,IAAS;AACX"}
@@ -1,8 +1,8 @@
1
1
  import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
- import { _ as errorTargetMigrationNotSupported, a as errorContractValidationFailed, c as errorDriverRequired, l as errorFileNotFound, o as errorDatabaseConnectionRequired, y as errorUnexpected } from "./cli-errors-Djtz98Vm.mjs";
3
- import { S as formatStyledHeader, c as resolveContractPath, o as maskConnectionUrl, t as addGlobalOptions } from "./command-helpers-DtavI0wJ.mjs";
4
- import { t as createProgressAdapter } from "./progress-adapter-DFfvZcYL.mjs";
5
- import { t as createControlClient } from "./client-oXO2WCPD.mjs";
2
+ import { E as errorTargetMigrationNotSupported, O as errorUnexpected, a as errorContractValidationFailed, c as errorDriverRequired, l as errorFileNotFound, o as errorDatabaseConnectionRequired } from "./cli-errors-DFF1LlfU.mjs";
3
+ import { D as formatStyledHeader, c as resolveContractPath, o as maskConnectionUrl, t as addGlobalOptions } from "./command-helpers-BnqwTptC.mjs";
4
+ import { t as createProgressAdapter } from "./progress-adapter-xASh41wr.mjs";
5
+ import { t as createControlClient } from "./client-a5NJce0-.mjs";
6
6
  import { notOk, ok } from "@prisma-next/utils/result";
7
7
  import { readFile } from "node:fs/promises";
8
8
  import { hasMigrations } from "@prisma-next/framework-components/control";
@@ -101,4 +101,4 @@ function addMigrationCommandOptions(command) {
101
101
  //#endregion
102
102
  export { prepareMigrationContext as n, addMigrationCommandOptions as t };
103
103
 
104
- //# sourceMappingURL=migration-command-scaffold-BtkunvFQ.mjs.map
104
+ //# sourceMappingURL=migration-command-scaffold-CNdZl60X.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-command-scaffold-BtkunvFQ.mjs","names":[],"sources":["../src/utils/migration-command-scaffold.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport { hasMigrations } from '@prisma-next/framework-components/control';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport type { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { ControlClient } from '../control-api/types';\nimport {\n type CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from './cli-errors';\nimport { addGlobalOptions, maskConnectionUrl, resolveContractPath } from './command-helpers';\nimport { formatStyledHeader } from './formatters/styled';\nimport type { GlobalFlags } from './global-flags';\nimport { createProgressAdapter } from './progress-adapter';\nimport type { TerminalUI } from './terminal-ui';\n\n/**\n * Resolved context for a migration command.\n * Contains everything needed to invoke a control-api operation.\n */\nexport interface MigrationContext {\n readonly client: ControlClient;\n readonly contractJson: Record<string, unknown>;\n readonly dbConnection: unknown;\n readonly onProgress: ReturnType<typeof createProgressAdapter>;\n readonly configPath: string;\n readonly contractPath: string;\n readonly contractPathAbsolute: string;\n readonly config: Awaited<ReturnType<typeof loadConfig>>;\n}\n\n/**\n * Command-specific configuration for the shared scaffold.\n */\nexport interface MigrationCommandDescriptor {\n readonly commandName: string;\n readonly description: string;\n readonly url: string;\n}\n\n/**\n * Prepares the shared context for migration commands (db init, db update).\n *\n * Handles: config loading, contract file reading, JSON parsing, connection resolution,\n * driver/migration-support validation, client creation, and header output.\n *\n * Returns a Result with either the resolved context or a structured error.\n */\nexport async function prepareMigrationContext(\n options: { readonly db?: string; readonly config?: string; readonly dryRun?: boolean },\n flags: GlobalFlags,\n ui: TerminalUI,\n descriptor: MigrationCommandDescriptor,\n): Promise<Result<MigrationContext, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header to stderr (decoration)\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n }\n if (options.dryRun) {\n details.push({ label: 'mode', value: 'dry run' });\n }\n const header = formatStyledHeader({\n command: descriptor.commandName,\n description: descriptor.description,\n url: descriptor.url,\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n // Parse contract JSON\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for ${descriptor.commandName} (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: descriptor.commandName,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(\n errorDriverRequired({ why: `Config.driver is required for ${descriptor.commandName}` }),\n );\n }\n\n if (!hasMigrations(config.target)) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ ui, flags });\n\n return ok({\n client,\n contractJson,\n dbConnection,\n onProgress,\n configPath,\n contractPath,\n contractPathAbsolute,\n config,\n });\n}\n\n/**\n * Registers the shared CLI options for migration commands (db init, db update).\n */\nexport function addMigrationCommandOptions(command: Command): Command {\n addGlobalOptions(command);\n return command\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--dry-run', 'Preview planned operations without applying', false);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,eAAsB,wBACpB,SACA,OACA,IACA,YACuD;CAEvD,MAAM,SAAS,MAAM,WAAW,QAAQ,OAAO;CAC/C,MAAM,aAAa,QAA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cACH,OAAO,MACL,gCAAgC;EAC9B,KAAK,uCAAuC,WAAW,YAAY,yBAAyB,WAAW;EACvG,aAAa,WAAW;EACzB,CAAC,CACH;CAIH,IAAI,CAAC,OAAO,QACV,OAAO,MACL,oBAAoB,EAAE,KAAK,iCAAiC,WAAW,eAAe,CAAC,CACxF;CAGH,IAAI,CAAC,cAAc,OAAO,OAAO,EAC/B,OAAO,MACL,iCAAiC,EAC/B,KAAK,WAAW,OAAO,OAAO,GAAG,gCAClC,CAAC,CACH;CAIH,MAAM,SAAS,oBAAoB;EACjC,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,SAAS,OAAO;EAChB,QAAQ,OAAO;EACf,gBAAgB,OAAO,kBAAkB,EAAE;EAC5C,CAAC;CAGF,MAAM,aAAa,sBAAsB;EAAE;EAAI;EAAO,CAAC;CAEvD,OAAO,GAAG;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;;;;;AAMJ,SAAgB,2BAA2B,SAA2B;CACpE,iBAAiB,QAAQ;CACzB,OAAO,QACJ,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,aAAa,+CAA+C,MAAM"}
1
+ {"version":3,"file":"migration-command-scaffold-CNdZl60X.mjs","names":[],"sources":["../src/utils/migration-command-scaffold.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { relative, resolve } from 'node:path';\nimport { hasMigrations } from '@prisma-next/framework-components/control';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport type { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { ControlClient } from '../control-api/types';\nimport {\n type CliStructuredError,\n errorContractValidationFailed,\n errorDatabaseConnectionRequired,\n errorDriverRequired,\n errorFileNotFound,\n errorTargetMigrationNotSupported,\n errorUnexpected,\n} from './cli-errors';\nimport { addGlobalOptions, maskConnectionUrl, resolveContractPath } from './command-helpers';\nimport { formatStyledHeader } from './formatters/styled';\nimport type { GlobalFlags } from './global-flags';\nimport { createProgressAdapter } from './progress-adapter';\nimport type { TerminalUI } from './terminal-ui';\n\n/**\n * Resolved context for a migration command.\n * Contains everything needed to invoke a control-api operation.\n */\nexport interface MigrationContext {\n readonly client: ControlClient;\n readonly contractJson: Record<string, unknown>;\n readonly dbConnection: unknown;\n readonly onProgress: ReturnType<typeof createProgressAdapter>;\n readonly configPath: string;\n readonly contractPath: string;\n readonly contractPathAbsolute: string;\n readonly config: Awaited<ReturnType<typeof loadConfig>>;\n}\n\n/**\n * Command-specific configuration for the shared scaffold.\n */\nexport interface MigrationCommandDescriptor {\n readonly commandName: string;\n readonly description: string;\n readonly url: string;\n}\n\n/**\n * Prepares the shared context for migration commands (db init, db update).\n *\n * Handles: config loading, contract file reading, JSON parsing, connection resolution,\n * driver/migration-support validation, client creation, and header output.\n *\n * Returns a Result with either the resolved context or a structured error.\n */\nexport async function prepareMigrationContext(\n options: { readonly db?: string; readonly config?: string; readonly dryRun?: boolean },\n flags: GlobalFlags,\n ui: TerminalUI,\n descriptor: MigrationCommandDescriptor,\n): Promise<Result<MigrationContext, CliStructuredError>> {\n // Load config\n const config = await loadConfig(options.config);\n const configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n const contractPathAbsolute = resolveContractPath(config);\n const contractPath = relative(process.cwd(), contractPathAbsolute);\n\n // Output header to stderr (decoration)\n if (!flags.json && !flags.quiet) {\n const details: Array<{ label: string; value: string }> = [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n ];\n if (options.db) {\n details.push({ label: 'database', value: maskConnectionUrl(options.db) });\n }\n if (options.dryRun) {\n details.push({ label: 'mode', value: 'dry run' });\n }\n const header = formatStyledHeader({\n command: descriptor.commandName,\n description: descriptor.description,\n url: descriptor.url,\n details,\n flags,\n });\n ui.stderr(header);\n }\n\n // Load contract file\n let contractJsonContent: string;\n try {\n contractJsonContent = await readFile(contractPathAbsolute, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return notOk(\n errorFileNotFound(contractPathAbsolute, {\n why: `Contract file not found at ${contractPathAbsolute}`,\n fix: `Run \\`prisma-next contract emit\\` to generate ${contractPath}, or update \\`config.contract.output\\` in ${configPath}`,\n }),\n );\n }\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to read contract file: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n // Parse contract JSON\n let contractJson: Record<string, unknown>;\n try {\n contractJson = JSON.parse(contractJsonContent) as Record<string, unknown>;\n } catch (error) {\n return notOk(\n errorContractValidationFailed(\n `Contract JSON is invalid: ${error instanceof Error ? error.message : String(error)}`,\n { where: { path: contractPathAbsolute } },\n ),\n );\n }\n\n // Resolve database connection (--db flag or config.db.connection)\n const dbConnection = options.db ?? config.db?.connection;\n if (!dbConnection) {\n return notOk(\n errorDatabaseConnectionRequired({\n why: `Database connection is required for ${descriptor.commandName} (set db.connection in ${configPath}, or pass --db <url>)`,\n commandName: descriptor.commandName,\n }),\n );\n }\n\n // Check for driver\n if (!config.driver) {\n return notOk(\n errorDriverRequired({ why: `Config.driver is required for ${descriptor.commandName}` }),\n );\n }\n\n if (!hasMigrations(config.target)) {\n return notOk(\n errorTargetMigrationNotSupported({\n why: `Target \"${config.target.id}\" does not support migrations`,\n }),\n );\n }\n\n // Create control client\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n driver: config.driver,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ ui, flags });\n\n return ok({\n client,\n contractJson,\n dbConnection,\n onProgress,\n configPath,\n contractPath,\n contractPathAbsolute,\n config,\n });\n}\n\n/**\n * Registers the shared CLI options for migration commands (db init, db update).\n */\nexport function addMigrationCommandOptions(command: Command): Command {\n addGlobalOptions(command);\n return command\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option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;EACd,OAAO,MACL,8BACE,6BAA6B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAClF,EAAE,OAAO,EAAE,MAAM,qBAAqB,EAAE,CAC1C,CACF;CACF;CAGA,MAAM,eAAe,QAAQ,MAAM,OAAO,IAAI;CAC9C,IAAI,CAAC,cACH,OAAO,MACL,gCAAgC;EAC9B,KAAK,uCAAuC,WAAW,YAAY,yBAAyB,WAAW;EACvG,aAAa,WAAW;CAC1B,CAAC,CACH;CAIF,IAAI,CAAC,OAAO,QACV,OAAO,MACL,oBAAoB,EAAE,KAAK,iCAAiC,WAAW,cAAc,CAAC,CACxF;CAGF,IAAI,CAAC,cAAc,OAAO,MAAM,GAC9B,OAAO,MACL,iCAAiC,EAC/B,KAAK,WAAW,OAAO,OAAO,GAAG,+BACnC,CAAC,CACH;CAIF,MAAM,SAAS,oBAAoB;EACjC,QAAQ,OAAO;EACf,QAAQ,OAAO;EACf,SAAS,OAAO;EAChB,QAAQ,OAAO;EACf,gBAAgB,OAAO,kBAAkB,CAAC;CAC5C,CAAC;CAGD,MAAM,aAAa,sBAAsB;EAAE;EAAI;CAAM,CAAC;CAEtD,OAAO,GAAG;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH;;;;AAKA,SAAgB,2BAA2B,SAA2B;CACpE,iBAAiB,OAAO;CACxB,OAAO,QACJ,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,aAAa,+CAA+C,KAAK;AAC7E"}
@@ -0,0 +1,288 @@
1
+ import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
+ import { O as errorUnexpected, T as errorSpaceNotFound, f as errorInvalidSpaceId, k as mapMigrationToolsError } from "./cli-errors-DFF1LlfU.mjs";
3
+ import { D as formatStyledHeader, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, p as setCommandSeeAlso, t as addGlobalOptions, v as parseGlobalFlagsOrExit, x as handleResult, y as createTerminalUI } from "./command-helpers-BnqwTptC.mjs";
4
+ import { Command } from "commander";
5
+ import { ifDefined } from "@prisma-next/utils/defined";
6
+ import { notOk, ok } from "@prisma-next/utils/result";
7
+ import { APP_SPACE_ID, isValidSpaceId } from "@prisma-next/migration-tools/spaces";
8
+ import { bold, cyan, cyanBright, dim, green, greenBright, yellow } from "colorette";
9
+ import { MigrationToolsError } from "@prisma-next/migration-tools/errors";
10
+ import { enumerateMigrationSpaces } from "@prisma-next/migration-tools/enumerate-migration-spaces";
11
+ //#region src/utils/formatters/migration-list-render.ts
12
+ const HASH_WIDTH = 7;
13
+ const EMPTY_SOURCE = "∅";
14
+ const SELF_EDGE_GLYPH = "⟲";
15
+ const FORWARD_EDGE_GLYPH = "→";
16
+ const DECORATION_PREFIX = " ";
17
+ const IDENTITY_MIGRATION_LIST_STYLER = {
18
+ dirName: (text) => text,
19
+ sourceHash: (text) => text,
20
+ destHash: (text) => text,
21
+ glyph: (text) => text,
22
+ invariants: (ids) => `{${ids.join(", ")}}`,
23
+ refs: (names) => `(${names.join(", ")})`,
24
+ spaceHeading: (text) => text,
25
+ summary: (text) => text,
26
+ emptyState: (text) => text
27
+ };
28
+ function abbreviateContractHash(hash) {
29
+ return (hash.startsWith("sha256:") ? hash.slice(7) : hash).slice(0, HASH_WIDTH);
30
+ }
31
+ function formatSourceColumn(from, style) {
32
+ if (from === null) return style.glyph(EMPTY_SOURCE) + " ".repeat(HASH_WIDTH - 1);
33
+ return style.sourceHash(abbreviateContractHash(from));
34
+ }
35
+ function formatDestColumn(from, to, style) {
36
+ if (from !== null && from === to) return " ".repeat(HASH_WIDTH);
37
+ return style.destHash(abbreviateContractHash(to));
38
+ }
39
+ function formatArrowGlyph(from, to, style) {
40
+ return style.glyph(from !== null && from === to ? SELF_EDGE_GLYPH : FORWARD_EDGE_GLYPH);
41
+ }
42
+ function formatDecorations(providedInvariants, refs, style) {
43
+ const blocks = [];
44
+ if (providedInvariants.length > 0) blocks.push(style.invariants(providedInvariants));
45
+ if (refs.length > 0) blocks.push(style.refs(refs));
46
+ if (blocks.length === 0) return "";
47
+ return `${DECORATION_PREFIX}${blocks.join(" ")}`;
48
+ }
49
+ function formatMigrationRow(migration, dirNameWidth, style) {
50
+ const dirNamePadding = " ".repeat(Math.max(0, dirNameWidth - migration.dirName.length));
51
+ return `${`${style.dirName(migration.dirName)}${dirNamePadding}`}${formatSourceColumn(migration.from, style)} ${formatArrowGlyph(migration.from, migration.to, style)} ${formatDestColumn(migration.from, migration.to, style)}${formatDecorations(migration.providedInvariants, migration.refs, style)}`;
52
+ }
53
+ function formatEmptyStateLine(spaceId, style) {
54
+ return style.emptyState(`There are no migrations in migrations/${spaceId}/ yet`);
55
+ }
56
+ function renderSpaceBlock(spaceId, migrations, multiSpace, style) {
57
+ if (migrations.length === 0) {
58
+ const emptyLine = formatEmptyStateLine(spaceId, style);
59
+ if (!multiSpace) return [emptyLine];
60
+ return [style.spaceHeading(`${spaceId}:`), ` ${emptyLine}`];
61
+ }
62
+ const dirNameWidth = Math.max(...migrations.map((entry) => entry.dirName.length)) + 2;
63
+ const rows = migrations.map((entry) => formatMigrationRow(entry, dirNameWidth, style));
64
+ if (!multiSpace) return rows;
65
+ return [style.spaceHeading(`${spaceId}:`), ...rows.map((row) => ` ${row}`)];
66
+ }
67
+ /**
68
+ * Compose the styled `migration list` output. The renderer is
69
+ * presentation-neutral — every token passes through `style` before
70
+ * landing in the output, so the same composition serves the pure-text
71
+ * path ({@link renderMigrationList} via
72
+ * {@link IDENTITY_MIGRATION_LIST_STYLER}) and the ANSI-styled CLI path
73
+ * (via the ANSI styler the CLI shell wires up).
74
+ */
75
+ function renderMigrationListWithStyle(result, style) {
76
+ const multiSpace = result.spaces.length > 1;
77
+ const lines = [];
78
+ for (let index = 0; index < result.spaces.length; index++) {
79
+ const space = result.spaces[index];
80
+ if (index > 0) lines.push("");
81
+ lines.push(...renderSpaceBlock(space.spaceId, space.migrations, multiSpace, style));
82
+ }
83
+ if (result.spaces.reduce((count, space) => count + space.migrations.length, 0) > 0) {
84
+ lines.push("");
85
+ lines.push(style.summary(result.summary));
86
+ }
87
+ return lines.join("\n");
88
+ }
89
+ //#endregion
90
+ //#region src/utils/formatters/migration-list-styler.ts
91
+ /**
92
+ * The reserved ref name for the live-database marker. Treated as a
93
+ * structurally distinct token from user-named refs so the styler can
94
+ * make it visually pop in `(refs)` decorations.
95
+ */
96
+ const DB_REF_NAME = "db";
97
+ function styleRefName(name) {
98
+ return name === DB_REF_NAME ? bold(greenBright(name)) : green(name);
99
+ }
100
+ /**
101
+ * Build a {@link MigrationListStyler} that decorates `migration list`
102
+ * tokens with ANSI SGR codes. When `useColor` is `false` (non-TTY,
103
+ * `--no-color`, `NO_COLOR=1`, piped output) the function returns the
104
+ * shared identity styler so callers get plain text with zero ANSI
105
+ * bytes — pipe-friendly by construction.
106
+ *
107
+ * Palette:
108
+ *
109
+ * - `dirName`: bold
110
+ * - `sourceHash`: dim cyan
111
+ * - `destHash`: bright cyan
112
+ * - `glyph` (`→` / `⟲` / `∅`): dim
113
+ * - `invariants` (`{...}`): yellow
114
+ * - `refs` (`(...)`): green; the live-DB `db` marker inside is green-bold
115
+ * - `spaceHeading` (`<spaceId>:`): bold
116
+ * - `summary`: dim
117
+ * - `emptyState`: dim
118
+ */
119
+ function createAnsiMigrationListStyler(opts) {
120
+ if (!opts.useColor) return IDENTITY_MIGRATION_LIST_STYLER;
121
+ return {
122
+ dirName: (text) => bold(text),
123
+ sourceHash: (text) => dim(cyan(text)),
124
+ destHash: (text) => cyanBright(text),
125
+ glyph: (text) => dim(text),
126
+ invariants: (ids) => yellow(`{${ids.join(", ")}}`),
127
+ refs: (names) => {
128
+ const open = green("(");
129
+ const close = green(")");
130
+ const separator = green(", ");
131
+ return open + names.map(styleRefName).join(separator) + close;
132
+ },
133
+ spaceHeading: (text) => bold(text),
134
+ summary: (text) => dim(text),
135
+ emptyState: (text) => dim(text)
136
+ };
137
+ }
138
+ //#endregion
139
+ //#region src/commands/migration-list.ts
140
+ /**
141
+ * Compute the trailing one-line summary appended below the migration
142
+ * rows. Wording follows the existing CLI's pluralization style ("N
143
+ * migration(s) on disk" for the common single-space path; multi-space
144
+ * adds "across K contract space(s)" so consumers can see the spread).
145
+ *
146
+ * The renderer suppresses the summary line when `totalMigrations === 0`
147
+ * — the empty-state line carries enough information on its own — so
148
+ * this function always returns a string even for the empty-state.
149
+ */
150
+ function computeSummary(spaces) {
151
+ const totalMigrations = spaces.reduce((count, space) => count + space.migrations.length, 0);
152
+ if (spaces.length <= 1) return `${totalMigrations} migration(s) on disk`;
153
+ return `${totalMigrations} migration(s) across ${spaces.length} contract space(s)`;
154
+ }
155
+ /**
156
+ * The unit-testable core of `migration list`. Given an absolute
157
+ * `migrationsDir` and an optional `spaceFilter`, enumerates every
158
+ * on-disk migration (via {@link enumerateMigrationSpaces}), narrows to
159
+ * the requested space if any, and assembles a {@link MigrationListResult}
160
+ * ready for the renderer or JSON serializer.
161
+ *
162
+ * The enumerator is the single source of truth for "what is a contract
163
+ * space": existence, the `--space` candidate-suggestion list, and
164
+ * scoping are all derived from one {@link enumerateMigrationSpaces}
165
+ * traversal. This means the reserved-name exclusion the enumerator
166
+ * applies (e.g. the per-space `refs/` subdirectory) is honoured here for
167
+ * free — a `--space refs` request resolves to `SPACE_NOT_FOUND`, not a
168
+ * synthesized empty-state.
169
+ *
170
+ * Distinct empty-state paths:
171
+ *
172
+ * - `migrations/` missing or contains no valid space directories →
173
+ * synthesizes `[{ spaceId: APP_SPACE_ID, migrations: [] }]` so the
174
+ * renderer's empty-state path can name a directory (spec § Empty-state +
175
+ * the `migrations/` missing edge case).
176
+ * - `--space <id>` on an existing-but-empty space dir → the enumerator
177
+ * surfaces `{ spaceId, migrations: [] }`; `<id>` is in the set, so it
178
+ * scopes to that entry and renders the empty-state the same way.
179
+ * - `--space <id>` on a non-existent (or reserved) space → structured
180
+ * `MIGRATION.SPACE_NOT_FOUND` error (NOT empty-state).
181
+ *
182
+ * Errors caught here:
183
+ *
184
+ * - {@link MigrationToolsError} from the enumerator → mapped through
185
+ * {@link mapMigrationToolsError} so callers see the catalogue code.
186
+ * - Anything else (filesystem etc.) → wrapped via {@link errorUnexpected}.
187
+ */
188
+ async function runMigrationList(inputs) {
189
+ const { migrationsDir, spaceFilter } = inputs;
190
+ if (spaceFilter !== void 0 && !isValidSpaceId(spaceFilter)) return notOk(errorInvalidSpaceId(spaceFilter));
191
+ let spaces;
192
+ try {
193
+ spaces = await enumerateMigrationSpaces({ projectMigrationsDir: migrationsDir });
194
+ } catch (error) {
195
+ if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));
196
+ return notOk(errorUnexpected(error instanceof Error ? error.message : String(error), { why: `Failed to enumerate migrations: ${error instanceof Error ? error.message : String(error)}` }));
197
+ }
198
+ if (spaceFilter !== void 0 && !spaces.some((s) => s.spaceId === spaceFilter)) return notOk(errorSpaceNotFound(spaceFilter, spaces.map((s) => s.spaceId).sort()));
199
+ const scopedSpaces = spaceFilter !== void 0 ? spaces.filter((s) => s.spaceId === spaceFilter) : spaces;
200
+ const resultSpaces = scopedSpaces.length === 0 ? [{
201
+ spaceId: APP_SPACE_ID,
202
+ migrations: []
203
+ }] : scopedSpaces;
204
+ return ok({
205
+ ok: true,
206
+ spaces: resultSpaces,
207
+ summary: computeSummary(resultSpaces)
208
+ });
209
+ }
210
+ /**
211
+ * CLI shell: loads config, resolves paths, prints the styled header on
212
+ * stderr (interactive mode only), and delegates to {@link runMigrationList}.
213
+ * Kept intentionally thin so the unit-testable surface lives in the core.
214
+ */
215
+ async function executeMigrationListCommand(options, flags, ui) {
216
+ const config = await loadConfig(options.config);
217
+ const { configPath, migrationsDir, migrationsRelative } = resolveMigrationPaths(options.config, config);
218
+ if (!flags.json && !flags.quiet) {
219
+ const header = formatStyledHeader({
220
+ command: "migration list",
221
+ description: "List on-disk migrations, latest first, per contract space",
222
+ details: [
223
+ {
224
+ label: "config",
225
+ value: configPath
226
+ },
227
+ {
228
+ label: "migrations",
229
+ value: migrationsRelative
230
+ },
231
+ ...options.space !== void 0 ? [{
232
+ label: "space",
233
+ value: options.space
234
+ }] : []
235
+ ],
236
+ flags
237
+ });
238
+ ui.stderr(header);
239
+ }
240
+ return runMigrationList({
241
+ migrationsDir,
242
+ ...ifDefined("spaceFilter", options.space)
243
+ });
244
+ }
245
+ function createMigrationListCommand() {
246
+ const command = new Command("list");
247
+ setCommandDescriptions(command, "List on-disk migrations, latest first, per contract space", "Enumerates every on-disk migration under migrations/<space>/ for every\ncontract space found on disk, latest first. Offline — does not consult\nthe database. Each row shows source → destination contract hashes\n(7-char git-style), the self-edge marker (⟲), any provided invariants\n({...}), and refs landing on the destination ((production, db)). Pass\n--space <id> to narrow to a single contract space.");
248
+ setCommandExamples(command, [
249
+ "prisma-next migration list",
250
+ "prisma-next migration list --space app",
251
+ "prisma-next migration list --json"
252
+ ]);
253
+ setCommandSeeAlso(command, [
254
+ {
255
+ verb: "migration status",
256
+ oneLiner: "Show migration path and pending status"
257
+ },
258
+ {
259
+ verb: "migration log",
260
+ oneLiner: "Show executed migration history"
261
+ },
262
+ {
263
+ verb: "migration graph",
264
+ oneLiner: "Show the migration graph topology"
265
+ },
266
+ {
267
+ verb: "migration show",
268
+ oneLiner: "Display migration package contents"
269
+ }
270
+ ]);
271
+ addGlobalOptions(command).option("--config <path>", "Path to prisma-next.config.ts").option("--space <id>", "Narrow output to a single contract space").action(async (options) => {
272
+ const flags = parseGlobalFlagsOrExit(options);
273
+ const ui = createTerminalUI(flags);
274
+ const exitCode = handleResult(await executeMigrationListCommand(options, flags, ui), flags, ui, (listResult) => {
275
+ if (flags.json) ui.output(JSON.stringify(listResult, null, 2));
276
+ else if (!flags.quiet) {
277
+ const styler = createAnsiMigrationListStyler({ useColor: ui.useColor });
278
+ ui.output(renderMigrationListWithStyle(listResult, styler));
279
+ }
280
+ });
281
+ process.exit(exitCode);
282
+ });
283
+ return command;
284
+ }
285
+ //#endregion
286
+ export { runMigrationList as n, createMigrationListCommand as t };
287
+
288
+ //# sourceMappingURL=migration-list-CnYiHrNV.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-list-CnYiHrNV.mjs","names":[],"sources":["../src/utils/formatters/migration-list-render.ts","../src/utils/formatters/migration-list-styler.ts","../src/commands/migration-list.ts"],"sourcesContent":["import type {\n MigrationListEntry,\n MigrationListResult,\n} from '@prisma-next/migration-tools/migration-list-types';\n\nexport type {\n MigrationListEntry,\n MigrationListResult,\n MigrationSpaceListEntry,\n} from '@prisma-next/migration-tools/migration-list-types';\n\nconst HASH_WIDTH = 7;\nconst EMPTY_SOURCE = '∅';\nconst SELF_EDGE_GLYPH = '⟲';\nconst FORWARD_EDGE_GLYPH = '→';\nconst DECORATION_PREFIX = ' ';\n\n/**\n * Semantic styler for `migration list` output tokens. Token-typed so\n * the renderer composes presentation-neutral fragments and the styler\n * decides how each token kind is decorated (ANSI codes, plain text,\n * etc.). The renderer pads with raw spaces *outside* styled tokens so\n * visible column widths stay stable regardless of what the styler\n * emits — adding ANSI escape sequences never disturbs alignment.\n *\n * `invariants` and `refs` receive the underlying string arrays rather\n * than a pre-joined string so per-element styling (e.g. distinguishing\n * the live-DB `db` marker from user-named refs) is possible without\n * having to re-parse a joined block.\n */\nexport interface MigrationListStyler {\n dirName(text: string): string;\n sourceHash(text: string): string;\n destHash(text: string): string;\n glyph(text: string): string;\n invariants(ids: readonly string[]): string;\n refs(names: readonly string[]): string;\n spaceHeading(text: string): string;\n summary(text: string): string;\n emptyState(text: string): string;\n}\n\nexport const IDENTITY_MIGRATION_LIST_STYLER: MigrationListStyler = {\n dirName: (text) => text,\n sourceHash: (text) => text,\n destHash: (text) => text,\n glyph: (text) => text,\n invariants: (ids) => `{${ids.join(', ')}}`,\n refs: (names) => `(${names.join(', ')})`,\n spaceHeading: (text) => text,\n summary: (text) => text,\n emptyState: (text) => text,\n};\n\nfunction abbreviateContractHash(hash: string): string {\n const stripped = hash.startsWith('sha256:') ? hash.slice(7) : hash;\n return stripped.slice(0, HASH_WIDTH);\n}\n\nfunction formatSourceColumn(from: string | null, style: MigrationListStyler): string {\n if (from === null) {\n return style.glyph(EMPTY_SOURCE) + ' '.repeat(HASH_WIDTH - EMPTY_SOURCE.length);\n }\n return style.sourceHash(abbreviateContractHash(from));\n}\n\nfunction formatDestColumn(from: string | null, to: string, style: MigrationListStyler): string {\n if (from !== null && from === to) {\n return ' '.repeat(HASH_WIDTH);\n }\n return style.destHash(abbreviateContractHash(to));\n}\n\nfunction formatArrowGlyph(from: string | null, to: string, style: MigrationListStyler): string {\n return style.glyph(from !== null && from === to ? SELF_EDGE_GLYPH : FORWARD_EDGE_GLYPH);\n}\n\nfunction formatDecorations(\n providedInvariants: readonly string[],\n refs: readonly string[],\n style: MigrationListStyler,\n): string {\n const blocks: string[] = [];\n if (providedInvariants.length > 0) {\n blocks.push(style.invariants(providedInvariants));\n }\n if (refs.length > 0) {\n blocks.push(style.refs(refs));\n }\n if (blocks.length === 0) return '';\n return `${DECORATION_PREFIX}${blocks.join(' ')}`;\n}\n\nfunction formatMigrationRow(\n migration: MigrationListEntry,\n dirNameWidth: number,\n style: MigrationListStyler,\n): string {\n const dirNamePadding = ' '.repeat(Math.max(0, dirNameWidth - migration.dirName.length));\n const dirName = `${style.dirName(migration.dirName)}${dirNamePadding}`;\n const source = formatSourceColumn(migration.from, style);\n const arrow = formatArrowGlyph(migration.from, migration.to, style);\n const dest = formatDestColumn(migration.from, migration.to, style);\n const decorations = formatDecorations(migration.providedInvariants, migration.refs, style);\n return `${dirName}${source} ${arrow} ${dest}${decorations}`;\n}\n\nfunction formatEmptyStateLine(spaceId: string, style: MigrationListStyler): string {\n return style.emptyState(`There are no migrations in migrations/${spaceId}/ yet`);\n}\n\nfunction renderSpaceBlock(\n spaceId: string,\n migrations: readonly MigrationListEntry[],\n multiSpace: boolean,\n style: MigrationListStyler,\n): readonly string[] {\n if (migrations.length === 0) {\n const emptyLine = formatEmptyStateLine(spaceId, style);\n if (!multiSpace) {\n return [emptyLine];\n }\n return [style.spaceHeading(`${spaceId}:`), ` ${emptyLine}`];\n }\n\n const dirNameWidth = Math.max(...migrations.map((entry) => entry.dirName.length)) + 2;\n const rows = migrations.map((entry) => formatMigrationRow(entry, dirNameWidth, style));\n if (!multiSpace) {\n return rows;\n }\n return [style.spaceHeading(`${spaceId}:`), ...rows.map((row) => ` ${row}`)];\n}\n\n/**\n * Compose the styled `migration list` output. The renderer is\n * presentation-neutral — every token passes through `style` before\n * landing in the output, so the same composition serves the pure-text\n * path ({@link renderMigrationList} via\n * {@link IDENTITY_MIGRATION_LIST_STYLER}) and the ANSI-styled CLI path\n * (via the ANSI styler the CLI shell wires up).\n */\nexport function renderMigrationListWithStyle(\n result: MigrationListResult,\n style: MigrationListStyler,\n): string {\n const multiSpace = result.spaces.length > 1;\n const lines: string[] = [];\n\n for (let index = 0; index < result.spaces.length; index++) {\n const space = result.spaces[index]!;\n if (index > 0) {\n lines.push('');\n }\n lines.push(...renderSpaceBlock(space.spaceId, space.migrations, multiSpace, style));\n }\n\n const totalMigrations = result.spaces.reduce(\n (count, space) => count + space.migrations.length,\n 0,\n );\n if (totalMigrations > 0) {\n lines.push('');\n lines.push(style.summary(result.summary));\n }\n\n return lines.join('\\n');\n}\n\nexport function renderMigrationList(result: MigrationListResult): string {\n return renderMigrationListWithStyle(result, IDENTITY_MIGRATION_LIST_STYLER);\n}\n","import { bold, cyan, cyanBright, dim, green, greenBright, yellow } from 'colorette';\nimport { IDENTITY_MIGRATION_LIST_STYLER, type MigrationListStyler } from './migration-list-render';\n\n/**\n * The reserved ref name for the live-database marker. Treated as a\n * structurally distinct token from user-named refs so the styler can\n * make it visually pop in `(refs)` decorations.\n */\nconst DB_REF_NAME = 'db';\n\nfunction styleRefName(name: string): string {\n return name === DB_REF_NAME ? bold(greenBright(name)) : green(name);\n}\n\n/**\n * Build a {@link MigrationListStyler} that decorates `migration list`\n * tokens with ANSI SGR codes. When `useColor` is `false` (non-TTY,\n * `--no-color`, `NO_COLOR=1`, piped output) the function returns the\n * shared identity styler so callers get plain text with zero ANSI\n * bytes — pipe-friendly by construction.\n *\n * Palette:\n *\n * - `dirName`: bold\n * - `sourceHash`: dim cyan\n * - `destHash`: bright cyan\n * - `glyph` (`→` / `⟲` / `∅`): dim\n * - `invariants` (`{...}`): yellow\n * - `refs` (`(...)`): green; the live-DB `db` marker inside is green-bold\n * - `spaceHeading` (`<spaceId>:`): bold\n * - `summary`: dim\n * - `emptyState`: dim\n */\nexport function createAnsiMigrationListStyler(opts: {\n readonly useColor: boolean;\n}): MigrationListStyler {\n if (!opts.useColor) {\n return IDENTITY_MIGRATION_LIST_STYLER;\n }\n return {\n dirName: (text) => bold(text),\n sourceHash: (text) => dim(cyan(text)),\n destHash: (text) => cyanBright(text),\n glyph: (text) => dim(text),\n invariants: (ids) => yellow(`{${ids.join(', ')}}`),\n refs: (names) => {\n const open = green('(');\n const close = green(')');\n const separator = green(', ');\n return open + names.map(styleRefName).join(separator) + close;\n },\n spaceHeading: (text) => bold(text),\n summary: (text) => dim(text),\n emptyState: (text) => dim(text),\n };\n}\n","import { enumerateMigrationSpaces } from '@prisma-next/migration-tools/enumerate-migration-spaces';\nimport { MigrationToolsError } from '@prisma-next/migration-tools/errors';\nimport type {\n MigrationListResult,\n MigrationSpaceListEntry,\n} from '@prisma-next/migration-tools/migration-list-types';\nimport { APP_SPACE_ID, isValidSpaceId } from '@prisma-next/migration-tools/spaces';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { loadConfig } from '../config-loader';\nimport {\n type CliStructuredError,\n errorInvalidSpaceId,\n errorSpaceNotFound,\n errorUnexpected,\n mapMigrationToolsError,\n} from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n resolveMigrationPaths,\n setCommandDescriptions,\n setCommandExamples,\n setCommandSeeAlso,\n} from '../utils/command-helpers';\nimport { renderMigrationListWithStyle } from '../utils/formatters/migration-list-render';\nimport { createAnsiMigrationListStyler } from '../utils/formatters/migration-list-styler';\nimport { formatStyledHeader } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface MigrationListOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly space?: string;\n}\n\n/**\n * Inputs for {@link runMigrationList} — the pure-ish data-and-policy core\n * of `migration list` that tests exercise directly.\n *\n * The core depends only on the filesystem rooted at `migrationsDir`. It\n * does NOT call `loadConfig`, parse CLI flags, render a styled header,\n * or write to any stream. Output rendering is the caller's concern (the\n * CLI shell renders via {@link renderMigrationList}; JSON callers\n * serialize the {@link MigrationListResult} directly).\n */\nexport interface RunMigrationListInputs {\n /** Absolute path to the project's `migrations/` directory. */\n readonly migrationsDir: string;\n /**\n * Optional contract-space id to narrow the result to a single space.\n * Same validation rules as {@link isValidSpaceId}. When absent, every\n * on-disk space contributes.\n */\n readonly spaceFilter?: string;\n}\n\n/**\n * Compute the trailing one-line summary appended below the migration\n * rows. Wording follows the existing CLI's pluralization style (\"N\n * migration(s) on disk\" for the common single-space path; multi-space\n * adds \"across K contract space(s)\" so consumers can see the spread).\n *\n * The renderer suppresses the summary line when `totalMigrations === 0`\n * — the empty-state line carries enough information on its own — so\n * this function always returns a string even for the empty-state.\n */\nfunction computeSummary(spaces: readonly MigrationSpaceListEntry[]): string {\n const totalMigrations = spaces.reduce((count, space) => count + space.migrations.length, 0);\n if (spaces.length <= 1) {\n return `${totalMigrations} migration(s) on disk`;\n }\n return `${totalMigrations} migration(s) across ${spaces.length} contract space(s)`;\n}\n\n/**\n * The unit-testable core of `migration list`. Given an absolute\n * `migrationsDir` and an optional `spaceFilter`, enumerates every\n * on-disk migration (via {@link enumerateMigrationSpaces}), narrows to\n * the requested space if any, and assembles a {@link MigrationListResult}\n * ready for the renderer or JSON serializer.\n *\n * The enumerator is the single source of truth for \"what is a contract\n * space\": existence, the `--space` candidate-suggestion list, and\n * scoping are all derived from one {@link enumerateMigrationSpaces}\n * traversal. This means the reserved-name exclusion the enumerator\n * applies (e.g. the per-space `refs/` subdirectory) is honoured here for\n * free — a `--space refs` request resolves to `SPACE_NOT_FOUND`, not a\n * synthesized empty-state.\n *\n * Distinct empty-state paths:\n *\n * - `migrations/` missing or contains no valid space directories →\n * synthesizes `[{ spaceId: APP_SPACE_ID, migrations: [] }]` so the\n * renderer's empty-state path can name a directory (spec § Empty-state +\n * the `migrations/` missing edge case).\n * - `--space <id>` on an existing-but-empty space dir → the enumerator\n * surfaces `{ spaceId, migrations: [] }`; `<id>` is in the set, so it\n * scopes to that entry and renders the empty-state the same way.\n * - `--space <id>` on a non-existent (or reserved) space → structured\n * `MIGRATION.SPACE_NOT_FOUND` error (NOT empty-state).\n *\n * Errors caught here:\n *\n * - {@link MigrationToolsError} from the enumerator → mapped through\n * {@link mapMigrationToolsError} so callers see the catalogue code.\n * - Anything else (filesystem etc.) → wrapped via {@link errorUnexpected}.\n */\nexport async function runMigrationList(\n inputs: RunMigrationListInputs,\n): Promise<Result<MigrationListResult, CliStructuredError>> {\n const { migrationsDir, spaceFilter } = inputs;\n\n if (spaceFilter !== undefined && !isValidSpaceId(spaceFilter)) {\n return notOk(errorInvalidSpaceId(spaceFilter));\n }\n\n let spaces: readonly MigrationSpaceListEntry[];\n try {\n spaces = await enumerateMigrationSpaces({ projectMigrationsDir: migrationsDir });\n } catch (error) {\n if (MigrationToolsError.is(error)) return notOk(mapMigrationToolsError(error));\n return notOk(\n errorUnexpected(error instanceof Error ? error.message : String(error), {\n why: `Failed to enumerate migrations: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n\n if (spaceFilter !== undefined && !spaces.some((s) => s.spaceId === spaceFilter)) {\n return notOk(errorSpaceNotFound(spaceFilter, spaces.map((s) => s.spaceId).sort()));\n }\n\n const scopedSpaces =\n spaceFilter !== undefined ? spaces.filter((s) => s.spaceId === spaceFilter) : spaces;\n\n const resultSpaces: readonly MigrationSpaceListEntry[] =\n scopedSpaces.length === 0 ? [{ spaceId: APP_SPACE_ID, migrations: [] }] : scopedSpaces;\n\n return ok({\n ok: true,\n spaces: resultSpaces,\n summary: computeSummary(resultSpaces),\n });\n}\n\n/**\n * CLI shell: loads config, resolves paths, prints the styled header on\n * stderr (interactive mode only), and delegates to {@link runMigrationList}.\n * Kept intentionally thin so the unit-testable surface lives in the core.\n */\nasync function executeMigrationListCommand(\n options: MigrationListOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n): Promise<Result<MigrationListResult, CliStructuredError>> {\n const config = await loadConfig(options.config);\n const { configPath, migrationsDir, migrationsRelative } = resolveMigrationPaths(\n options.config,\n config,\n );\n\n if (!flags.json && !flags.quiet) {\n const header = formatStyledHeader({\n command: 'migration list',\n description: 'List on-disk migrations, latest first, per contract space',\n details: [\n { label: 'config', value: configPath },\n { label: 'migrations', value: migrationsRelative },\n ...(options.space !== undefined ? [{ label: 'space', value: options.space }] : []),\n ],\n flags,\n });\n ui.stderr(header);\n }\n\n return runMigrationList({\n migrationsDir,\n ...ifDefined('spaceFilter', options.space),\n });\n}\n\nexport function createMigrationListCommand(): Command {\n const command = new Command('list');\n setCommandDescriptions(\n command,\n 'List on-disk migrations, latest first, per contract space',\n 'Enumerates every on-disk migration under migrations/<space>/ for every\\n' +\n 'contract space found on disk, latest first. Offline — does not consult\\n' +\n 'the database. Each row shows source → destination contract hashes\\n' +\n '(7-char git-style), the self-edge marker (⟲), any provided invariants\\n' +\n '({...}), and refs landing on the destination ((production, db)). Pass\\n' +\n '--space <id> to narrow to a single contract space.',\n );\n setCommandExamples(command, [\n 'prisma-next migration list',\n 'prisma-next migration list --space app',\n 'prisma-next migration list --json',\n ]);\n setCommandSeeAlso(command, [\n { verb: 'migration status', oneLiner: 'Show migration path and pending status' },\n { verb: 'migration log', oneLiner: 'Show executed migration history' },\n { verb: 'migration graph', oneLiner: 'Show the migration graph topology' },\n { verb: 'migration show', oneLiner: 'Display migration package contents' },\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--space <id>', 'Narrow output to a single contract space')\n .action(async (options: MigrationListOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const result = await executeMigrationListCommand(options, flags, ui);\n const exitCode = handleResult(result, flags, ui, (listResult) => {\n if (flags.json) {\n ui.output(JSON.stringify(listResult, null, 2));\n } else if (!flags.quiet) {\n const styler = createAnsiMigrationListStyler({ useColor: ui.useColor });\n ui.output(renderMigrationListWithStyle(listResult, styler));\n }\n });\n process.exit(exitCode);\n });\n return command;\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AA2B1B,MAAa,iCAAsD;CACjE,UAAU,SAAS;CACnB,aAAa,SAAS;CACtB,WAAW,SAAS;CACpB,QAAQ,SAAS;CACjB,aAAa,QAAQ,IAAI,IAAI,KAAK,IAAI,EAAE;CACxC,OAAO,UAAU,IAAI,MAAM,KAAK,IAAI,EAAE;CACtC,eAAe,SAAS;CACxB,UAAU,SAAS;CACnB,aAAa,SAAS;AACxB;AAEA,SAAS,uBAAuB,MAAsB;CAEpD,QADiB,KAAK,WAAW,SAAS,IAAI,KAAK,MAAM,CAAC,IAAI,MAC9C,MAAM,GAAG,UAAU;AACrC;AAEA,SAAS,mBAAmB,MAAqB,OAAoC;CACnF,IAAI,SAAS,MACX,OAAO,MAAM,MAAM,YAAY,IAAI,IAAI,OAAO,aAAa,CAAmB;CAEhF,OAAO,MAAM,WAAW,uBAAuB,IAAI,CAAC;AACtD;AAEA,SAAS,iBAAiB,MAAqB,IAAY,OAAoC;CAC7F,IAAI,SAAS,QAAQ,SAAS,IAC5B,OAAO,IAAI,OAAO,UAAU;CAE9B,OAAO,MAAM,SAAS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