prisma-next 0.11.0-dev.5 → 0.11.0-dev.50

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 (139) 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 +9 -10
  4. package/dist/cli.mjs.map +1 -1
  5. package/dist/{client-oXO2WCPD.mjs → client-5uvDppD8.mjs} +23 -21
  6. package/dist/client-5uvDppD8.mjs.map +1 -0
  7. package/dist/{command-helpers-DtavI0wJ.mjs → command-helpers-4UNsRRc4.mjs} +427 -9
  8. package/dist/command-helpers-4UNsRRc4.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 +79 -39
  30. package/dist/commands/migrate.mjs.map +1 -1
  31. package/dist/commands/migration-check.d.mts +4 -3
  32. package/dist/commands/migration-check.d.mts.map +1 -1
  33. package/dist/commands/migration-check.mjs +1 -280
  34. package/dist/commands/migration-graph.d.mts +1 -1
  35. package/dist/commands/migration-graph.d.mts.map +1 -1
  36. package/dist/commands/migration-graph.mjs +3 -4
  37. package/dist/commands/migration-graph.mjs.map +1 -1
  38. package/dist/commands/migration-list.d.mts +63 -12
  39. package/dist/commands/migration-list.d.mts.map +1 -1
  40. package/dist/commands/migration-list.mjs +2 -103
  41. package/dist/commands/migration-log.d.mts.map +1 -1
  42. package/dist/commands/migration-log.mjs +3 -4
  43. package/dist/commands/migration-log.mjs.map +1 -1
  44. package/dist/commands/migration-new.d.mts.map +1 -1
  45. package/dist/commands/migration-new.mjs +33 -38
  46. package/dist/commands/migration-new.mjs.map +1 -1
  47. package/dist/commands/migration-plan.d.mts +2 -1
  48. package/dist/commands/migration-plan.d.mts.map +1 -1
  49. package/dist/commands/migration-plan.mjs +1 -1
  50. package/dist/commands/migration-show.d.mts +4 -55
  51. package/dist/commands/migration-show.d.mts.map +1 -1
  52. package/dist/commands/migration-show.mjs +62 -153
  53. package/dist/commands/migration-show.mjs.map +1 -1
  54. package/dist/commands/migration-status.d.mts +5 -40
  55. package/dist/commands/migration-status.d.mts.map +1 -1
  56. package/dist/commands/migration-status.mjs +93 -67
  57. package/dist/commands/migration-status.mjs.map +1 -1
  58. package/dist/commands/ref.d.mts +1 -1
  59. package/dist/commands/ref.d.mts.map +1 -1
  60. package/dist/commands/ref.mjs +34 -9
  61. package/dist/commands/ref.mjs.map +1 -1
  62. package/dist/config-loader-B6sJjXTv.mjs.map +1 -1
  63. package/dist/config-loader.d.mts.map +1 -1
  64. package/dist/{contract-emit-o-8VmdQX.mjs → contract-emit-C-CFGZsI.mjs} +9 -6
  65. package/dist/{contract-emit-o-8VmdQX.mjs.map → contract-emit-C-CFGZsI.mjs.map} +1 -1
  66. package/dist/{contract-emit-CmsklifJ.mjs → contract-emit-CuUzzM46.mjs} +5 -6
  67. package/dist/{contract-emit-CmsklifJ.mjs.map → contract-emit-CuUzzM46.mjs.map} +1 -1
  68. package/dist/{contract-enrichment-Dani0mMW.mjs → contract-enrichment-XmUPhmsS.mjs} +4 -25
  69. package/dist/contract-enrichment-XmUPhmsS.mjs.map +1 -0
  70. package/dist/{contract-infer-pKkiCt7C.mjs → contract-infer-C98ZaRhp.mjs} +3 -4
  71. package/dist/{contract-infer-pKkiCt7C.mjs.map → contract-infer-C98ZaRhp.mjs.map} +1 -1
  72. package/dist/contract-space-aggregate-loader-CVHGuA35.mjs +170 -0
  73. package/dist/contract-space-aggregate-loader-CVHGuA35.mjs.map +1 -0
  74. package/dist/{db-verify-AoIUriL4.mjs → db-verify-BWl1Yxi-.mjs} +6 -7
  75. package/dist/{db-verify-AoIUriL4.mjs.map → db-verify-BWl1Yxi-.mjs.map} +1 -1
  76. package/dist/exports/control-api.d.mts +1 -1
  77. package/dist/exports/control-api.d.mts.map +1 -1
  78. package/dist/exports/control-api.mjs +3 -3
  79. package/dist/exports/index.d.mts.map +1 -1
  80. package/dist/exports/index.mjs +1 -1
  81. package/dist/exports/index.mjs.map +1 -1
  82. package/dist/exports/init-output.d.mts.map +1 -1
  83. package/dist/exports/init-output.mjs +1 -1
  84. package/dist/extension-pack-inputs-BiY86HbQ.mjs +62 -0
  85. package/dist/extension-pack-inputs-BiY86HbQ.mjs.map +1 -0
  86. package/dist/{framework-components-65gOHkHB.mjs → framework-components-DTcjouhS.mjs} +2 -2
  87. package/dist/{framework-components-65gOHkHB.mjs.map → framework-components-DTcjouhS.mjs.map} +1 -1
  88. package/dist/{global-flags-CdE7M0d9.d.mts → global-flags-DWsQ6SSI.d.mts} +1 -1
  89. package/dist/global-flags-DWsQ6SSI.d.mts.map +1 -0
  90. package/dist/glyph-mode-CBB4emzO.d.mts +5 -0
  91. package/dist/glyph-mode-CBB4emzO.d.mts.map +1 -0
  92. package/dist/{graph-render-DJVv0_uf.mjs → graph-render-D2FnLpuK.mjs} +1 -1
  93. package/dist/{graph-render-DJVv0_uf.mjs.map → graph-render-D2FnLpuK.mjs.map} +1 -1
  94. package/dist/{init-Db5Itt5r.mjs → init-C7PvN163.mjs} +5 -5
  95. package/dist/{init-Db5Itt5r.mjs.map → init-C7PvN163.mjs.map} +1 -1
  96. package/dist/{inspect-live-schema-LeWvkZVz.mjs → inspect-live-schema-BRCWQ-Sr.mjs} +5 -5
  97. package/dist/{inspect-live-schema-LeWvkZVz.mjs.map → inspect-live-schema-BRCWQ-Sr.mjs.map} +1 -1
  98. package/dist/migration-check-DoskM1nB.mjs +341 -0
  99. package/dist/migration-check-DoskM1nB.mjs.map +1 -0
  100. package/dist/migration-cli.d.mts.map +1 -1
  101. package/dist/migration-cli.mjs +4 -4
  102. package/dist/migration-cli.mjs.map +1 -1
  103. package/dist/{migration-command-scaffold-BtkunvFQ.mjs → migration-command-scaffold-CXLkoIJx.mjs} +5 -5
  104. package/dist/{migration-command-scaffold-BtkunvFQ.mjs.map → migration-command-scaffold-CXLkoIJx.mjs.map} +1 -1
  105. package/dist/migration-list-B2-iQ5Jd.mjs +646 -0
  106. package/dist/migration-list-B2-iQ5Jd.mjs.map +1 -0
  107. package/dist/{migration-plan-C2jeH1J5.mjs → migration-plan-BqmIKQpZ.mjs} +341 -88
  108. package/dist/migration-plan-BqmIKQpZ.mjs.map +1 -0
  109. package/dist/{migration-types-BXWvz12q.d.mts → migration-types-q64xAI_J.d.mts} +1 -1
  110. package/dist/{migration-types-BXWvz12q.d.mts.map → migration-types-q64xAI_J.d.mts.map} +1 -1
  111. package/dist/{migrations-CwZMa1Ck.mjs → migrations-BcVTutso.mjs} +12 -13
  112. package/dist/migrations-BcVTutso.mjs.map +1 -0
  113. package/dist/{output-BlsrGMEF.mjs → output-B60Gw5fu.mjs} +1 -1
  114. package/dist/{output-BlsrGMEF.mjs.map → output-B60Gw5fu.mjs.map} +1 -1
  115. package/dist/{progress-adapter-DFfvZcYL.mjs → progress-adapter-xASh41wr.mjs} +1 -1
  116. package/dist/{progress-adapter-DFfvZcYL.mjs.map → progress-adapter-xASh41wr.mjs.map} +1 -1
  117. package/dist/ref-advancement-DRh5Nquq.mjs +50 -0
  118. package/dist/ref-advancement-DRh5Nquq.mjs.map +1 -0
  119. package/dist/{types-C9FfXb1l.d.mts → types-CEtm6v6a.d.mts} +5 -11
  120. package/dist/types-CEtm6v6a.d.mts.map +1 -0
  121. package/dist/{verify-Bom75OYI.mjs → verify-DOHbbrub.mjs} +2 -2
  122. package/dist/{verify-Bom75OYI.mjs.map → verify-DOHbbrub.mjs.map} +1 -1
  123. package/package.json +12 -12
  124. package/dist/cli-errors-Czmx92Zy.d.mts +0 -3
  125. package/dist/cli-errors-Djtz98Vm.mjs +0 -71
  126. package/dist/cli-errors-Djtz98Vm.mjs.map +0 -1
  127. package/dist/client-oXO2WCPD.mjs.map +0 -1
  128. package/dist/command-helpers-DtavI0wJ.mjs.map +0 -1
  129. package/dist/commands/migration-check.mjs.map +0 -1
  130. package/dist/commands/migration-list.mjs.map +0 -1
  131. package/dist/contract-enrichment-Dani0mMW.mjs.map +0 -1
  132. package/dist/contract-space-aggregate-loader-BmNQwlws.mjs +0 -160
  133. package/dist/contract-space-aggregate-loader-BmNQwlws.mjs.map +0 -1
  134. package/dist/global-flags-CdE7M0d9.d.mts.map +0 -1
  135. package/dist/migration-plan-C2jeH1J5.mjs.map +0 -1
  136. package/dist/migrations-CwZMa1Ck.mjs.map +0 -1
  137. package/dist/terminal-ui-BiB_8KNo.mjs +0 -379
  138. package/dist/terminal-ui-BiB_8KNo.mjs.map +0 -1
  139. package/dist/types-C9FfXb1l.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"contract-emit-o-8VmdQX.mjs","names":["isRecord"],"sources":["../src/utils/emit-queue.ts","../src/utils/publish-contract-artifact-pair.ts","../src/utils/validate-contract-deps.ts","../src/control-api/operations/contract-emit.ts"],"sourcesContent":["/**\n * Per-output FIFO queue for `executeContractEmit`.\n *\n * Ensures that at most one emit (load → resolve source → emit bytes → publish)\n * runs per output JSON path at a time. Concurrent calls for the same path\n * line up behind the in-flight one and run in submission order; the user-visible\n * outcome is \"last submission wins on disk\" without any supersession bookkeeping.\n *\n * Long-lived hosts (Vite dev server, watch CLIs) must call `disposeEmitQueue`\n * when they stop publishing to a path, otherwise the module-global `Map`\n * accumulates one entry per unique output path for the lifetime of the process.\n */\nconst emitQueues = new Map<string, Promise<unknown>>();\n\nexport function queueEmitByOutput<T>(outputJsonPath: string, action: () => Promise<T>): Promise<T> {\n const previous = emitQueues.get(outputJsonPath) ?? Promise.resolve();\n // Continue regardless of the previous task's outcome — a failed emit must not\n // block subsequent ones. The current task's outcome propagates via `next`.\n const next = previous.then(action, action);\n emitQueues.set(outputJsonPath, next);\n return next;\n}\n\nexport function disposeEmitQueue(outputJsonPath: string): void {\n emitQueues.delete(outputJsonPath);\n}\n","import { readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'pathe';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction createTempArtifactPath(path: string, publicationToken: string, phase: string): string {\n return join(dirname(path), `.${basename(path)}.${process.pid}.${publicationToken}.${phase}.tmp`);\n}\n\ntype PreviousArtifact = { readonly content: string } | 'remove';\n\nasync function readExistingArtifact(path: string): Promise<PreviousArtifact> {\n try {\n return { content: await readFile(path, 'utf-8') };\n } catch (error) {\n if (isRecord(error) && error['code'] === 'ENOENT') {\n return 'remove';\n }\n throw error;\n }\n}\n\nasync function restoreArtifact(\n path: string,\n previous: PreviousArtifact,\n publicationToken: string,\n): Promise<void> {\n if (previous === 'remove') {\n await rm(path, { force: true });\n return;\n }\n\n const restorePath = createTempArtifactPath(path, publicationToken, 'rollback');\n await writeFile(restorePath, previous.content, 'utf-8');\n try {\n await rename(restorePath, path);\n } finally {\n await rm(restorePath, { force: true });\n }\n}\n\ninterface PublishEntry {\n readonly tempPath: string;\n readonly outputPath: string;\n readonly previous: PreviousArtifact;\n}\n\nfunction withRollbackFailureCause(error: unknown, rollbackFailures: readonly unknown[]): Error {\n const rollbackCause = new AggregateError(\n rollbackFailures,\n 'Failed to restore published artifacts',\n );\n\n if (error instanceof Error) {\n Object.defineProperty(error, 'cause', {\n value: rollbackCause,\n configurable: true,\n writable: true,\n });\n return error;\n }\n\n return new Error(String(error), { cause: rollbackCause });\n}\n\nasync function publishPairWithRollback(\n entries: readonly PublishEntry[],\n publicationToken: string,\n): Promise<void> {\n const replaced: PublishEntry[] = [];\n try {\n for (const entry of entries) {\n await rename(entry.tempPath, entry.outputPath);\n replaced.push(entry);\n }\n } catch (error) {\n const rollbackResults = await Promise.allSettled(\n replaced.map((entry) => restoreArtifact(entry.outputPath, entry.previous, publicationToken)),\n );\n const rollbackFailures = rollbackResults.flatMap((result) =>\n result.status === 'rejected' ? [result.reason] : [],\n );\n\n if (rollbackFailures.length > 0) {\n throw withRollbackFailureCause(error, rollbackFailures);\n }\n\n throw error;\n }\n}\n\nexport async function publishContractArtifactPair({\n outputJsonPath,\n outputDtsPath,\n contractJson,\n contractDts,\n publicationToken,\n beforePublish,\n}: {\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n readonly contractJson: string;\n readonly contractDts: string;\n readonly publicationToken: string;\n readonly beforePublish?: () => Promise<boolean> | boolean;\n}): Promise<boolean> {\n const tempJsonPath = createTempArtifactPath(outputJsonPath, publicationToken, 'next');\n const tempDtsPath = createTempArtifactPath(outputDtsPath, publicationToken, 'next');\n\n try {\n await writeFile(tempJsonPath, contractJson, 'utf-8');\n await writeFile(tempDtsPath, contractDts, 'utf-8');\n\n if ((await beforePublish?.()) === false) {\n return false;\n }\n\n const previousJson = await readExistingArtifact(outputJsonPath);\n const previousDts = await readExistingArtifact(outputDtsPath);\n\n await publishPairWithRollback(\n [\n { tempPath: tempDtsPath, outputPath: outputDtsPath, previous: previousDts },\n { tempPath: tempJsonPath, outputPath: outputJsonPath, previous: previousJson },\n ],\n publicationToken,\n );\n return true;\n } finally {\n await Promise.allSettled([rm(tempJsonPath, { force: true }), rm(tempDtsPath, { force: true })]);\n }\n}\n","import { createRequire } from 'node:module';\n\nconst IMPORT_PATTERN = /import\\s+type\\s+.*?\\s+from\\s+['\"](@[^/]+\\/[^/'\"]+)/g;\n\nexport function extractPackageSpecifiers(dtsContent: string): string[] {\n const packages = new Set<string>();\n for (const match of dtsContent.matchAll(IMPORT_PATTERN)) {\n const pkg = match[1];\n if (pkg) packages.add(pkg);\n }\n return [...packages];\n}\n\nexport interface ContractDepsValidation {\n readonly missing: readonly string[];\n readonly warning?: string;\n}\n\nexport function validateContractDeps(\n dtsContent: string,\n projectRoot: string,\n): ContractDepsValidation {\n const packages = extractPackageSpecifiers(dtsContent);\n const resolve = createRequire(`${projectRoot}/package.json`);\n\n const missing: string[] = [];\n for (const pkg of packages) {\n try {\n resolve.resolve(`${pkg}/package.json`);\n } catch {\n missing.push(pkg);\n }\n }\n\n if (missing.length === 0) {\n return { missing };\n }\n\n const list = missing.map((p) => ` - ${p}`).join('\\n');\n const warning = [\n 'contract.d.ts imports types from packages that are not installed:',\n list,\n '',\n 'Install them with your package manager:',\n ...missing.map((p) => ` ${p}`),\n ].join('\\n');\n\n return { missing, warning };\n}\n","import { mkdir } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { emit, getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { abortable } from '@prisma-next/utils/abortable';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from '../../config-loader';\nimport { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';\nimport { queueEmitByOutput } from '../../utils/emit-queue';\nimport { assertFrameworkComponentsCompatible } from '../../utils/framework-components';\nimport { publishContractArtifactPair } from '../../utils/publish-contract-artifact-pair';\nimport { validateContractDeps } from '../../utils/validate-contract-deps';\nimport { enrichContract } from '../contract-enrichment';\nimport type {\n ContractEmitOptions,\n ContractEmitResult,\n ControlActionName,\n OnControlProgress,\n} from '../types';\n\nconst EMIT_ACTION: ControlActionName = 'emit';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction startSpan(onProgress: OnControlProgress | undefined, spanId: string, label: string): void {\n onProgress?.({ action: EMIT_ACTION, kind: 'spanStart', spanId, label });\n}\n\nfunction endSpan(\n onProgress: OnControlProgress | undefined,\n spanId: string,\n outcome: 'ok' | 'error',\n): void {\n onProgress?.({ action: EMIT_ACTION, kind: 'spanEnd', spanId, outcome });\n}\n\nfunction failedToResolveContractSource(why: string, fix: string, meta?: Record<string, unknown>) {\n return errorRuntime('Failed to resolve contract source', {\n why,\n fix,\n ...ifDefined('meta', meta),\n });\n}\n\ntype ValidatedProviderResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: ReturnType<typeof errorRuntime> };\n\nfunction diagnosticLocationSuffix(diagnostic: Record<string, unknown>): string {\n const sourceId = typeof diagnostic['sourceId'] === 'string' ? diagnostic['sourceId'] : undefined;\n const span = isRecord(diagnostic['span']) ? diagnostic['span'] : undefined;\n const start = span && isRecord(span['start']) ? span['start'] : undefined;\n const line = start && typeof start['line'] === 'number' ? start['line'] : undefined;\n const column = start && typeof start['column'] === 'number' ? start['column'] : undefined;\n if (sourceId && line !== undefined && column !== undefined) {\n return ` (${sourceId}:${line}:${column})`;\n }\n if (sourceId) {\n return ` (${sourceId})`;\n }\n return '';\n}\n\nfunction mapDiagnosticsToIssues(\n diagnostics: readonly unknown[],\n): ReadonlyArray<{ readonly kind: string; readonly message: string }> {\n const issues: { readonly kind: string; readonly message: string }[] = [];\n for (const raw of diagnostics) {\n if (!isRecord(raw)) continue;\n const code = typeof raw['code'] === 'string' ? raw['code'] : 'diagnostic';\n const message = typeof raw['message'] === 'string' ? raw['message'] : '';\n issues.push({ kind: code, message: `${message}${diagnosticLocationSuffix(raw)}` });\n }\n return issues;\n}\n\nfunction validateProviderResult(providerResult: unknown): ValidatedProviderResult {\n if (!isRecord(providerResult) || typeof providerResult['ok'] !== 'boolean') {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed result shape.',\n 'Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).',\n ),\n };\n }\n\n if (providerResult['ok']) {\n if (!('value' in providerResult)) {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed success result: missing value.',\n 'Ensure contract.source.load success payload is ok(Contract).',\n ),\n };\n }\n return { ok: true, value: providerResult['value'] };\n }\n\n const failure = providerResult['failure'];\n if (\n !isRecord(failure) ||\n typeof failure['summary'] !== 'string' ||\n !Array.isArray(failure['diagnostics'])\n ) {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed failure result: expected summary and diagnostics.',\n 'Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).',\n ),\n };\n }\n return {\n ok: false,\n error: failedToResolveContractSource(\n String(failure['summary']),\n 'Fix contract source diagnostics and return ok(Contract).',\n {\n diagnostics: failure['diagnostics'],\n issues: mapDiagnosticsToIssues(failure['diagnostics']),\n ...ifDefined('providerMeta', failure['meta']),\n },\n ),\n };\n}\n\n/**\n * Canonical contract emit operation.\n *\n * This is the SINGLE publication path used by both the CLI command\n * (`prisma-next contract emit`) and the Vite plugin\n * (`@prisma-next/vite-plugin-contract-emit`). New callers must go through this\n * function rather than re-implementing load → emit → publish.\n *\n * The whole flow (load config → resolve source → emit bytes → atomic publish)\n * is serialized per output JSON path via `queueEmitByOutput`. Concurrent calls\n * for the same output line up FIFO; the user-visible outcome is \"last\n * submission wins on disk\" without any supersession bookkeeping. Within a\n * single emit, `publishContractArtifactPair` stages temp files, renames\n * `contract.d.ts` before `contract.json`, and attempts to restore the previous\n * pair if either rename fails — so type-only consumers never observe a\n * mismatched pair.\n *\n * @throws {CliStructuredError} on config/source/validation problems\n * @throws {DOMException} `AbortError` if cancelled via `signal`\n */\nexport async function executeContractEmit(\n options: ContractEmitOptions,\n): Promise<ContractEmitResult> {\n const { configPath, outputPath, signal = new AbortController().signal, onProgress } = options;\n const unlessAborted = abortable(signal);\n\n const config = await unlessAborted(loadConfig(configPath));\n\n if (!config.contract) {\n throw errorContractConfigMissing({\n why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n });\n }\n\n const contractConfig = config.contract;\n\n const effectiveOutput =\n outputPath !== undefined ? join(outputPath, 'contract.json') : contractConfig.output;\n\n if (!effectiveOutput) {\n throw errorContractConfigMissing({\n why: 'Contract config must have output path. This should not happen if defineConfig() was used.',\n });\n }\n\n if (typeof contractConfig.source?.load !== 'function') {\n throw errorContractConfigMissing({\n why: 'Contract config must include a valid source provider object',\n });\n }\n\n let outputPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n outputPaths = getEmittedArtifactPaths(effectiveOutput);\n } catch (error) {\n throw errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n });\n }\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;\n\n return queueEmitByOutput(outputJsonPath, async () => {\n const stack = createControlStack(config);\n\n const sourceContext = {\n composedExtensionPacks: stack.extensionPacks.map((p) => p.id),\n scalarTypeDescriptors: stack.scalarTypeDescriptors,\n authoringContributions: stack.authoringContributions,\n codecLookup: stack.codecLookup,\n controlMutationDefaults: stack.controlMutationDefaults,\n resolvedInputs: contractConfig.source.inputs ?? [],\n };\n\n startSpan(onProgress, 'resolveSource', 'Resolving contract source...');\n let providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>;\n try {\n providerResult = await unlessAborted(contractConfig.source.load(sourceContext));\n } catch (error) {\n endSpan(onProgress, 'resolveSource', 'error');\n if (signal.aborted || (isRecord(error) && error['name'] === 'AbortError')) {\n throw error;\n }\n throw failedToResolveContractSource(\n error instanceof Error ? error.message : String(error),\n 'Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.',\n );\n }\n\n const validatedContract = validateProviderResult(providerResult);\n if (!validatedContract.ok) {\n endSpan(onProgress, 'resolveSource', 'error');\n throw validatedContract.error;\n }\n endSpan(onProgress, 'resolveSource', 'ok');\n\n startSpan(onProgress, 'emit', 'Emitting contract...');\n let emitResult: Awaited<ReturnType<typeof emit>>;\n try {\n const familyInstance = config.family.create(stack);\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n // Blind cast: `validateProviderResult` upstream has already\n // pinned `validatedContract.value` to the provider's loose\n // `Contract` envelope, but the local `Contract` type at this\n // call site is the precise structural interface. Re-narrowing\n // the envelope into the precise type is exactly what the\n // `familyInstance.deserializeContract(enrichedIR)` call on the\n // next line does — the cast just defers the structural check\n // by one statement so `enrichContract` can decorate first.\n const enrichedIR = enrichContract(\n validatedContract.value as unknown as Contract,\n frameworkComponents,\n );\n familyInstance.deserializeContract(enrichedIR);\n // Each target's descriptor ships a `contractSerializer` SPI; the\n // framework canonicalizer threads its `serializeContract` so the\n // on-disk JSON envelope is constructed by target-owned code\n // rather than by walking the in-memory contract with\n // `Object.entries` (which would leak runtime-only class API\n // fields into the persisted shape).\n const serializeContract = (c: Contract): JsonObject =>\n config.target.contractSerializer.serializeContract(c);\n emitResult = await unlessAborted(\n emit(enrichedIR, stack, config.family.emission, {\n outputJsonPath,\n serializeContract,\n }),\n );\n } catch (error) {\n endSpan(onProgress, 'emit', 'error');\n throw error;\n }\n endSpan(onProgress, 'emit', 'ok');\n\n await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));\n await publishContractArtifactPair({\n outputJsonPath,\n outputDtsPath,\n contractJson: emitResult.contractJson,\n contractDts: emitResult.contractDts,\n publicationToken: String(process.hrtime.bigint()),\n });\n\n const validationWarning = validateContractDeps(\n emitResult.contractDts,\n dirname(outputDtsPath),\n ).warning;\n\n return {\n storageHash: emitResult.storageHash,\n ...ifDefined('executionHash', emitResult.executionHash),\n profileHash: emitResult.profileHash,\n files: {\n json: output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GAAG,UAAU,qBAAqB,kBAAkB;GACrD;GACD"}
1
+ {"version":3,"file":"contract-emit-C-CFGZsI.mjs","names":["isRecord"],"sources":["../src/utils/emit-queue.ts","../src/utils/publish-contract-artifact-pair.ts","../src/utils/validate-contract-deps.ts","../src/control-api/operations/contract-emit.ts"],"sourcesContent":["/**\n * Per-output FIFO queue for `executeContractEmit`.\n *\n * Ensures that at most one emit (load → resolve source → emit bytes → publish)\n * runs per output JSON path at a time. Concurrent calls for the same path\n * line up behind the in-flight one and run in submission order; the user-visible\n * outcome is \"last submission wins on disk\" without any supersession bookkeeping.\n *\n * Long-lived hosts (Vite dev server, watch CLIs) must call `disposeEmitQueue`\n * when they stop publishing to a path, otherwise the module-global `Map`\n * accumulates one entry per unique output path for the lifetime of the process.\n */\nconst emitQueues = new Map<string, Promise<unknown>>();\n\nexport function queueEmitByOutput<T>(outputJsonPath: string, action: () => Promise<T>): Promise<T> {\n const previous = emitQueues.get(outputJsonPath) ?? Promise.resolve();\n // Continue regardless of the previous task's outcome — a failed emit must not\n // block subsequent ones. The current task's outcome propagates via `next`.\n const next = previous.then(action, action);\n emitQueues.set(outputJsonPath, next);\n return next;\n}\n\nexport function disposeEmitQueue(outputJsonPath: string): void {\n emitQueues.delete(outputJsonPath);\n}\n","import { readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport { basename, dirname, join } from 'pathe';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction createTempArtifactPath(path: string, publicationToken: string, phase: string): string {\n return join(dirname(path), `.${basename(path)}.${process.pid}.${publicationToken}.${phase}.tmp`);\n}\n\ntype PreviousArtifact = { readonly content: string } | 'remove';\n\nasync function readExistingArtifact(path: string): Promise<PreviousArtifact> {\n try {\n return { content: await readFile(path, 'utf-8') };\n } catch (error) {\n if (isRecord(error) && error['code'] === 'ENOENT') {\n return 'remove';\n }\n throw error;\n }\n}\n\nasync function restoreArtifact(\n path: string,\n previous: PreviousArtifact,\n publicationToken: string,\n): Promise<void> {\n if (previous === 'remove') {\n await rm(path, { force: true });\n return;\n }\n\n const restorePath = createTempArtifactPath(path, publicationToken, 'rollback');\n await writeFile(restorePath, previous.content, 'utf-8');\n try {\n await rename(restorePath, path);\n } finally {\n await rm(restorePath, { force: true });\n }\n}\n\ninterface PublishEntry {\n readonly tempPath: string;\n readonly outputPath: string;\n readonly previous: PreviousArtifact;\n}\n\nfunction withRollbackFailureCause(error: unknown, rollbackFailures: readonly unknown[]): Error {\n const rollbackCause = new AggregateError(\n rollbackFailures,\n 'Failed to restore published artifacts',\n );\n\n if (error instanceof Error) {\n Object.defineProperty(error, 'cause', {\n value: rollbackCause,\n configurable: true,\n writable: true,\n });\n return error;\n }\n\n return new Error(String(error), { cause: rollbackCause });\n}\n\nasync function publishPairWithRollback(\n entries: readonly PublishEntry[],\n publicationToken: string,\n): Promise<void> {\n const replaced: PublishEntry[] = [];\n try {\n for (const entry of entries) {\n await rename(entry.tempPath, entry.outputPath);\n replaced.push(entry);\n }\n } catch (error) {\n const rollbackResults = await Promise.allSettled(\n replaced.map((entry) => restoreArtifact(entry.outputPath, entry.previous, publicationToken)),\n );\n const rollbackFailures = rollbackResults.flatMap((result) =>\n result.status === 'rejected' ? [result.reason] : [],\n );\n\n if (rollbackFailures.length > 0) {\n throw withRollbackFailureCause(error, rollbackFailures);\n }\n\n throw error;\n }\n}\n\nexport async function publishContractArtifactPair({\n outputJsonPath,\n outputDtsPath,\n contractJson,\n contractDts,\n publicationToken,\n beforePublish,\n}: {\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n readonly contractJson: string;\n readonly contractDts: string;\n readonly publicationToken: string;\n readonly beforePublish?: () => Promise<boolean> | boolean;\n}): Promise<boolean> {\n const tempJsonPath = createTempArtifactPath(outputJsonPath, publicationToken, 'next');\n const tempDtsPath = createTempArtifactPath(outputDtsPath, publicationToken, 'next');\n\n try {\n await writeFile(tempJsonPath, contractJson, 'utf-8');\n await writeFile(tempDtsPath, contractDts, 'utf-8');\n\n if ((await beforePublish?.()) === false) {\n return false;\n }\n\n const previousJson = await readExistingArtifact(outputJsonPath);\n const previousDts = await readExistingArtifact(outputDtsPath);\n\n await publishPairWithRollback(\n [\n { tempPath: tempDtsPath, outputPath: outputDtsPath, previous: previousDts },\n { tempPath: tempJsonPath, outputPath: outputJsonPath, previous: previousJson },\n ],\n publicationToken,\n );\n return true;\n } finally {\n await Promise.allSettled([rm(tempJsonPath, { force: true }), rm(tempDtsPath, { force: true })]);\n }\n}\n","import { createRequire } from 'node:module';\n\nconst IMPORT_PATTERN = /import\\s+type\\s+.*?\\s+from\\s+['\"](@[^/]+\\/[^/'\"]+)/g;\n\nexport function extractPackageSpecifiers(dtsContent: string): string[] {\n const packages = new Set<string>();\n for (const match of dtsContent.matchAll(IMPORT_PATTERN)) {\n const pkg = match[1];\n if (pkg) packages.add(pkg);\n }\n return [...packages];\n}\n\nexport interface ContractDepsValidation {\n readonly missing: readonly string[];\n readonly warning?: string;\n}\n\nexport function validateContractDeps(\n dtsContent: string,\n projectRoot: string,\n): ContractDepsValidation {\n const packages = extractPackageSpecifiers(dtsContent);\n const resolve = createRequire(`${projectRoot}/package.json`);\n\n const missing: string[] = [];\n for (const pkg of packages) {\n try {\n resolve.resolve(`${pkg}/package.json`);\n } catch {\n missing.push(pkg);\n }\n }\n\n if (missing.length === 0) {\n return { missing };\n }\n\n const list = missing.map((p) => ` - ${p}`).join('\\n');\n const warning = [\n 'contract.d.ts imports types from packages that are not installed:',\n list,\n '',\n 'Install them with your package manager:',\n ...missing.map((p) => ` ${p}`),\n ].join('\\n');\n\n return { missing, warning };\n}\n","import { mkdir } from 'node:fs/promises';\nimport type { Contract } from '@prisma-next/contract/types';\nimport { emit, getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { createControlStack } from '@prisma-next/framework-components/control';\nimport { abortable } from '@prisma-next/utils/abortable';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport type { JsonObject } from '@prisma-next/utils/json';\nimport { dirname, join } from 'pathe';\nimport { loadConfig } from '../../config-loader';\nimport { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';\nimport { queueEmitByOutput } from '../../utils/emit-queue';\nimport { assertFrameworkComponentsCompatible } from '../../utils/framework-components';\nimport { publishContractArtifactPair } from '../../utils/publish-contract-artifact-pair';\nimport { validateContractDeps } from '../../utils/validate-contract-deps';\nimport { enrichContract } from '../contract-enrichment';\nimport type {\n ContractEmitOptions,\n ContractEmitResult,\n ControlActionName,\n OnControlProgress,\n} from '../types';\n\nconst EMIT_ACTION: ControlActionName = 'emit';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction startSpan(onProgress: OnControlProgress | undefined, spanId: string, label: string): void {\n onProgress?.({ action: EMIT_ACTION, kind: 'spanStart', spanId, label });\n}\n\nfunction endSpan(\n onProgress: OnControlProgress | undefined,\n spanId: string,\n outcome: 'ok' | 'error',\n): void {\n onProgress?.({ action: EMIT_ACTION, kind: 'spanEnd', spanId, outcome });\n}\n\nfunction failedToResolveContractSource(why: string, fix: string, meta?: Record<string, unknown>) {\n return errorRuntime('Failed to resolve contract source', {\n why,\n fix,\n ...ifDefined('meta', meta),\n });\n}\n\ntype ValidatedProviderResult =\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; readonly error: ReturnType<typeof errorRuntime> };\n\nfunction diagnosticLocationSuffix(diagnostic: Record<string, unknown>): string {\n const sourceId = typeof diagnostic['sourceId'] === 'string' ? diagnostic['sourceId'] : undefined;\n const span = isRecord(diagnostic['span']) ? diagnostic['span'] : undefined;\n const start = span && isRecord(span['start']) ? span['start'] : undefined;\n const line = start && typeof start['line'] === 'number' ? start['line'] : undefined;\n const column = start && typeof start['column'] === 'number' ? start['column'] : undefined;\n if (sourceId && line !== undefined && column !== undefined) {\n return ` (${sourceId}:${line}:${column})`;\n }\n if (sourceId) {\n return ` (${sourceId})`;\n }\n return '';\n}\n\nfunction mapDiagnosticsToIssues(\n diagnostics: readonly unknown[],\n): ReadonlyArray<{ readonly kind: string; readonly message: string }> {\n const issues: { readonly kind: string; readonly message: string }[] = [];\n for (const raw of diagnostics) {\n if (!isRecord(raw)) continue;\n const code = typeof raw['code'] === 'string' ? raw['code'] : 'diagnostic';\n const message = typeof raw['message'] === 'string' ? raw['message'] : '';\n issues.push({ kind: code, message: `${message}${diagnosticLocationSuffix(raw)}` });\n }\n return issues;\n}\n\nfunction validateProviderResult(providerResult: unknown): ValidatedProviderResult {\n if (!isRecord(providerResult) || typeof providerResult['ok'] !== 'boolean') {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed result shape.',\n 'Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).',\n ),\n };\n }\n\n if (providerResult['ok']) {\n if (!('value' in providerResult)) {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed success result: missing value.',\n 'Ensure contract.source.load success payload is ok(Contract).',\n ),\n };\n }\n return { ok: true, value: providerResult['value'] };\n }\n\n const failure = providerResult['failure'];\n if (\n !isRecord(failure) ||\n typeof failure['summary'] !== 'string' ||\n !Array.isArray(failure['diagnostics'])\n ) {\n return {\n ok: false,\n error: failedToResolveContractSource(\n 'Contract source provider returned malformed failure result: expected summary and diagnostics.',\n 'Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).',\n ),\n };\n }\n return {\n ok: false,\n error: failedToResolveContractSource(\n String(failure['summary']),\n 'Fix contract source diagnostics and return ok(Contract).',\n {\n diagnostics: failure['diagnostics'],\n issues: mapDiagnosticsToIssues(failure['diagnostics']),\n ...ifDefined('providerMeta', failure['meta']),\n },\n ),\n };\n}\n\n/**\n * Canonical contract emit operation.\n *\n * This is the SINGLE publication path used by both the CLI command\n * (`prisma-next contract emit`) and the Vite plugin\n * (`@prisma-next/vite-plugin-contract-emit`). New callers must go through this\n * function rather than re-implementing load → emit → publish.\n *\n * The whole flow (load config → resolve source → emit bytes → atomic publish)\n * is serialized per output JSON path via `queueEmitByOutput`. Concurrent calls\n * for the same output line up FIFO; the user-visible outcome is \"last\n * submission wins on disk\" without any supersession bookkeeping. Within a\n * single emit, `publishContractArtifactPair` stages temp files, renames\n * `contract.d.ts` before `contract.json`, and attempts to restore the previous\n * pair if either rename fails — so type-only consumers never observe a\n * mismatched pair.\n *\n * @throws {CliStructuredError} on config/source/validation problems\n * @throws {DOMException} `AbortError` if cancelled via `signal`\n */\nexport async function executeContractEmit(\n options: ContractEmitOptions,\n): Promise<ContractEmitResult> {\n const { configPath, outputPath, signal = new AbortController().signal, onProgress } = options;\n const unlessAborted = abortable(signal);\n\n const config = await unlessAborted(loadConfig(configPath));\n\n if (!config.contract) {\n throw errorContractConfigMissing({\n why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n });\n }\n\n const contractConfig = config.contract;\n\n const effectiveOutput =\n outputPath !== undefined ? join(outputPath, 'contract.json') : contractConfig.output;\n\n if (!effectiveOutput) {\n throw errorContractConfigMissing({\n why: 'Contract config must have output path. This should not happen if defineConfig() was used.',\n });\n }\n\n if (typeof contractConfig.source?.load !== 'function') {\n throw errorContractConfigMissing({\n why: 'Contract config must include a valid source provider object',\n });\n }\n\n let outputPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n outputPaths = getEmittedArtifactPaths(effectiveOutput);\n } catch (error) {\n throw errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n });\n }\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;\n\n return queueEmitByOutput(outputJsonPath, async () => {\n const stack = createControlStack(config);\n\n const sourceContext = {\n composedExtensionPacks: stack.extensionPacks.map((p) => p.id),\n scalarTypeDescriptors: stack.scalarTypeDescriptors,\n authoringContributions: stack.authoringContributions,\n codecLookup: stack.codecLookup,\n controlMutationDefaults: stack.controlMutationDefaults,\n resolvedInputs: contractConfig.source.inputs ?? [],\n };\n\n startSpan(onProgress, 'resolveSource', 'Resolving contract source...');\n let providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>;\n try {\n providerResult = await unlessAborted(contractConfig.source.load(sourceContext));\n } catch (error) {\n endSpan(onProgress, 'resolveSource', 'error');\n if (signal.aborted || (isRecord(error) && error['name'] === 'AbortError')) {\n throw error;\n }\n throw failedToResolveContractSource(\n error instanceof Error ? error.message : String(error),\n 'Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.',\n );\n }\n\n const validatedContract = validateProviderResult(providerResult);\n if (!validatedContract.ok) {\n endSpan(onProgress, 'resolveSource', 'error');\n throw validatedContract.error;\n }\n endSpan(onProgress, 'resolveSource', 'ok');\n\n startSpan(onProgress, 'emit', 'Emitting contract...');\n let emitResult: Awaited<ReturnType<typeof emit>>;\n try {\n const familyInstance = config.family.create(stack);\n const rawComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n const frameworkComponents = assertFrameworkComponentsCompatible(\n config.family.familyId,\n config.target.targetId,\n rawComponents,\n );\n // Blind cast: `validateProviderResult` upstream has already\n // pinned `validatedContract.value` to the provider's loose\n // `Contract` envelope, but the local `Contract` type at this\n // call site is the precise structural interface. Re-narrowing\n // the envelope into the precise type is exactly what the\n // `familyInstance.deserializeContract(enrichedIR)` call on the\n // next line does — the cast just defers the structural check\n // by one statement so `enrichContract` can decorate first.\n const enrichedIR = enrichContract(\n validatedContract.value as unknown as Contract,\n frameworkComponents,\n );\n familyInstance.deserializeContract(enrichedIR);\n // Each target's descriptor ships a `contractSerializer` SPI; the\n // framework canonicalizer threads its `serializeContract` so the\n // on-disk JSON envelope is constructed by target-owned code\n // rather than by walking the in-memory contract with\n // `Object.entries` (which would leak runtime-only class API\n // fields into the persisted shape). The optional `shouldPreserveEmpty`\n // and `sortStorage` hooks let the family contribute storage-specific\n // canonicalization rules without the framework importing family code.\n const { contractSerializer } = config.target;\n const serializeContract = (c: Contract): JsonObject =>\n contractSerializer.serializeContract(c);\n emitResult = await unlessAborted(\n emit(enrichedIR, stack, config.family.emission, {\n outputJsonPath,\n serializeContract,\n ...ifDefined('shouldPreserveEmpty', contractSerializer.shouldPreserveEmpty),\n ...ifDefined('sortStorage', contractSerializer.sortStorage),\n }),\n );\n } catch (error) {\n endSpan(onProgress, 'emit', 'error');\n throw error;\n }\n endSpan(onProgress, 'emit', 'ok');\n\n await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));\n await publishContractArtifactPair({\n outputJsonPath,\n outputDtsPath,\n contractJson: emitResult.contractJson,\n contractDts: emitResult.contractDts,\n publicationToken: String(process.hrtime.bigint()),\n });\n\n const validationWarning = validateContractDeps(\n emitResult.contractDts,\n dirname(outputDtsPath),\n ).warning;\n\n return {\n storageHash: emitResult.storageHash,\n ...ifDefined('executionHash', emitResult.executionHash),\n profileHash: emitResult.profileHash,\n files: {\n json: outputJsonPath,\n dts: outputDtsPath,\n },\n ...ifDefined('validationWarning', validationWarning),\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAYA,MAAM,6BAAa,IAAI,IAA8B;AAErD,SAAgB,kBAAqB,gBAAwB,QAAsC;CAIjG,MAAM,QAHW,WAAW,IAAI,cAAc,KAAK,QAAQ,QAAQ,GAG7C,KAAK,QAAQ,MAAM;CACzC,WAAW,IAAI,gBAAgB,IAAI;CACnC,OAAO;AACT;AAEA,SAAgB,iBAAiB,gBAA8B;CAC7D,WAAW,OAAO,cAAc;AAClC;;;ACtBA,SAASA,WAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU;AAChD;AAEA,SAAS,uBAAuB,MAAc,kBAA0B,OAAuB;CAC7F,OAAO,KAAK,QAAQ,IAAI,GAAG,IAAI,SAAS,IAAI,EAAE,GAAG,QAAQ,IAAI,GAAG,iBAAiB,GAAG,MAAM,KAAK;AACjG;AAIA,eAAe,qBAAqB,MAAyC;CAC3E,IAAI;EACF,OAAO,EAAE,SAAS,MAAM,SAAS,MAAM,OAAO,EAAE;CAClD,SAAS,OAAO;EACd,IAAIA,WAAS,KAAK,KAAK,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GAS7C,MAAM,EAAE,uBAAuB,OAAO;GACtC,MAAM,qBAAqB,MACzB,mBAAmB,kBAAkB,CAAC;GACxC,aAAa,MAAM,cACjB,KAAK,YAAY,OAAO,OAAO,OAAO,UAAU;IAC9C;IACA;IACA,GAAG,UAAU,uBAAuB,mBAAmB,mBAAmB;IAC1E,GAAG,UAAU,eAAe,mBAAmB,WAAW;GAC5D,CAAC,CACH;EACF,SAAS,OAAO;GACd,QAAQ,YAAY,QAAQ,OAAO;GACnC,MAAM;EACR;EACA,QAAQ,YAAY,QAAQ,IAAI;EAEhC,MAAM,cAAc,MAAM,QAAQ,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC,CAAC;EACvE,MAAM,4BAA4B;GAChC;GACA;GACA,cAAc,WAAW;GACzB,aAAa,WAAW;GACxB,kBAAkB,OAAO,QAAQ,OAAO,OAAO,CAAC;EAClD,CAAC;EAED,MAAM,oBAAoB,qBACxB,WAAW,aACX,QAAQ,aAAa,CACvB,EAAE;EAEF,OAAO;GACL,aAAa,WAAW;GACxB,GAAG,UAAU,iBAAiB,WAAW,aAAa;GACtD,aAAa,WAAW;GACxB,OAAO;IACL,MAAM;IACN,KAAK;GACP;GACA,GAAG,UAAU,qBAAqB,iBAAiB;EACrD;CACF,CAAC;AACH"}
@@ -1,9 +1,8 @@
1
1
  import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
- import { t as CliStructuredError$1, y as errorUnexpected$1 } from "./cli-errors-Djtz98Vm.mjs";
3
- import { n as executeContractEmit } from "./contract-emit-o-8VmdQX.mjs";
4
- import { c as isVerbose, t as createTerminalUI } from "./terminal-ui-BiB_8KNo.mjs";
5
- import { C as formatSuccessMessage, S as formatStyledHeader, d as setCommandDescriptions, f as setCommandExamples, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "./command-helpers-DtavI0wJ.mjs";
6
- import { t as createProgressAdapter } from "./progress-adapter-DFfvZcYL.mjs";
2
+ import { O as errorUnexpected$1, t as CliStructuredError$1 } from "./cli-errors-DFF1LlfU.mjs";
3
+ import { n as executeContractEmit } from "./contract-emit-C-CFGZsI.mjs";
4
+ import { D as formatStyledHeader, O as formatSuccessMessage, d as setCommandDescriptions, f as setCommandExamples, j as isVerbose, t as addGlobalOptions, v as parseGlobalFlagsOrExit, x as handleResult, y as createTerminalUI } from "./command-helpers-4UNsRRc4.mjs";
5
+ import { t as createProgressAdapter } from "./progress-adapter-xASh41wr.mjs";
7
6
  import { Command } from "commander";
8
7
  import { getEmittedArtifactPaths } from "@prisma-next/emitter";
9
8
  import { errorContractConfigMissing } from "@prisma-next/errors/control";
@@ -149,4 +148,4 @@ function createContractEmitCommand() {
149
148
  //#endregion
150
149
  export { createContractEmitCommand as t };
151
150
 
152
- //# sourceMappingURL=contract-emit-CmsklifJ.mjs.map
151
+ //# sourceMappingURL=contract-emit-CuUzzM46.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract-emit-CmsklifJ.mjs","names":["CliStructuredError","errorUnexpected"],"sources":["../src/utils/formatters/emit.ts","../src/commands/contract-emit.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { relative } from 'pathe';\n\nimport type { GlobalFlags } from '../global-flags';\nimport { isVerbose } from './helpers';\n\n// EmitContractResult type for CLI output formatting (includes file paths)\nexport interface EmitContractResult {\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n readonly outDir: string;\n readonly files: {\n readonly json: string;\n readonly dts: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * Formats human-readable output for contract emit.\n */\nexport function formatEmitOutput(result: EmitContractResult, flags: GlobalFlags): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n // Convert absolute paths to relative paths from cwd\n const jsonPath = relative(process.cwd(), result.files.json);\n const dtsPath = relative(process.cwd(), result.files.dts);\n\n lines.push(`✔ Emitted contract.json → ${jsonPath}`);\n lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);\n lines.push(` storageHash: ${result.storageHash}`);\n if (result.executionHash) {\n lines.push(` executionHash: ${result.executionHash}`);\n }\n if (result.profileHash) {\n lines.push(` profileHash: ${result.profileHash}`);\n }\n if (isVerbose(flags, 1)) {\n lines.push(` Total time: ${result.timings.total}ms`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for contract emit.\n */\nexport function formatEmitJson(result: EmitContractResult): string {\n const output = {\n ok: true,\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n ...(result.profileHash ? { profileHash: result.profileHash } : {}),\n outDir: result.outDir,\n files: result.files,\n timings: result.timings,\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { errorContractConfigMissing } from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, join, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { executeContractEmit } from '../control-api/operations/contract-emit';\nimport type { ContractEmitResult } from '../control-api/types';\nimport { CliStructuredError, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n type EmitContractResult,\n formatEmitJson,\n formatEmitOutput,\n} from '../utils/formatters/emit';\nimport { formatStyledHeader, formatSuccessMessage } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface ContractEmitOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly outputPath?: string;\n}\n\ninterface HeaderPaths {\n readonly displayConfigPath: string;\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n}\n\n/**\n * Pre-load the config just to compute display paths for the styled header. The\n * actual emit work goes through `executeContractEmit`, which loads the config\n * itself; the redundant load here is bounded and lets the header render before\n * the emit spans start.\n */\nasync function resolveHeaderPaths(\n configOption: string | undefined,\n outputPath: string | undefined,\n): Promise<Result<HeaderPaths, CliStructuredError>> {\n const displayConfigPath = configOption\n ? relative(process.cwd(), resolve(configOption))\n : 'prisma-next.config.ts';\n\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = await loadConfig(configOption);\n } catch (error) {\n if (error instanceof CliStructuredError) {\n return notOk(error);\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 effectiveJsonPath =\n outputPath !== undefined ? join(outputPath, 'contract.json') : config.contract?.output;\n\n if (!effectiveJsonPath) {\n return notOk(\n errorContractConfigMissing({\n why: 'Config.contract.output is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n }),\n );\n }\n\n try {\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } =\n getEmittedArtifactPaths(effectiveJsonPath);\n return ok({ displayConfigPath, outputJsonPath, outputDtsPath });\n } catch (error) {\n return notOk(\n errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n}\n\nasync function executeContractEmitCommand(\n options: ContractEmitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<EmitContractResult, CliStructuredError>> {\n const outputPath = options.outputPath !== undefined ? resolve(options.outputPath) : undefined;\n\n const headerPathsResult = await resolveHeaderPaths(options.config, outputPath);\n if (!headerPathsResult.ok) {\n return headerPathsResult;\n }\n const { displayConfigPath, outputJsonPath, outputDtsPath } = headerPathsResult.value;\n\n if (!flags.json && !flags.quiet) {\n ui.stderr(\n formatStyledHeader({\n command: 'contract emit',\n description: 'Emit your contract artifacts',\n url: 'https://pris.ly/contract-emit',\n details: [\n { label: 'config', value: displayConfigPath },\n { label: 'contract', value: relative(process.cwd(), outputJsonPath) },\n { label: 'types', value: relative(process.cwd(), outputDtsPath) },\n ],\n flags,\n }),\n );\n }\n\n const onProgress = createProgressAdapter({ ui, flags });\n const configPath = options.config ? resolve(options.config) : 'prisma-next.config.ts';\n\n let result: ContractEmitResult;\n try {\n result = await executeContractEmit({\n configPath,\n onProgress,\n ...ifDefined('outputPath', outputPath),\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected('Unexpected error during contract emit', {\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n\n if (result.validationWarning) {\n ui.warn(result.validationWarning);\n }\n\n return ok({\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n profileHash: result.profileHash,\n outDir: dirname(result.files.json),\n files: result.files,\n timings: { total: Date.now() - startTime },\n });\n}\n\nexport function createContractEmitCommand(): Command {\n const command = new Command('emit');\n setCommandDescriptions(\n command,\n 'Emit your contract artifacts',\n 'Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\\n' +\n 'contract.d.ts. The contract.json contains the canonical contract structure, and\\n' +\n 'contract.d.ts provides TypeScript types for type-safe query building.',\n );\n setCommandExamples(command, [\n 'prisma-next contract emit',\n 'prisma-next contract emit --config ./custom-config.ts',\n 'prisma-next contract emit --output-path ./generated',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--output-path <dir>', 'Directory to write contract.json and contract.d.ts into')\n .action(async (options: ContractEmitOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await executeContractEmitCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (emitResult) => {\n if (flags.json) {\n ui.output(formatEmitJson(emitResult));\n } else {\n const output = formatEmitOutput(emitResult, flags);\n if (output) {\n ui.log(output);\n }\n if (!flags.quiet) {\n ui.success(formatSuccessMessage(flags));\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"m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,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC5D,CAAC,CACH;;CAGH,IAAI,OAAO,mBACT,GAAG,KAAK,OAAO,kBAAkB;CAGnC,OAAO,GAAG;EACR,aAAa,OAAO;EACpB,GAAG,UAAU,iBAAiB,OAAO,cAAc;EACnD,aAAa,OAAO;EACpB,QAAQ,QAAQ,OAAO,MAAM,KAAK;EAClC,OAAO,OAAO;EACd,SAAS,EAAE,OAAO,KAAK,KAAK,GAAG,WAAW;EAC3C,CAAC;;AAGJ,SAAgB,4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,OAAO;CACnC,uBACE,SACA,gCACA,+OAGD;CACD,mBAAmB,SAAS;EAC1B;EACA;EACA;EACD,CAAC;CACF,iBAAiB,QAAQ,CACtB,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,uBAAuB,0DAA0D,CACxF,OAAO,OAAO,YAAiC;EAC9C,MAAM,QAAQ,uBAAuB,QAAQ;EAC7C,MAAM,KAAK,iBAAiB,MAAM;EAKlC,MAAM,WAAW,aAAa,MAFT,2BAA2B,SAAS,OAAO,IAF9C,KAAK,KAEsD,CAAC,EAExC,OAAO,KAAK,eAAe;GAC/D,IAAI,MAAM,MACR,GAAG,OAAO,eAAe,WAAW,CAAC;QAChC;IACL,MAAM,SAAS,iBAAiB,YAAY,MAAM;IAClD,IAAI,QACF,GAAG,IAAI,OAAO;IAEhB,IAAI,CAAC,MAAM,OACT,GAAG,QAAQ,qBAAqB,MAAM,CAAC;;IAG3C;EACF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
1
+ {"version":3,"file":"contract-emit-CuUzzM46.mjs","names":["CliStructuredError","errorUnexpected"],"sources":["../src/utils/formatters/emit.ts","../src/commands/contract-emit.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { relative } from 'pathe';\n\nimport type { GlobalFlags } from '../global-flags';\nimport { isVerbose } from './helpers';\n\n// EmitContractResult type for CLI output formatting (includes file paths)\nexport interface EmitContractResult {\n readonly storageHash: string;\n readonly executionHash?: string;\n readonly profileHash: string;\n readonly outDir: string;\n readonly files: {\n readonly json: string;\n readonly dts: string;\n };\n readonly timings: {\n readonly total: number;\n };\n}\n\n/**\n * Formats human-readable output for contract emit.\n */\nexport function formatEmitOutput(result: EmitContractResult, flags: GlobalFlags): string {\n if (flags.quiet) {\n return '';\n }\n\n const lines: string[] = [];\n\n // Convert absolute paths to relative paths from cwd\n const jsonPath = relative(process.cwd(), result.files.json);\n const dtsPath = relative(process.cwd(), result.files.dts);\n\n lines.push(`✔ Emitted contract.json → ${jsonPath}`);\n lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);\n lines.push(` storageHash: ${result.storageHash}`);\n if (result.executionHash) {\n lines.push(` executionHash: ${result.executionHash}`);\n }\n if (result.profileHash) {\n lines.push(` profileHash: ${result.profileHash}`);\n }\n if (isVerbose(flags, 1)) {\n lines.push(` Total time: ${result.timings.total}ms`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Formats JSON output for contract emit.\n */\nexport function formatEmitJson(result: EmitContractResult): string {\n const output = {\n ok: true,\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n ...(result.profileHash ? { profileHash: result.profileHash } : {}),\n outDir: result.outDir,\n files: result.files,\n timings: result.timings,\n };\n\n return JSON.stringify(output, null, 2);\n}\n","import { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { errorContractConfigMissing } from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, join, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { executeContractEmit } from '../control-api/operations/contract-emit';\nimport type { ContractEmitResult } from '../control-api/types';\nimport { CliStructuredError, errorUnexpected } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport {\n type EmitContractResult,\n formatEmitJson,\n formatEmitOutput,\n} from '../utils/formatters/emit';\nimport { formatStyledHeader, formatSuccessMessage } from '../utils/formatters/styled';\nimport type { CommonCommandOptions } from '../utils/global-flags';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\n\ninterface ContractEmitOptions extends CommonCommandOptions {\n readonly config?: string;\n readonly outputPath?: string;\n}\n\ninterface HeaderPaths {\n readonly displayConfigPath: string;\n readonly outputJsonPath: string;\n readonly outputDtsPath: string;\n}\n\n/**\n * Pre-load the config just to compute display paths for the styled header. The\n * actual emit work goes through `executeContractEmit`, which loads the config\n * itself; the redundant load here is bounded and lets the header render before\n * the emit spans start.\n */\nasync function resolveHeaderPaths(\n configOption: string | undefined,\n outputPath: string | undefined,\n): Promise<Result<HeaderPaths, CliStructuredError>> {\n const displayConfigPath = configOption\n ? relative(process.cwd(), resolve(configOption))\n : 'prisma-next.config.ts';\n\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = await loadConfig(configOption);\n } catch (error) {\n if (error instanceof CliStructuredError) {\n return notOk(error);\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 effectiveJsonPath =\n outputPath !== undefined ? join(outputPath, 'contract.json') : config.contract?.output;\n\n if (!effectiveJsonPath) {\n return notOk(\n errorContractConfigMissing({\n why: 'Config.contract.output is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n }),\n );\n }\n\n try {\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } =\n getEmittedArtifactPaths(effectiveJsonPath);\n return ok({ displayConfigPath, outputJsonPath, outputDtsPath });\n } catch (error) {\n return notOk(\n errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n}\n\nasync function executeContractEmitCommand(\n options: ContractEmitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<EmitContractResult, CliStructuredError>> {\n const outputPath = options.outputPath !== undefined ? resolve(options.outputPath) : undefined;\n\n const headerPathsResult = await resolveHeaderPaths(options.config, outputPath);\n if (!headerPathsResult.ok) {\n return headerPathsResult;\n }\n const { displayConfigPath, outputJsonPath, outputDtsPath } = headerPathsResult.value;\n\n if (!flags.json && !flags.quiet) {\n ui.stderr(\n formatStyledHeader({\n command: 'contract emit',\n description: 'Emit your contract artifacts',\n url: 'https://pris.ly/contract-emit',\n details: [\n { label: 'config', value: displayConfigPath },\n { label: 'contract', value: relative(process.cwd(), outputJsonPath) },\n { label: 'types', value: relative(process.cwd(), outputDtsPath) },\n ],\n flags,\n }),\n );\n }\n\n const onProgress = createProgressAdapter({ ui, flags });\n const configPath = options.config ? resolve(options.config) : 'prisma-next.config.ts';\n\n let result: ContractEmitResult;\n try {\n result = await executeContractEmit({\n configPath,\n onProgress,\n ...ifDefined('outputPath', outputPath),\n });\n } catch (error) {\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n return notOk(\n errorUnexpected('Unexpected error during contract emit', {\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n\n if (result.validationWarning) {\n ui.warn(result.validationWarning);\n }\n\n return ok({\n storageHash: result.storageHash,\n ...ifDefined('executionHash', result.executionHash),\n profileHash: result.profileHash,\n outDir: dirname(result.files.json),\n files: result.files,\n timings: { total: Date.now() - startTime },\n });\n}\n\nexport function createContractEmitCommand(): Command {\n const command = new Command('emit');\n setCommandDescriptions(\n command,\n 'Emit your contract artifacts',\n 'Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\\n' +\n 'contract.d.ts. The contract.json contains the canonical contract structure, and\\n' +\n 'contract.d.ts provides TypeScript types for type-safe query building.',\n );\n setCommandExamples(command, [\n 'prisma-next contract emit',\n 'prisma-next contract emit --config ./custom-config.ts',\n 'prisma-next contract emit --output-path ./generated',\n ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--output-path <dir>', 'Directory to write contract.json and contract.d.ts into')\n .action(async (options: ContractEmitOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await executeContractEmitCommand(options, flags, ui, startTime);\n\n const exitCode = handleResult(result, flags, ui, (emitResult) => {\n if (flags.json) {\n ui.output(formatEmitJson(emitResult));\n } else {\n const output = formatEmitOutput(emitResult, flags);\n if (output) {\n ui.log(output);\n }\n if (!flags.quiet) {\n ui.success(formatSuccessMessage(flags));\n }\n }\n });\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,QAA4B,OAA4B;CACvF,IAAI,MAAM,OACR,OAAO;CAGT,MAAM,QAAkB,CAAC;CAGzB,MAAM,WAAW,SAAS,QAAQ,IAAI,GAAG,OAAO,MAAM,IAAI;CAC1D,MAAM,UAAU,SAAS,QAAQ,IAAI,GAAG,OAAO,MAAM,GAAG;CAExD,MAAM,KAAK,6BAA6B,UAAU;CAClD,MAAM,KAAK,6BAA6B,SAAS;CACjD,MAAM,KAAK,kBAAkB,OAAO,aAAa;CACjD,IAAI,OAAO,eACT,MAAM,KAAK,oBAAoB,OAAO,eAAe;CAEvD,IAAI,OAAO,aACT,MAAM,KAAK,kBAAkB,OAAO,aAAa;CAEnD,IAAI,UAAU,OAAO,CAAC,GACpB,MAAM,KAAK,iBAAiB,OAAO,QAAQ,MAAM,GAAG;CAGtD,OAAO,MAAM,KAAK,IAAI;AACxB;;;;AAKA,SAAgB,eAAe,QAAoC;CACjE,MAAM,SAAS;EACb,IAAI;EACJ,aAAa,OAAO;EACpB,GAAG,UAAU,iBAAiB,OAAO,aAAa;EAClD,GAAI,OAAO,cAAc,EAAE,aAAa,OAAO,YAAY,IAAI,CAAC;EAChE,QAAQ,OAAO;EACf,OAAO,OAAO;EACd,SAAS,OAAO;C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AAO,eAAe,UAAU,CAAC;QAC/B;IACL,MAAM,SAAS,iBAAiB,YAAY,KAAK;IACjD,IAAI,QACF,GAAG,IAAI,MAAM;IAEf,IAAI,CAAC,MAAM,OACT,GAAG,QAAQ,qBAAqB,KAAK,CAAC;GAE1C;EACF,CAAC;EACD,QAAQ,KAAK,QAAQ;CACvB,CAAC;CAEH,OAAO;AACT"}
@@ -1,3 +1,4 @@
1
+ import { mergeCapabilityMatrices } from "@prisma-next/framework-components/components";
1
2
  //#region src/control-api/contract-enrichment.ts
2
3
  function isPlainObject(value) {
3
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -13,25 +14,6 @@ function sortDeep(value) {
13
14
  function sortDeepTyped(value) {
14
15
  return sortDeep(value);
15
16
  }
16
- function extractCapabilityMatrix(value) {
17
- if (!isPlainObject(value)) return {};
18
- const out = {};
19
- for (const [namespace, maybeCaps] of Object.entries(value)) {
20
- if (!isPlainObject(maybeCaps)) continue;
21
- const caps = {};
22
- for (const [key, flag] of Object.entries(maybeCaps)) if (typeof flag === "boolean") caps[key] = flag;
23
- if (Object.keys(caps).length > 0) out[namespace] = caps;
24
- }
25
- return out;
26
- }
27
- function mergeCapabilities(left, right) {
28
- const next = { ...left };
29
- for (const [namespace, capabilities] of Object.entries(right)) next[namespace] = {
30
- ...left[namespace] ?? {},
31
- ...capabilities
32
- };
33
- return next;
34
- }
35
17
  function extractExtensionPackMeta(component) {
36
18
  const { kind, id, version, capabilities, types } = component;
37
19
  const base = {
@@ -55,12 +37,9 @@ function extractExtensionPackMeta(component) {
55
37
  * Enriches a raw contract with framework-derived metadata: capabilities from all component descriptors and extension pack metadata from extension descriptors. Produces deterministically sorted output.
56
38
  */
57
39
  function enrichContract(ir, components) {
58
- let mergedCapabilities = ir.capabilities;
40
+ const mergedCapabilities = mergeCapabilityMatrices(ir.capabilities, components);
59
41
  const extensionPacksMeta = {};
60
- for (const component of components) {
61
- if (component.capabilities) mergedCapabilities = mergeCapabilities(mergedCapabilities, extractCapabilityMatrix(component.capabilities));
62
- if (component.kind === "extension") extensionPacksMeta[component.id] = extractExtensionPackMeta(component);
63
- }
42
+ for (const component of components) if (component.kind === "extension") extensionPacksMeta[component.id] = extractExtensionPackMeta(component);
64
43
  const extensionPacks = Object.keys(extensionPacksMeta).length > 0 ? {
65
44
  ...ir.extensionPacks,
66
45
  ...extensionPacksMeta
@@ -74,4 +53,4 @@ function enrichContract(ir, components) {
74
53
  //#endregion
75
54
  export { enrichContract as t };
76
55
 
77
- //# sourceMappingURL=contract-enrichment-Dani0mMW.mjs.map
56
+ //# sourceMappingURL=contract-enrichment-XmUPhmsS.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-enrichment-XmUPhmsS.mjs","names":[],"sources":["../src/control-api/contract-enrichment.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n mergeCapabilityMatrices,\n type TargetBoundComponentDescriptor,\n} from '@prisma-next/framework-components/components';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction sortDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortDeep);\n }\n if (!isPlainObject(value)) {\n return value;\n }\n const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));\n const next: Record<string, unknown> = {};\n for (const [key, child] of entries) {\n next[key] = sortDeep(child);\n }\n return next;\n}\n\nfunction sortDeepTyped<T>(value: T): T {\n return sortDeep(value) as T;\n}\n\nfunction extractExtensionPackMeta(\n component: TargetBoundComponentDescriptor<string, string>,\n): Record<string, unknown> {\n const { kind, id, version, capabilities, types } = component;\n const base: Record<string, unknown> = {\n kind,\n id,\n familyId: component.familyId,\n targetId: component.targetId,\n version,\n };\n if (capabilities) {\n base['capabilities'] = capabilities;\n }\n if (types) {\n if (types.codecTypes) {\n const {\n controlPlaneHooks: _,\n codecDescriptors: _cd,\n ...cleanedCodecTypes\n } = types.codecTypes;\n base['types'] = { ...types, codecTypes: cleanedCodecTypes };\n } else {\n base['types'] = types;\n }\n }\n return base;\n}\n\n/**\n * Enriches a raw contract with framework-derived metadata: capabilities from all component descriptors and extension pack metadata from extension descriptors. Produces deterministically sorted output.\n */\nexport function enrichContract(\n ir: Contract,\n components: ReadonlyArray<TargetBoundComponentDescriptor<string, string>>,\n): Contract {\n const mergedCapabilities = mergeCapabilityMatrices(ir.capabilities, components);\n\n const extensionPacksMeta: Record<string, unknown> = {};\n for (const component of components) {\n if (component.kind === 'extension') {\n extensionPacksMeta[component.id] = extractExtensionPackMeta(component);\n }\n }\n\n const extensionPacks =\n Object.keys(extensionPacksMeta).length > 0\n ? { ...ir.extensionPacks, ...extensionPacksMeta }\n : ir.extensionPacks;\n\n return {\n ...ir,\n capabilities: sortDeepTyped(mergedCapabilities),\n extensionPacks: sortDeepTyped(extensionPacks),\n };\n}\n"],"mappings":";;AAMA,SAAS,cAAc,OAAkD;CACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,SAAS,OAAyB;CACzC,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,IAAI,QAAQ;CAE3B,IAAI,CAAC,cAAc,KAAK,GACtB,OAAO;CAET,MAAM,UAAU,OAAO,QAAQ,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;CAC3E,MAAM,OAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,KAAK,UAAU,SACzB,KAAK,OAAO,SAAS,KAAK;CAE5B,OAAO;AACT;AAEA,SAAS,cAAiB,OAAa;CACrC,OAAO,SAAS,KAAK;AACvB;AAEA,SAAS,yBACP,WACyB;CACzB,MAAM,EAAE,MAAM,IAAI,SAAS,cAAc,UAAU;CACnD,MAAM,OAAgC;EACpC;EACA;EACA,UAAU,UAAU;EACpB,UAAU,UAAU;EACpB;CACF;CACA,IAAI,cACF,KAAK,kBAAkB;CAEzB,IAAI,OACF,IAAI,MAAM,YAAY;EACpB,MAAM,EACJ,mBAAmB,GACnB,kBAAkB,KAClB,GAAG,sBACD,MAAM;EACV,KAAK,WAAW;GAAE,GAAG;GAAO,YAAY;EAAkB;CAC5D,OACE,KAAK,WAAW;CAGpB,OAAO;AACT;;;;AAKA,SAAgB,eACd,IACA,YACU;CACV,MAAM,qBAAqB,wBAAwB,GAAG,cAAc,UAAU;CAE9E,MAAM,qBAA8C,CAAC;CACrD,KAAK,MAAM,aAAa,YACtB,IAAI,UAAU,SAAS,aACrB,mBAAmB,UAAU,MAAM,yBAAyB,SAAS;CAIzE,MAAM,iBACJ,OAAO,KAAK,kBAAkB,EAAE,SAAS,IACrC;EAAE,GAAG,GAAG;EAAgB,GAAG;CAAmB,IAC9C,GAAG;CAET,OAAO;EACL,GAAG;EACH,cAAc,cAAc,kBAAkB;EAC9C,gBAAgB,cAAc,cAAc;CAC9C;AACF"}
@@ -1,6 +1,5 @@
1
- import { t as createTerminalUI } from "./terminal-ui-BiB_8KNo.mjs";
2
- import { d as setCommandDescriptions, f as setCommandExamples, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "./command-helpers-DtavI0wJ.mjs";
3
- import { t as inspectLiveSchema } from "./inspect-live-schema-LeWvkZVz.mjs";
1
+ import { d as setCommandDescriptions, f as setCommandExamples, t as addGlobalOptions, v as parseGlobalFlagsOrExit, x as handleResult, y as createTerminalUI } from "./command-helpers-4UNsRRc4.mjs";
2
+ import { t as inspectLiveSchema } from "./inspect-live-schema-BRCWQ-Sr.mjs";
4
3
  import { Command } from "commander";
5
4
  import { notOk, ok } from "@prisma-next/utils/result";
6
5
  import { dirname, relative, resolve } from "pathe";
@@ -73,4 +72,4 @@ function createContractInferCommand() {
73
72
  //#endregion
74
73
  export { createContractInferCommand as t };
75
74
 
76
- //# sourceMappingURL=contract-infer-pKkiCt7C.mjs.map
75
+ //# sourceMappingURL=contract-infer-C98ZaRhp.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract-infer-pKkiCt7C.mjs","names":[],"sources":["../src/commands/contract-infer-paths.ts","../src/commands/contract-infer.ts"],"sourcesContent":["import { dirname, resolve } from 'pathe';\n\ninterface ContractInferPathOptions {\n readonly output?: string;\n readonly config?: string;\n}\n\n/**\n * Resolves the output path for the inferred PSL contract.\n *\n * Priority:\n * 1. --output <path> flag (resolved relative to cwd)\n * 2. contract.prisma next to config.contract.output\n * 3. Canonical default: contract.prisma in the config directory\n */\nexport function resolveContractInferOutputPath(\n options: ContractInferPathOptions,\n contractOutput: string | undefined,\n): string {\n const configDir = options.config\n ? dirname(resolve(process.cwd(), options.config))\n : process.cwd();\n\n if (options.output) {\n return resolve(process.cwd(), options.output);\n }\n if (contractOutput) {\n const contractPath = resolve(configDir, contractOutput);\n return resolve(dirname(contractPath), 'contract.prisma');\n }\n return resolve(configDir, 'contract.prisma');\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { errorRuntime } from '@prisma-next/errors/execution';\nimport { printPsl } from '@prisma-next/psl-printer';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, relative } from 'pathe';\nimport type { CliStructuredError } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\nimport { resolveContractInferOutputPath } from './contract-infer-paths';\nimport {\n type InspectLiveSchemaOptions,\n type InspectLiveSchemaResult,\n inspectLiveSchema,\n} from './inspect-live-schema';\n\ninterface ContractInferOptions extends InspectLiveSchemaOptions {\n readonly output?: string;\n}\n\ninterface ContractInferSuccessResult {\n readonly ok: true;\n readonly summary: string;\n readonly target: InspectLiveSchemaResult['target'];\n readonly psl: {\n readonly path: string;\n };\n readonly meta: InspectLiveSchemaResult['meta'];\n readonly timings: {\n readonly total: number;\n };\n}\n\nasync function executeContractInferCommand(\n options: ContractInferOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<ContractInferSuccessResult, CliStructuredError>> {\n const inspectResult = await inspectLiveSchema(options, flags, ui, startTime, {\n commandName: 'contract infer',\n description: 'Infer a PSL contract from the live database schema',\n url: 'https://pris.ly/contract-infer',\n });\n\n if (!inspectResult.ok) {\n return inspectResult;\n }\n\n const { config, target, meta, pslContractAst } = inspectResult.value;\n\n if (!pslContractAst) {\n return notOk(\n errorRuntime('contract infer is not supported for this family', {\n why: 'The configured family does not implement the PslContractInferCapable capability, so an inferred PSL contract cannot be produced from the live database schema.',\n fix: 'Use a family that supports contract inference (e.g. SQL/Postgres).',\n }),\n );\n }\n\n const outputPath = resolveContractInferOutputPath(options, config.contract?.output);\n const pslContent = printPsl(pslContractAst);\n\n if (existsSync(outputPath) && !flags.json && !flags.quiet) {\n ui.stderr(`\\u26A0 Overwriting existing file: ${relative(process.cwd(), outputPath)}`);\n }\n\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, pslContent, 'utf-8');\n\n const pslPath = relative(process.cwd(), outputPath);\n if (!flags.json && !flags.quiet) {\n ui.stderr(`\\u2714 Contract written to ${pslPath}`);\n }\n\n return ok({\n ok: true,\n summary: 'Contract inferred successfully',\n target,\n psl: {\n path: pslPath,\n },\n meta,\n timings: {\n total: Date.now() - startTime,\n },\n });\n}\n\nexport function createContractInferCommand(): Command {\n const command = new Command('infer');\n setCommandDescriptions(\n command,\n 'Infer a PSL contract from the live database schema',\n 'Reads the live database schema and writes an inferred PSL contract to disk.\\n' +\n 'This command stops at `contract.prisma`; follow it with `contract emit` and\\n' +\n '`db sign` as separate steps.',\n );\n setCommandExamples(command, [\n 'prisma-next contract infer --db $DATABASE_URL',\n 'prisma-next contract infer --db $DATABASE_URL --output ./src/prisma/contract.prisma',\n 'prisma-next contract infer --db $DATABASE_URL --json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--output <path>', 'Write the inferred PSL contract to the specified path')\n .action(async (options: ContractInferOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await executeContractInferCommand(options, flags, ui, startTime);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n }\n });\n\n process.exit(exitCode);\n });\n\n return command;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,SAAgB,+BACd,SACA,gBACQ;CACR,MAAM,YAAY,QAAQ,SACtB,QAAQ,QAAQ,QAAQ,KAAK,EAAE,QAAQ,OAAO,CAAC,GAC/C,QAAQ,KAAK;CAEjB,IAAI,QAAQ,QACV,OAAO,QAAQ,QAAQ,KAAK,EAAE,QAAQ,OAAO;CAE/C,IAAI,gBAEF,OAAO,QAAQ,QADM,QAAQ,WAAW,eACL,CAAC,EAAE,kBAAkB;CAE1D,OAAO,QAAQ,WAAW,kBAAkB;;;;ACS9C,eAAe,4BACb,SACA,OACA,IACA,WACiE;CACjE,MAAM,gBAAgB,MAAM,kBAAkB,SAAS,OAAO,IAAI,WAAW;EAC3E,aAAa;EACb,aAAa;EACb,KAAK;EACN,CAAC;CAEF,IAAI,CAAC,cAAc,IACjB,OAAO;CAGT,MAAM,EAAE,QAAQ,QAAQ,MAAM,mBAAmB,cAAc;CAE/D,IAAI,CAAC,gBACH,OAAO,MACL,aAAa,mDAAmD;EAC9D,KAAK;EACL,KAAK;EACN,CAAC,CACH;CAGH,MAAM,aAAa,+BAA+B,SAAS,OAAO,UAAU,OAAO;CACnF,MAAM,aAAa,SAAS,eAAe;CAE3C,IAAI,WAAW,WAAW,IAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OAClD,GAAG,OAAO,qCAAqC,SAAS,QAAQ,KAAK,EAAE,WAAW,GAAG;CAGvF,UAAU,QAAQ,WAAW,EAAE,EAAE,WAAW,MAAM,CAAC;CACnD,cAAc,YAAY,YAAY,QAAQ;CAE9C,MAAM,UAAU,SAAS,QAAQ,KAAK,EAAE,WAAW;CACnD,IAAI,CAAC,MAAM,QAAQ,CAAC,MAAM,OACxB,GAAG,OAAO,8BAA8B,UAAU;CAGpD,OAAO,GAAG;EACR,IAAI;EACJ,SAAS;EACT;EACA,KAAK,EACH,MAAM,SACP;EACD;EACA,SAAS,EACP,OAAO,KAAK,KAAK,GAAG,WACrB;EACF,CAAC;;AAGJ,SAAgB,6BAAsC;CACpD,MAAM,UAAU,IAAI,QAAQ,QAAQ;CACpC,uBACE,SACA,sDACA,yLAGD;CACD,mBAAmB,SAAS;EAC1B;EACA;EACA;EACD,CAAC;CACF,iBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,mBAAmB,wDAAwD,CAClF,OAAO,OAAO,YAAkC;EAC/C,MAAM,QAAQ,uBAAuB,QAAQ;EAC7C,MAAM,KAAK,iBAAiB,MAAM;EAIlC,MAAM,WAAW,aAAa,MADT,4BAA4B,SAAS,OAAO,IAF/C,KAAK,KAEuD,CAAC,EACzC,OAAO,KAAK,UAAU;GAC1D,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,OAAO,MAAM,EAAE,CAAC;IAE3C;EAEF,QAAQ,KAAK,SAAS;GACtB;CAEJ,OAAO"}
1
+ {"version":3,"file":"contract-infer-C98ZaRhp.mjs","names":[],"sources":["../src/commands/contract-infer-paths.ts","../src/commands/contract-infer.ts"],"sourcesContent":["import { dirname, resolve } from 'pathe';\n\ninterface ContractInferPathOptions {\n readonly output?: string;\n readonly config?: string;\n}\n\n/**\n * Resolves the output path for the inferred PSL contract.\n *\n * Priority:\n * 1. --output <path> flag (resolved relative to cwd)\n * 2. contract.prisma next to config.contract.output\n * 3. Canonical default: contract.prisma in the config directory\n */\nexport function resolveContractInferOutputPath(\n options: ContractInferPathOptions,\n contractOutput: string | undefined,\n): string {\n const configDir = options.config\n ? dirname(resolve(process.cwd(), options.config))\n : process.cwd();\n\n if (options.output) {\n return resolve(process.cwd(), options.output);\n }\n if (contractOutput) {\n const contractPath = resolve(configDir, contractOutput);\n return resolve(dirname(contractPath), 'contract.prisma');\n }\n return resolve(configDir, 'contract.prisma');\n}\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { errorRuntime } from '@prisma-next/errors/execution';\nimport { printPsl } from '@prisma-next/psl-printer';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, relative } from 'pathe';\nimport type { CliStructuredError } from '../utils/cli-errors';\nimport {\n addGlobalOptions,\n setCommandDescriptions,\n setCommandExamples,\n} from '../utils/command-helpers';\nimport { type GlobalFlags, parseGlobalFlagsOrExit } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { createTerminalUI, type TerminalUI } from '../utils/terminal-ui';\nimport { resolveContractInferOutputPath } from './contract-infer-paths';\nimport {\n type InspectLiveSchemaOptions,\n type InspectLiveSchemaResult,\n inspectLiveSchema,\n} from './inspect-live-schema';\n\ninterface ContractInferOptions extends InspectLiveSchemaOptions {\n readonly output?: string;\n}\n\ninterface ContractInferSuccessResult {\n readonly ok: true;\n readonly summary: string;\n readonly target: InspectLiveSchemaResult['target'];\n readonly psl: {\n readonly path: string;\n };\n readonly meta: InspectLiveSchemaResult['meta'];\n readonly timings: {\n readonly total: number;\n };\n}\n\nasync function executeContractInferCommand(\n options: ContractInferOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<ContractInferSuccessResult, CliStructuredError>> {\n const inspectResult = await inspectLiveSchema(options, flags, ui, startTime, {\n commandName: 'contract infer',\n description: 'Infer a PSL contract from the live database schema',\n url: 'https://pris.ly/contract-infer',\n });\n\n if (!inspectResult.ok) {\n return inspectResult;\n }\n\n const { config, target, meta, pslContractAst } = inspectResult.value;\n\n if (!pslContractAst) {\n return notOk(\n errorRuntime('contract infer is not supported for this family', {\n why: 'The configured family does not implement the PslContractInferCapable capability, so an inferred PSL contract cannot be produced from the live database schema.',\n fix: 'Use a family that supports contract inference (e.g. SQL/Postgres).',\n }),\n );\n }\n\n const outputPath = resolveContractInferOutputPath(options, config.contract?.output);\n const pslContent = printPsl(pslContractAst);\n\n if (existsSync(outputPath) && !flags.json && !flags.quiet) {\n ui.stderr(`\\u26A0 Overwriting existing file: ${relative(process.cwd(), outputPath)}`);\n }\n\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, pslContent, 'utf-8');\n\n const pslPath = relative(process.cwd(), outputPath);\n if (!flags.json && !flags.quiet) {\n ui.stderr(`\\u2714 Contract written to ${pslPath}`);\n }\n\n return ok({\n ok: true,\n summary: 'Contract inferred successfully',\n target,\n psl: {\n path: pslPath,\n },\n meta,\n timings: {\n total: Date.now() - startTime,\n },\n });\n}\n\nexport function createContractInferCommand(): Command {\n const command = new Command('infer');\n setCommandDescriptions(\n command,\n 'Infer a PSL contract from the live database schema',\n 'Reads the live database schema and writes an inferred PSL contract to disk.\\n' +\n 'This command stops at `contract.prisma`; follow it with `contract emit` and\\n' +\n '`db sign` as separate steps.',\n );\n setCommandExamples(command, [\n 'prisma-next contract infer --db $DATABASE_URL',\n 'prisma-next contract infer --db $DATABASE_URL --output ./src/prisma/contract.prisma',\n 'prisma-next contract infer --db $DATABASE_URL --json',\n ]);\n addGlobalOptions(command)\n .option('--db <url>', 'Database connection string')\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .option('--output <path>', 'Write the inferred PSL contract to the specified path')\n .action(async (options: ContractInferOptions) => {\n const flags = parseGlobalFlagsOrExit(options);\n const ui = createTerminalUI(flags);\n const startTime = Date.now();\n\n const result = await executeContractInferCommand(options, flags, ui, startTime);\n const exitCode = handleResult(result, flags, ui, (value) => {\n if (flags.json) {\n ui.output(JSON.stringify(value, null, 2));\n }\n });\n\n process.exit(exitCode);\n });\n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;CACF,CAAC;AACH;AAEA,SAAgB,6BAAsC;CACpD,MAAM,UAAU,IAAI,QAAQ,OAAO;CACnC,uBACE,SACA,sDACA,wLAGF;CACA,mBAAmB,SAAS;EAC1B;EACA;EACA;CACF,CAAC;CACD,iBAAiB,OAAO,EACrB,OAAO,cAAc,4BAA4B,EACjD,OAAO,mBAAmB,+BAA+B,EACzD,OAAO,mBAAmB,uDAAuD,EACjF,OAAO,OAAO,YAAkC;EAC/C,MAAM,QAAQ,uBAAuB,OAAO;EAC5C,MAAM,KAAK,iBAAiB,KAAK;EAIjC,MAAM,WAAW,aAAa,MADT,4BAA4B,SAAS,OAAO,IAF/C,KAAK,IAEsD,CAAC,GACxC,OAAO,KAAK,UAAU;GAC1D,IAAI,MAAM,MACR,GAAG,OAAO,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;EAE5C,CAAC;EAED,QAAQ,KAAK,QAAQ;CACvB,CAAC;CAEH,OAAO;AACT"}
@@ -0,0 +1,170 @@
1
+ import { t as CliStructuredError } from "./cli-errors-DFF1LlfU.mjs";
2
+ import { t as toDeclaredExtensionsFromRaw } from "./extension-pack-inputs-BiY86HbQ.mjs";
3
+ import { notOk, ok } from "@prisma-next/utils/result";
4
+ import { loadContractSpaceAggregate } from "@prisma-next/migration-tools/aggregate";
5
+ //#region src/utils/contract-space-aggregate-loader.ts
6
+ const CONTRACT_SPACES_DOCS_URL = "https://pris.ly/contract-spaces";
7
+ function contractSpaceError5002(summary, options) {
8
+ return new CliStructuredError("5002", summary, {
9
+ domain: "MIG",
10
+ why: options.why,
11
+ fix: options.fix,
12
+ docsUrl: CONTRACT_SPACES_DOCS_URL,
13
+ meta: { violations: options.violations }
14
+ });
15
+ }
16
+ /**
17
+ * Build the `5002` structured-error envelope for a contract-space
18
+ * target mismatch. Shared between the declared-extension precheck (the
19
+ * descriptor's configured target disagrees with the project target) and
20
+ * the on-disk-contract check surfaced by `checkIntegrity`.
21
+ */
22
+ function targetMismatchError(spaceId, expected, actual) {
23
+ return contractSpaceError5002(`Contract-space target mismatch for "${spaceId}"`, {
24
+ why: `Space "${spaceId}" targets "${actual}" but the project's adapter targets "${expected}".`,
25
+ fix: "Update the extension descriptor to target the configured database, or change the project adapter.",
26
+ violations: [{
27
+ kind: "targetMismatch",
28
+ spaceId,
29
+ expected,
30
+ actual
31
+ }]
32
+ });
33
+ }
34
+ /**
35
+ * Human-readable detail for an integrity violation, used as the `why`
36
+ * of the `integrityFailure` envelope. Mirrors the messages the prior
37
+ * throw-on-load loader produced so downstream consumers see the same
38
+ * text for the same on-disk state.
39
+ */
40
+ function describeIntegrityViolation(violation) {
41
+ switch (violation.kind) {
42
+ case "hashMismatch": return `Migration "${violation.dirName}" stored hash "${violation.stored}" does not match computed hash "${violation.computed}".`;
43
+ case "providedInvariantsMismatch": return `Migration "${violation.dirName}" providedInvariants in migration.json disagrees with ops.json.`;
44
+ case "packageUnloadable": return `Migration "${violation.dirName}" could not be loaded: ${violation.detail}`;
45
+ case "sameSourceAndTarget": return `Migration "${violation.dirName}" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`;
46
+ case "headRefMissing": return `Head ref \`refs/head.json\` is missing for contract space "${violation.spaceId}".`;
47
+ case "headRefNotInGraph": return `Head ref ${violation.hash} for contract space "${violation.spaceId}" is not present in the migration graph.`;
48
+ case "refUnreadable": return `Ref "${violation.refName}" for contract space "${violation.spaceId}" is unreadable: ${violation.detail}`;
49
+ case "duplicateMigrationHash": return `Multiple migrations in space "${violation.spaceId}" share migrationHash "${violation.migrationHash}" (${violation.dirNames.join(", ")}).`;
50
+ default: {
51
+ const spaceId = "spaceId" in violation ? violation.spaceId : "*";
52
+ return `Integrity violation "${violation.kind}" for contract space "${spaceId}".`;
53
+ }
54
+ }
55
+ }
56
+ /**
57
+ * Map the integrity violations `checkIntegrity` reports into a single
58
+ * CLI structured-error envelope, preserving the error codes the prior
59
+ * throw-on-load loader emitted: `5001` (layout drift, bundled) and
60
+ * `5002` (target / disjointness / contract-validation / structural
61
+ * integrity). Returns `null` when there is nothing to refuse on.
62
+ *
63
+ * Precedence reproduces the prior loader's first-failure ordering:
64
+ * layout drift first (every offence bundled into one envelope), then
65
+ * target mismatch, then disjointness, then a contract-validation
66
+ * failure, then any remaining structural integrity violation.
67
+ */
68
+ function mapIntegrityViolations(violations) {
69
+ if (violations.length === 0) return null;
70
+ const layout = violations.filter((v) => v.kind === "orphanSpaceDir" || v.kind === "declaredButUnmigrated");
71
+ if (layout.length > 0) {
72
+ const lines = layout.map((v) => `- [${v.kind}] ${v.spaceId}`);
73
+ return new CliStructuredError("5001", layout.length === 1 ? "Contract-space layout violation detected" : `Contract-space layout violations detected (${layout.length})`, {
74
+ domain: "MIG",
75
+ why: `The on-disk \`migrations/\` directory and your \`extensionPacks\` declaration are not in agreement.\n${lines.join("\n")}`,
76
+ fix: "Declare the extension in `extensionPacks` and re-emit its contract-space artefacts, or remove the orphan `migrations/<space>` directory.",
77
+ docsUrl: CONTRACT_SPACES_DOCS_URL,
78
+ meta: { violations: layout }
79
+ });
80
+ }
81
+ const targetMismatch = violations.find((v) => v.kind === "targetMismatch");
82
+ if (targetMismatch && targetMismatch.kind === "targetMismatch") return targetMismatchError(targetMismatch.spaceId, targetMismatch.expected, targetMismatch.actual);
83
+ const disjointness = violations.find((v) => v.kind === "disjointness");
84
+ if (disjointness && disjointness.kind === "disjointness") return contractSpaceError5002(`Contract-space disjointness violation: storage element "${disjointness.element}" claimed by multiple spaces`, {
85
+ why: `Spaces ${disjointness.claimedBy.map((s) => `"${s}"`).join(", ")} all claim the storage element "${disjointness.element}". Each storage element must be owned by exactly one contract space.`,
86
+ fix: "Update the conflicting contracts so each storage element is claimed by exactly one space.",
87
+ violations: [disjointness]
88
+ });
89
+ const contractUnreadable = violations.find((v) => v.kind === "contractUnreadable");
90
+ if (contractUnreadable && contractUnreadable.kind === "contractUnreadable") return contractSpaceError5002(`Contract-space contract validation failed for "${contractUnreadable.spaceId}"`, {
91
+ why: contractUnreadable.detail,
92
+ fix: "Re-emit the extension contract with `prisma-next contract emit`, or fix the extension pack descriptor producing the invalid contract.",
93
+ violations: [contractUnreadable]
94
+ });
95
+ const structural = violations[0];
96
+ return contractSpaceError5002(`Contract-space integrity failure for "${"spaceId" in structural ? structural.spaceId : "*"}"`, {
97
+ why: describeIntegrityViolation(structural),
98
+ fix: "Re-emit the affected migration package(s) or restore the on-disk `migrations/` directory from version control.",
99
+ violations: [structural]
100
+ });
101
+ }
102
+ function declaredExtensionsFromInputs(extensionPacks) {
103
+ return toDeclaredExtensionsFromRaw(extensionPacks);
104
+ }
105
+ /**
106
+ * Reject extension descriptors whose configured target disagrees with
107
+ * the project target before any on-disk read.
108
+ */
109
+ function refuseDeclaredExtensionTargetMismatch(inputs) {
110
+ for (const declared of declaredExtensionsFromInputs(inputs.extensionPacks)) if (declared.targetId !== inputs.targetId) return targetMismatchError(declared.id, inputs.targetId, declared.targetId);
111
+ return null;
112
+ }
113
+ /**
114
+ * Load the tolerant {@link ContractSpaceAggregate} once at the CLI
115
+ * surface. Construction never throws on disk content; callers query
116
+ * {@link ContractSpaceAggregate.app} / extension facets instead of
117
+ * re-reading `migrations/`.
118
+ */
119
+ async function loadContractSpaceAggregateForCli(inputs) {
120
+ const targetFailure = refuseDeclaredExtensionTargetMismatch(inputs);
121
+ if (targetFailure) return notOk(targetFailure);
122
+ return ok(await loadContractSpaceAggregate({
123
+ migrationsDir: inputs.migrationsDir,
124
+ deserializeContract: inputs.deserializeContract,
125
+ appContract: inputs.appContract
126
+ }));
127
+ }
128
+ /**
129
+ * Run `checkIntegrity` on a loaded aggregate and map violations into
130
+ * the contract-space refusal envelope, or return `null` when the model
131
+ * is acceptable for the requested check scope.
132
+ */
133
+ function refuseContractSpaceIntegrity(aggregate, options) {
134
+ return mapIntegrityViolations(aggregate.checkIntegrity(options));
135
+ }
136
+ const PACKAGE_CORRUPTION_KINDS = new Set([
137
+ "hashMismatch",
138
+ "providedInvariantsMismatch",
139
+ "packageUnloadable"
140
+ ]);
141
+ /**
142
+ * Reader-subset integrity refusal for `migration status`: package
143
+ * corruptions only (`hashMismatch`, `providedInvariantsMismatch`,
144
+ * `packageUnloadable`).
145
+ */
146
+ function refusePackageCorruptionOnAggregate(aggregate) {
147
+ return mapIntegrityViolations(aggregate.checkIntegrity().filter((v) => PACKAGE_CORRUPTION_KINDS.has(v.kind)));
148
+ }
149
+ /**
150
+ * Construct the tolerant {@link ContractSpaceAggregate} at the CLI
151
+ * surface and apply the explicit integrity refusal.
152
+ *
153
+ * App-space migration packages are read from `migrations/<app>/` by the
154
+ * loader itself; callers no longer thread them through.
155
+ */
156
+ async function buildContractSpaceAggregate(inputs) {
157
+ const declaredExtensions = declaredExtensionsFromInputs(inputs.extensionPacks);
158
+ const loaded = await loadContractSpaceAggregateForCli(inputs);
159
+ if (!loaded.ok) return loaded;
160
+ const failure = refuseContractSpaceIntegrity(loaded.value, {
161
+ declaredExtensions,
162
+ checkContracts: true
163
+ });
164
+ if (failure) return notOk(failure);
165
+ return ok(loaded.value);
166
+ }
167
+ //#endregion
168
+ export { refusePackageCorruptionOnAggregate as i, loadContractSpaceAggregateForCli as n, refuseContractSpaceIntegrity as r, buildContractSpaceAggregate as t };
169
+
170
+ //# sourceMappingURL=contract-space-aggregate-loader-CVHGuA35.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-space-aggregate-loader-CVHGuA35.mjs","names":[],"sources":["../src/utils/contract-space-aggregate-loader.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport type { ControlExtensionDescriptor } from '@prisma-next/framework-components/control';\nimport type {\n ContractSpaceAggregate,\n DeclaredExtensionEntry,\n IntegrityQueryOptions,\n IntegrityViolation,\n} from '@prisma-next/migration-tools/aggregate';\nimport { loadContractSpaceAggregate } from '@prisma-next/migration-tools/aggregate';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { CliStructuredError } from './cli-errors';\nimport { toDeclaredExtensionsFromRaw } from './extension-pack-inputs';\n\nconst CONTRACT_SPACES_DOCS_URL = 'https://pris.ly/contract-spaces';\n\nfunction contractSpaceError5002(\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly violations: readonly IntegrityViolation[];\n },\n): CliStructuredError {\n return new CliStructuredError('5002', summary, {\n domain: 'MIG',\n why: options.why,\n fix: options.fix,\n docsUrl: CONTRACT_SPACES_DOCS_URL,\n meta: { violations: options.violations },\n });\n}\n\n/**\n * Build the `5002` structured-error envelope for a contract-space\n * target mismatch. Shared between the declared-extension precheck (the\n * descriptor's configured target disagrees with the project target) and\n * the on-disk-contract check surfaced by `checkIntegrity`.\n */\nfunction targetMismatchError(\n spaceId: string,\n expected: string,\n actual: string,\n): CliStructuredError {\n return contractSpaceError5002(`Contract-space target mismatch for \"${spaceId}\"`, {\n why: `Space \"${spaceId}\" targets \"${actual}\" but the project's adapter targets \"${expected}\".`,\n fix: 'Update the extension descriptor to target the configured database, or change the project adapter.',\n violations: [{ kind: 'targetMismatch', spaceId, expected, actual }],\n });\n}\n\n/**\n * Human-readable detail for an integrity violation, used as the `why`\n * of the `integrityFailure` envelope. Mirrors the messages the prior\n * throw-on-load loader produced so downstream consumers see the same\n * text for the same on-disk state.\n */\nfunction describeIntegrityViolation(violation: IntegrityViolation): string {\n switch (violation.kind) {\n case 'hashMismatch':\n return `Migration \"${violation.dirName}\" stored hash \"${violation.stored}\" does not match computed hash \"${violation.computed}\".`;\n case 'providedInvariantsMismatch':\n return `Migration \"${violation.dirName}\" providedInvariants in migration.json disagrees with ops.json.`;\n case 'packageUnloadable':\n return `Migration \"${violation.dirName}\" could not be loaded: ${violation.detail}`;\n case 'sameSourceAndTarget':\n return `Migration \"${violation.dirName}\" has source equal to target (${violation.hash}) with no data invariant — a true no-op self-edge.`;\n case 'headRefMissing':\n return `Head ref \\`refs/head.json\\` is missing for contract space \"${violation.spaceId}\".`;\n case 'headRefNotInGraph':\n return `Head ref ${violation.hash} for contract space \"${violation.spaceId}\" is not present in the migration graph.`;\n case 'refUnreadable':\n return `Ref \"${violation.refName}\" for contract space \"${violation.spaceId}\" is unreadable: ${violation.detail}`;\n case 'duplicateMigrationHash':\n return `Multiple migrations in space \"${violation.spaceId}\" share migrationHash \"${violation.migrationHash}\" (${violation.dirNames.join(', ')}).`;\n default: {\n const spaceId = 'spaceId' in violation ? violation.spaceId : '*';\n return `Integrity violation \"${violation.kind}\" for contract space \"${spaceId}\".`;\n }\n }\n}\n\n/**\n * Map the integrity violations `checkIntegrity` reports into a single\n * CLI structured-error envelope, preserving the error codes the prior\n * throw-on-load loader emitted: `5001` (layout drift, bundled) and\n * `5002` (target / disjointness / contract-validation / structural\n * integrity). Returns `null` when there is nothing to refuse on.\n *\n * Precedence reproduces the prior loader's first-failure ordering:\n * layout drift first (every offence bundled into one envelope), then\n * target mismatch, then disjointness, then a contract-validation\n * failure, then any remaining structural integrity violation.\n */\nexport function mapIntegrityViolations(\n violations: readonly IntegrityViolation[],\n): CliStructuredError | null {\n if (violations.length === 0) return null;\n\n const layout = violations.filter(\n (v): v is Extract<IntegrityViolation, { kind: 'orphanSpaceDir' | 'declaredButUnmigrated' }> =>\n v.kind === 'orphanSpaceDir' || v.kind === 'declaredButUnmigrated',\n );\n if (layout.length > 0) {\n const lines = layout.map((v) => `- [${v.kind}] ${v.spaceId}`);\n const summary =\n layout.length === 1\n ? 'Contract-space layout violation detected'\n : `Contract-space layout violations detected (${layout.length})`;\n return new CliStructuredError('5001', summary, {\n domain: 'MIG',\n why: `The on-disk \\`migrations/\\` directory and your \\`extensionPacks\\` declaration are not in agreement.\\n${lines.join('\\n')}`,\n fix: 'Declare the extension in `extensionPacks` and re-emit its contract-space artefacts, or remove the orphan `migrations/<space>` directory.',\n docsUrl: CONTRACT_SPACES_DOCS_URL,\n meta: { violations: layout },\n });\n }\n\n const targetMismatch = violations.find((v) => v.kind === 'targetMismatch');\n if (targetMismatch && targetMismatch.kind === 'targetMismatch') {\n return targetMismatchError(\n targetMismatch.spaceId,\n targetMismatch.expected,\n targetMismatch.actual,\n );\n }\n\n const disjointness = violations.find((v) => v.kind === 'disjointness');\n if (disjointness && disjointness.kind === 'disjointness') {\n return contractSpaceError5002(\n `Contract-space disjointness violation: storage element \"${disjointness.element}\" claimed by multiple spaces`,\n {\n why: `Spaces ${disjointness.claimedBy.map((s) => `\"${s}\"`).join(', ')} all claim the storage element \"${disjointness.element}\". Each storage element must be owned by exactly one contract space.`,\n fix: 'Update the conflicting contracts so each storage element is claimed by exactly one space.',\n violations: [disjointness],\n },\n );\n }\n\n const contractUnreadable = violations.find((v) => v.kind === 'contractUnreadable');\n if (contractUnreadable && contractUnreadable.kind === 'contractUnreadable') {\n return contractSpaceError5002(\n `Contract-space contract validation failed for \"${contractUnreadable.spaceId}\"`,\n {\n why: contractUnreadable.detail,\n fix: 'Re-emit the extension contract with `prisma-next contract emit`, or fix the extension pack descriptor producing the invalid contract.',\n violations: [contractUnreadable],\n },\n );\n }\n\n // Any remaining recoverable structural violation refuses as an\n // integrity failure, surfacing the first one's detail (every violation\n // is still computed; the gate just renders one envelope).\n const structural = violations[0]!;\n const spaceId = 'spaceId' in structural ? structural.spaceId : '*';\n return contractSpaceError5002(`Contract-space integrity failure for \"${spaceId}\"`, {\n why: describeIntegrityViolation(structural),\n fix: 'Re-emit the affected migration package(s) or restore the on-disk `migrations/` directory from version control.',\n violations: [structural],\n });\n}\n\n/**\n * Inputs needed to compose the aggregate loader at the CLI surface.\n *\n * Keeps the loader framework-neutral (no `Config` import) by accepting\n * already-resolved structural inputs: validated app contract, target\n * id, migrations root directory, and the set of extension descriptors.\n */\nexport interface BuildAggregateInputs<TFamilyId extends string, TTargetId extends string> {\n readonly targetId: TTargetId;\n readonly migrationsDir: string;\n readonly appContract: Contract;\n readonly extensionPacks: ReadonlyArray<ControlExtensionDescriptor<TFamilyId, TTargetId>>;\n readonly deserializeContract: (contractJson: unknown) => Contract;\n}\n\nfunction declaredExtensionsFromInputs(\n extensionPacks: BuildAggregateInputs<string, string>['extensionPacks'],\n): readonly DeclaredExtensionEntry[] {\n return toDeclaredExtensionsFromRaw(extensionPacks as ReadonlyArray<unknown>);\n}\n\n/**\n * Reject extension descriptors whose configured target disagrees with\n * the project target before any on-disk read.\n */\nexport function refuseDeclaredExtensionTargetMismatch<\n TFamilyId extends string,\n TTargetId extends string,\n>(inputs: BuildAggregateInputs<TFamilyId, TTargetId>): CliStructuredError | null {\n for (const declared of declaredExtensionsFromInputs(inputs.extensionPacks)) {\n if (declared.targetId !== inputs.targetId) {\n return targetMismatchError(declared.id, inputs.targetId, declared.targetId);\n }\n }\n return null;\n}\n\n/**\n * Load the tolerant {@link ContractSpaceAggregate} once at the CLI\n * surface. Construction never throws on disk content; callers query\n * {@link ContractSpaceAggregate.app} / extension facets instead of\n * re-reading `migrations/`.\n */\nexport async function loadContractSpaceAggregateForCli<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const targetFailure = refuseDeclaredExtensionTargetMismatch(inputs);\n if (targetFailure) {\n return notOk(targetFailure);\n }\n\n const aggregate = await loadContractSpaceAggregate({\n migrationsDir: inputs.migrationsDir,\n deserializeContract: inputs.deserializeContract,\n appContract: inputs.appContract,\n });\n return ok(aggregate);\n}\n\n/**\n * Run `checkIntegrity` on a loaded aggregate and map violations into\n * the contract-space refusal envelope, or return `null` when the model\n * is acceptable for the requested check scope.\n */\nexport function refuseContractSpaceIntegrity(\n aggregate: ContractSpaceAggregate,\n options: IntegrityQueryOptions,\n): CliStructuredError | null {\n return mapIntegrityViolations(aggregate.checkIntegrity(options));\n}\n\nconst PACKAGE_CORRUPTION_KINDS = new Set<IntegrityViolation['kind']>([\n 'hashMismatch',\n 'providedInvariantsMismatch',\n 'packageUnloadable',\n]);\n\n/**\n * Reader-subset integrity refusal for `migration status`: package\n * corruptions only (`hashMismatch`, `providedInvariantsMismatch`,\n * `packageUnloadable`).\n */\nexport function refusePackageCorruptionOnAggregate(\n aggregate: ContractSpaceAggregate,\n): CliStructuredError | null {\n const corruption = aggregate.checkIntegrity().filter((v) => PACKAGE_CORRUPTION_KINDS.has(v.kind));\n return mapIntegrityViolations(corruption);\n}\n\n/**\n * Construct the tolerant {@link ContractSpaceAggregate} at the CLI\n * surface and apply the explicit integrity refusal.\n *\n * App-space migration packages are read from `migrations/<app>/` by the\n * loader itself; callers no longer thread them through.\n */\nexport async function buildContractSpaceAggregate<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n inputs: BuildAggregateInputs<TFamilyId, TTargetId>,\n): Promise<Result<ContractSpaceAggregate, CliStructuredError>> {\n const declaredExtensions = declaredExtensionsFromInputs(inputs.extensionPacks);\n const loaded = await loadContractSpaceAggregateForCli(inputs);\n if (!loaded.ok) {\n return loaded;\n }\n const failure = refuseContractSpaceIntegrity(loaded.value, {\n declaredExtensions,\n checkContracts: true,\n });\n if (failure) {\n return notOk(failure);\n }\n return ok(loaded.value);\n}\n"],"mappings":";;;;;AAaA,MAAM,2BAA2B;AAEjC,SAAS,uBACP,SACA,SAKoB;CACpB,OAAO,IAAI,mBAAmB,QAAQ,SAAS;EAC7C,QAAQ;EACR,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,SAAS;EACT,MAAM,EAAE,YAAY,QAAQ,WAAW;CACzC,CAAC;AACH;;;;;;;AAQA,SAAS,oBACP,SACA,UACA,QACoB;CACpB,OAAO,uBAAuB,uCAAuC,QAAQ,IAAI;EAC/E,KAAK,UAAU,QAAQ,aAAa,OAAO,uCAAuC,SAAS;EAC3F,KAAK;EACL,YAAY,CAAC;GAAE,MAAM;GAAkB;GAAS;GAAU;EAAO,CAAC;CACpE,CAAC;AACH;;;;;;;AAQA,SAAS,2BAA2B,WAAuC;CACzE,QAAQ,UAAU,MAAlB;EACE,KAAK,gBACH,OAAO,cAAc,UAAU,QAAQ,iBAAiB,UAAU,OAAO,kCAAkC,UAAU,SAAS;EAChI,KAAK,8BACH,OAAO,cAAc,UAAU,QA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C2B;CAE3B,OAAO,uBADY,UAAU,eAAe,EAAE,QAAQ,MAAM,yBAAyB,IAAI,EAAE,IAAI,CACxD,CAAC;AAC1C;;;;;;;;AASA,eAAsB,4BAIpB,QAC6D;CAC7D,MAAM,qBAAqB,6BAA6B,OAAO,cAAc;CAC7E,MAAM,SAAS,MAAM,iCAAiC,MAAM;CAC5D,IAAI,CAAC,OAAO,IACV,OAAO;CAET,MAAM,UAAU,6BAA6B,OAAO,OAAO;EACzD;EACA,gBAAgB;CAClB,CAAC;CACD,IAAI,SACF,OAAO,MAAM,OAAO;CAEtB,OAAO,GAAG,OAAO,KAAK;AACxB"}
@@ -1,10 +1,9 @@
1
1
  import { t as loadConfig } from "./config-loader-B6sJjXTv.mjs";
2
- import { a as errorContractValidationFailed, c as errorDriverRequired, f as errorMarkerMissing, g as errorRuntime, l as errorFileNotFound, o as errorDatabaseConnectionRequired, t as CliStructuredError, u as errorHashMismatch, v as errorTargetMismatch, y as errorUnexpected } from "./cli-errors-Djtz98Vm.mjs";
3
- import { t as createTerminalUI } from "./terminal-ui-BiB_8KNo.mjs";
4
- import { S as formatStyledHeader, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, o as maskConnectionUrl, t as addGlobalOptions, v as parseGlobalFlagsOrExit, y as handleResult } from "./command-helpers-DtavI0wJ.mjs";
5
- import { t as createProgressAdapter } from "./progress-adapter-DFfvZcYL.mjs";
6
- import { a as ContractValidationError, t as createControlClient } from "./client-oXO2WCPD.mjs";
7
- import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "./verify-Bom75OYI.mjs";
2
+ import { C as errorRuntime, D as errorTargetMismatch, O as errorUnexpected, a as errorContractValidationFailed, c as errorDriverRequired, l as errorFileNotFound, m as errorMarkerMissing, o as errorDatabaseConnectionRequired, t as CliStructuredError, u as errorHashMismatch } from "./cli-errors-DFF1LlfU.mjs";
3
+ import { D as formatStyledHeader, c as resolveContractPath, d as setCommandDescriptions, f as setCommandExamples, l as resolveMigrationPaths, o as maskConnectionUrl, t as addGlobalOptions, v as parseGlobalFlagsOrExit, x as handleResult, y as createTerminalUI } from "./command-helpers-4UNsRRc4.mjs";
4
+ import { t as createProgressAdapter } from "./progress-adapter-xASh41wr.mjs";
5
+ import { a as ContractValidationError, t as createControlClient } from "./client-5uvDppD8.mjs";
6
+ import { c as formatVerifyOutput, i as formatSchemaVerifyOutput, r as formatSchemaVerifyJson, s as formatVerifyJson } from "./verify-DOHbbrub.mjs";
8
7
  import { Command } from "commander";
9
8
  import { ifDefined } from "@prisma-next/utils/defined";
10
9
  import { notOk, ok } from "@prisma-next/utils/result";
@@ -400,4 +399,4 @@ function createDbVerifyCommand() {
400
399
  //#endregion
401
400
  export { createDbVerifyCommand as t };
402
401
 
403
- //# sourceMappingURL=db-verify-AoIUriL4.mjs.map
402
+ //# sourceMappingURL=db-verify-BWl1Yxi-.mjs.map