@prisma-next/cli 0.5.0-dev.2 → 0.5.0-dev.21

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 (153) hide show
  1. package/README.md +54 -21
  2. package/dist/agent-skill-mongo.md +63 -31
  3. package/dist/agent-skill-postgres.md +1 -1
  4. package/dist/{cli-errors-C0JhVj0c.d.mts → cli-errors-BJLUczXT.d.mts} +1 -0
  5. package/dist/cli-errors-By1iVE3z.mjs +34 -0
  6. package/dist/cli-errors-By1iVE3z.mjs.map +1 -0
  7. package/dist/cli.mjs +127 -13
  8. package/dist/cli.mjs.map +1 -1
  9. package/dist/{client-TG7rbCWT.mjs → client-enZIahga.mjs} +20 -5
  10. package/dist/client-enZIahga.mjs.map +1 -0
  11. package/dist/commands/contract-emit.d.mts.map +1 -1
  12. package/dist/commands/contract-emit.mjs +7 -2
  13. package/dist/commands/contract-infer.mjs +8 -2
  14. package/dist/commands/db-init.mjs +9 -8
  15. package/dist/commands/db-init.mjs.map +1 -1
  16. package/dist/commands/db-schema.mjs +8 -5
  17. package/dist/commands/db-schema.mjs.map +1 -1
  18. package/dist/commands/db-sign.mjs +8 -7
  19. package/dist/commands/db-sign.mjs.map +1 -1
  20. package/dist/commands/db-update.mjs +9 -8
  21. package/dist/commands/db-update.mjs.map +1 -1
  22. package/dist/commands/db-verify.mjs +10 -9
  23. package/dist/commands/db-verify.mjs.map +1 -1
  24. package/dist/commands/migration-apply.d.mts +1 -1
  25. package/dist/commands/migration-apply.d.mts.map +1 -1
  26. package/dist/commands/migration-apply.mjs +15 -38
  27. package/dist/commands/migration-apply.mjs.map +1 -1
  28. package/dist/commands/migration-new.d.mts.map +1 -1
  29. package/dist/commands/migration-new.mjs +24 -28
  30. package/dist/commands/migration-new.mjs.map +1 -1
  31. package/dist/commands/migration-plan.d.mts +6 -3
  32. package/dist/commands/migration-plan.d.mts.map +1 -1
  33. package/dist/commands/migration-plan.mjs +38 -38
  34. package/dist/commands/migration-plan.mjs.map +1 -1
  35. package/dist/commands/migration-ref.d.mts +6 -4
  36. package/dist/commands/migration-ref.d.mts.map +1 -1
  37. package/dist/commands/migration-ref.mjs +31 -40
  38. package/dist/commands/migration-ref.mjs.map +1 -1
  39. package/dist/commands/migration-show.d.mts +4 -4
  40. package/dist/commands/migration-show.d.mts.map +1 -1
  41. package/dist/commands/migration-show.mjs +19 -26
  42. package/dist/commands/migration-show.mjs.map +1 -1
  43. package/dist/commands/migration-status.d.mts +5 -4
  44. package/dist/commands/migration-status.d.mts.map +1 -1
  45. package/dist/commands/migration-status.mjs +7 -2
  46. package/dist/{config-loader-_W4T21X1.mjs → config-loader-ih8ViDb_.mjs} +2 -2
  47. package/dist/config-loader-ih8ViDb_.mjs.map +1 -0
  48. package/dist/config-loader.mjs +1 -1
  49. package/dist/contract-emit-DS5NzZh2.mjs +6 -0
  50. package/dist/contract-emit-DWtGQYCD.mjs +150 -0
  51. package/dist/contract-emit-DWtGQYCD.mjs.map +1 -0
  52. package/dist/contract-emit-RZBWzkop.mjs +329 -0
  53. package/dist/contract-emit-RZBWzkop.mjs.map +1 -0
  54. package/dist/{contract-enrichment-CGW6mm-E.mjs → contract-enrichment-4Ptgw3Pe.mjs} +1 -1
  55. package/dist/{contract-enrichment-CGW6mm-E.mjs.map → contract-enrichment-4Ptgw3Pe.mjs.map} +1 -1
  56. package/dist/{contract-infer-BP3DrGgz.mjs → contract-infer-BjzkcwQt.mjs} +5 -5
  57. package/dist/{contract-infer-BP3DrGgz.mjs.map → contract-infer-BjzkcwQt.mjs.map} +1 -1
  58. package/dist/exports/control-api.d.mts +41 -16
  59. package/dist/exports/control-api.d.mts.map +1 -1
  60. package/dist/exports/control-api.mjs +7 -5
  61. package/dist/exports/index.mjs +8 -3
  62. package/dist/exports/index.mjs.map +1 -1
  63. package/dist/exports/init-output.d.mts +39 -0
  64. package/dist/exports/init-output.d.mts.map +1 -0
  65. package/dist/exports/init-output.mjs +3 -0
  66. package/dist/{extract-operation-statements-DZUJNmL3.mjs → extract-operation-statements-CU-Pp4-N.mjs} +2 -2
  67. package/dist/{extract-operation-statements-DZUJNmL3.mjs.map → extract-operation-statements-CU-Pp4-N.mjs.map} +1 -1
  68. package/dist/{extract-sql-ddl-DDMX-9mz.mjs → extract-sql-ddl-Bm0Mm0IT.mjs} +1 -1
  69. package/dist/{extract-sql-ddl-DDMX-9mz.mjs.map → extract-sql-ddl-Bm0Mm0IT.mjs.map} +1 -1
  70. package/dist/{framework-components-DfZKQBQ2.mjs → framework-components-Bgcre3Z6.mjs} +2 -2
  71. package/dist/{framework-components-DfZKQBQ2.mjs.map → framework-components-Bgcre3Z6.mjs.map} +1 -1
  72. package/dist/init-C-H-if1m.mjs +2062 -0
  73. package/dist/init-C-H-if1m.mjs.map +1 -0
  74. package/dist/{inspect-live-schema-DWzf4Q_m.mjs → inspect-live-schema-QklSDLt_.mjs} +6 -6
  75. package/dist/{inspect-live-schema-DWzf4Q_m.mjs.map → inspect-live-schema-QklSDLt_.mjs.map} +1 -1
  76. package/dist/migration-cli.mjs +15 -8
  77. package/dist/migration-cli.mjs.map +1 -1
  78. package/dist/{migration-command-scaffold-CLMD302g.mjs → migration-command-scaffold-BfloSWPZ.mjs} +7 -7
  79. package/dist/{migration-command-scaffold-CLMD302g.mjs.map → migration-command-scaffold-BfloSWPZ.mjs.map} +1 -1
  80. package/dist/{migration-status-B0HLF7So.mjs → migration-status-C5VYA5r9.mjs} +21 -35
  81. package/dist/migration-status-C5VYA5r9.mjs.map +1 -0
  82. package/dist/{migrations-B0dOQlk0.mjs → migrations-CSaDHNpB.mjs} +3 -3
  83. package/dist/migrations-CSaDHNpB.mjs.map +1 -0
  84. package/dist/output-BiO7kt87.mjs +103 -0
  85. package/dist/output-BiO7kt87.mjs.map +1 -0
  86. package/dist/{progress-adapter-B-YvmcDu.mjs → progress-adapter-DgRGldpT.mjs} +1 -1
  87. package/dist/{progress-adapter-B-YvmcDu.mjs.map → progress-adapter-DgRGldpT.mjs.map} +1 -1
  88. package/dist/quick-reference-mongo.md +34 -13
  89. package/dist/quick-reference-postgres.md +11 -9
  90. package/dist/{result-handler-CIyu0Pdt.mjs → result-handler-BmVh8AeV.mjs} +12 -93
  91. package/dist/result-handler-BmVh8AeV.mjs.map +1 -0
  92. package/dist/{terminal-ui-C5k88MmW.mjs → terminal-ui-u2YgKghu.mjs} +76 -2
  93. package/dist/terminal-ui-u2YgKghu.mjs.map +1 -0
  94. package/dist/{verify-BxiVp50b.mjs → verify-BumcH6Ry.mjs} +2 -2
  95. package/dist/{verify-BxiVp50b.mjs.map → verify-BumcH6Ry.mjs.map} +1 -1
  96. package/package.json +20 -15
  97. package/src/commands/contract-emit.ts +67 -163
  98. package/src/commands/init/detect-pnpm-catalog.ts +141 -0
  99. package/src/commands/init/errors.ts +254 -0
  100. package/src/commands/init/exit-codes.ts +62 -0
  101. package/src/commands/init/hygiene-gitattributes.ts +97 -0
  102. package/src/commands/init/hygiene-gitignore.ts +48 -0
  103. package/src/commands/init/hygiene-package-scripts.ts +91 -0
  104. package/src/commands/init/index.ts +112 -7
  105. package/src/commands/init/init.ts +766 -144
  106. package/src/commands/init/inputs.ts +421 -0
  107. package/src/commands/init/output.ts +147 -0
  108. package/src/commands/init/probe-db.ts +308 -0
  109. package/src/commands/init/reinit-cleanup.ts +83 -0
  110. package/src/commands/init/templates/agent-skill-mongo.md +63 -31
  111. package/src/commands/init/templates/agent-skill-postgres.md +1 -1
  112. package/src/commands/init/templates/agent-skill.ts +25 -3
  113. package/src/commands/init/templates/code-templates.ts +125 -32
  114. package/src/commands/init/templates/env.ts +80 -0
  115. package/src/commands/init/templates/quick-reference-mongo.md +34 -13
  116. package/src/commands/init/templates/quick-reference-postgres.md +11 -9
  117. package/src/commands/init/templates/quick-reference.ts +42 -3
  118. package/src/commands/init/templates/tsconfig.ts +167 -5
  119. package/src/commands/migration-apply.ts +15 -50
  120. package/src/commands/migration-new.ts +24 -28
  121. package/src/commands/migration-plan.ts +58 -42
  122. package/src/commands/migration-ref.ts +40 -54
  123. package/src/commands/migration-show.ts +27 -28
  124. package/src/commands/migration-status.ts +33 -50
  125. package/src/config-path-validation.ts +0 -1
  126. package/src/control-api/operations/contract-emit.ts +198 -115
  127. package/src/control-api/operations/migration-apply.ts +15 -0
  128. package/src/control-api/types.ts +22 -3
  129. package/src/exports/control-api.ts +2 -1
  130. package/src/exports/init-output.ts +10 -0
  131. package/src/migration-cli.ts +16 -9
  132. package/src/utils/cli-errors.ts +45 -1
  133. package/src/utils/command-helpers.ts +13 -26
  134. package/src/utils/emit-queue.ts +26 -0
  135. package/src/utils/formatters/graph-migration-mapper.ts +2 -2
  136. package/src/utils/formatters/migrations.ts +2 -2
  137. package/src/utils/publish-contract-artifact-pair.ts +134 -0
  138. package/dist/cli-errors-DHq6GQGu.mjs +0 -5
  139. package/dist/client-TG7rbCWT.mjs.map +0 -1
  140. package/dist/config-loader-_W4T21X1.mjs.map +0 -1
  141. package/dist/contract-emit-CNYyzJwF.mjs +0 -195
  142. package/dist/contract-emit-CNYyzJwF.mjs.map +0 -1
  143. package/dist/contract-emit-CQfj7xJn.mjs +0 -122
  144. package/dist/contract-emit-CQfj7xJn.mjs.map +0 -1
  145. package/dist/contract-emit-fhNwwhkQ.mjs +0 -4
  146. package/dist/init-CQfo_4Ro.mjs +0 -430
  147. package/dist/init-CQfo_4Ro.mjs.map +0 -1
  148. package/dist/migration-status-B0HLF7So.mjs.map +0 -1
  149. package/dist/migrations-B0dOQlk0.mjs.map +0 -1
  150. package/dist/result-handler-CIyu0Pdt.mjs.map +0 -1
  151. package/dist/terminal-ui-C5k88MmW.mjs.map +0 -1
  152. package/dist/validate-contract-deps-esa-VQ0h.mjs +0 -37
  153. package/dist/validate-contract-deps-esa-VQ0h.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-emit-CNYyzJwF.mjs","names":["lines: string[]","exhaustive: never","config: Awaited<ReturnType<typeof loadConfig>>","CliStructuredError","errorUnexpected","outputPaths: ReturnType<typeof getEmittedArtifactPaths>"],"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 { mkdirSync, writeFileSync } from 'node:fs';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { errorContractConfigMissing } from '@prisma-next/errors/control';\nimport { notOk, ok, type Result } from '@prisma-next/utils/result';\nimport { Command } from 'commander';\nimport { dirname, relative, resolve } from 'pathe';\nimport { loadConfig } from '../config-loader';\nimport { createControlClient } from '../control-api/client';\nimport type { EmitFailure } from '../control-api/types';\nimport {\n CliStructuredError,\n errorContractValidationFailed,\n errorRuntime,\n errorUnexpected,\n} 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, parseGlobalFlags } from '../utils/global-flags';\nimport { createProgressAdapter } from '../utils/progress-adapter';\nimport { handleResult } from '../utils/result-handler';\nimport { TerminalUI } from '../utils/terminal-ui';\n\ninterface ContractEmitOptions extends CommonCommandOptions {\n readonly config?: string;\n}\n\nfunction mapDiagnosticsToIssues(\n failure: EmitFailure,\n): ReadonlyArray<{ kind: string; message: string }> {\n const diagnostics = failure.diagnostics?.diagnostics ?? [];\n return diagnostics.map((diagnostic) => {\n const location =\n diagnostic.sourceId && diagnostic.span\n ? ` (${diagnostic.sourceId}:${diagnostic.span.start.line}:${diagnostic.span.start.column})`\n : diagnostic.sourceId\n ? ` (${diagnostic.sourceId})`\n : '';\n return {\n kind: diagnostic.code,\n message: `${diagnostic.message}${location}`,\n };\n });\n}\n\n/**\n * Maps an EmitFailure to a CliStructuredError for consistent error handling.\n */\nfunction mapEmitFailure(\n failure: EmitFailure,\n context?: { readonly configPath?: string },\n): CliStructuredError {\n if (failure.code === 'CONTRACT_SOURCE_INVALID') {\n const issues = mapDiagnosticsToIssues(failure);\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Contract source provider failed',\n fix: 'Check your contract source provider in prisma-next.config.ts and ensure it returns Result<Contract, Diagnostics>',\n ...(issues.length > 0 ? { meta: { issues } } : {}),\n });\n }\n\n if (failure.code === 'CONTRACT_VALIDATION_FAILED') {\n return errorContractValidationFailed(\n failure.why ?? 'Contract validation failed while emitting',\n context?.configPath ? { where: { path: context.configPath } } : undefined,\n );\n }\n\n if (failure.code === 'EMIT_FAILED') {\n return errorRuntime(failure.summary, {\n why: failure.why ?? 'Failed to emit contract',\n fix: 'Check your contract configuration and ensure the source is valid',\n });\n }\n\n // Exhaustive check - TypeScript will error if a new code is added but not handled\n const exhaustive: never = failure.code;\n throw new Error(`Unhandled EmitFailure code: ${exhaustive}`);\n}\n\n/**\n * Executes the contract emit command and returns a structured Result.\n */\nasync function executeContractEmitCommand(\n options: ContractEmitOptions,\n flags: GlobalFlags,\n ui: TerminalUI,\n startTime: number,\n): Promise<Result<EmitContractResult, CliStructuredError>> {\n // Load config\n let config: Awaited<ReturnType<typeof loadConfig>>;\n try {\n config = await loadConfig(options.config);\n } catch (error) {\n // Convert thrown CliStructuredError to Result\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 configPath = options.config\n ? relative(process.cwd(), resolve(options.config))\n : 'prisma-next.config.ts';\n\n // Resolve contract from config\n if (!config.contract) {\n return notOk(\n errorContractConfigMissing({\n why: 'Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }',\n }),\n );\n }\n\n // Contract config is already normalized by defineConfig() with defaults applied\n const contractConfig = config.contract;\n\n // Resolve artifact paths from config (already normalized by defineConfig() with defaults)\n if (!contractConfig.output) {\n return notOk(\n errorContractConfigMissing({\n why: 'Contract config must have output path. This should not happen if defineConfig() was used.',\n }),\n );\n }\n let outputPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n outputPaths = getEmittedArtifactPaths(contractConfig.output);\n } catch (error) {\n return notOk(\n errorContractConfigMissing({\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n }\n const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;\n\n // Output header to stderr (decoration)\n if (!flags.json && !flags.quiet) {\n const contractPath = relative(process.cwd(), outputJsonPath);\n const typesPath = relative(process.cwd(), outputDtsPath);\n const header = formatStyledHeader({\n command: 'contract emit',\n description: 'Emit your contract artifacts',\n url: 'https://pris.ly/contract-emit',\n details: [\n { label: 'config', value: configPath },\n { label: 'contract', value: contractPath },\n { label: 'types', value: typesPath },\n ],\n flags,\n });\n ui.stderr(header);\n }\n\n // Create control client (no driver needed for emit)\n const client = createControlClient({\n family: config.family,\n target: config.target,\n adapter: config.adapter,\n extensionPacks: config.extensionPacks ?? [],\n });\n\n // Create progress adapter\n const onProgress = createProgressAdapter({ ui, flags });\n\n try {\n // Call emit with progress callback\n const result = await client.emit({\n contractConfig: {\n source: contractConfig.source,\n output: outputJsonPath,\n },\n onProgress,\n });\n\n // Handle failures by mapping to CLI structured error\n if (!result.ok) {\n return notOk(mapEmitFailure(result.failure, { configPath }));\n }\n\n // Create directories if needed\n mkdirSync(dirname(outputJsonPath), { recursive: true });\n mkdirSync(dirname(outputDtsPath), { recursive: true });\n\n // Write the results to files\n writeFileSync(outputJsonPath, result.value.contractJson, 'utf-8');\n writeFileSync(outputDtsPath, result.value.contractDts, 'utf-8');\n\n // Validate that contract.d.ts type imports are resolvable\n const { validateContractDeps } = await import('../utils/validate-contract-deps');\n const depsValidation = validateContractDeps(result.value.contractDts, dirname(outputDtsPath));\n if (depsValidation.warning) {\n ui.warn(depsValidation.warning);\n }\n\n // Convert success result to CLI output format\n const emitResult: EmitContractResult = {\n storageHash: result.value.storageHash,\n ...(result.value.executionHash ? { executionHash: result.value.executionHash } : {}),\n profileHash: result.value.profileHash,\n outDir: dirname(outputJsonPath),\n files: {\n json: outputJsonPath,\n dts: outputDtsPath,\n },\n timings: { total: Date.now() - startTime },\n };\n\n return ok(emitResult);\n } catch (error) {\n // Use static type guard to work across module boundaries\n if (CliStructuredError.is(error)) {\n return notOk(error);\n }\n\n // Wrap unexpected errors\n return notOk(\n errorUnexpected('Unexpected error during contract emit', {\n why: error instanceof Error ? error.message : String(error),\n }),\n );\n } finally {\n await client.close();\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 ]);\n addGlobalOptions(command)\n .option('--config <path>', 'Path to prisma-next.config.ts')\n .action(async (options: ContractEmitOptions) => {\n const flags = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const startTime = Date.now();\n\n const result = await executeContractEmitCommand(options, flags, ui, startTime);\n\n // Handle result - formats output and returns exit code\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;AACvF,KAAI,MAAM,MACR,QAAO;CAGT,MAAMA,QAAkB,EAAE;CAG1B,MAAM,WAAW,SAAS,QAAQ,KAAK,EAAE,OAAO,MAAM,KAAK;CAC3D,MAAM,UAAU,SAAS,QAAQ,KAAK,EAAE,OAAO,MAAM,IAAI;AAEzD,OAAM,KAAK,6BAA6B,WAAW;AACnD,OAAM,KAAK,6BAA6B,UAAU;AAClD,OAAM,KAAK,kBAAkB,OAAO,cAAc;AAClD,KAAI,OAAO,cACT,OAAM,KAAK,oBAAoB,OAAO,gBAAgB;AAExD,KAAI,OAAO,YACT,OAAM,KAAK,kBAAkB,OAAO,cAAc;AAEpD,KAAI,UAAU,OAAO,EAAE,CACrB,OAAM,KAAK,iBAAi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,CAAC;AACF,kBAAiB,QAAQ,CACtB,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,OAAO,YAAiC;EAC9C,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;EAMjF,MAAM,WAAW,aAHF,MAAM,2BAA2B,SAAS,OAAO,IAF9C,KAAK,KAAK,CAEkD,EAGxC,OAAO,KAAK,eAAe;AAC/D,OAAI,MAAM,KACR,IAAG,OAAO,eAAe,WAAW,CAAC;QAChC;IACL,MAAM,SAAS,iBAAiB,YAAY,MAAM;AAClD,QAAI,OACF,IAAG,IAAI,OAAO;AAEhB,QAAI,CAAC,MAAM,MACT,IAAG,QAAQ,qBAAqB,MAAM,CAAC;;IAG3C;AACF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
@@ -1,122 +0,0 @@
1
- import { t as loadConfig } from "./config-loader-_W4T21X1.mjs";
2
- import { i as errorContractConfigMissing, m as errorRuntime } from "./cli-errors-DHq6GQGu.mjs";
3
- import { t as assertFrameworkComponentsCompatible } from "./framework-components-DfZKQBQ2.mjs";
4
- import { t as enrichContract } from "./contract-enrichment-CGW6mm-E.mjs";
5
- import { emit, getEmittedArtifactPaths } from "@prisma-next/emitter";
6
- import { dirname } from "pathe";
7
- import { ifDefined } from "@prisma-next/utils/defined";
8
- import { createControlStack } from "@prisma-next/framework-components/control";
9
- import { mkdir, writeFile } from "node:fs/promises";
10
- import { abortable } from "@prisma-next/utils/abortable";
11
-
12
- //#region src/control-api/operations/contract-emit.ts
13
- function isRecord(value) {
14
- return typeof value === "object" && value !== null;
15
- }
16
- function isAbortError(error) {
17
- return isRecord(error) && typeof error["name"] === "string" && error["name"] === "AbortError";
18
- }
19
- function isProviderFailureLike(value) {
20
- return isRecord(value) && typeof value["summary"] === "string" && Array.isArray(value["diagnostics"]);
21
- }
22
- /**
23
- * Executes the contract emit operation.
24
- *
25
- * This is an offline operation that:
26
- * 1. Loads the Prisma Next config from the specified path
27
- * 2. Resolves the contract source from config
28
- * 3. Creates a control plane stack and family instance
29
- * 4. Emits contract artifacts (JSON and DTS)
30
- * 5. Writes files to the paths specified in config
31
- *
32
- * Supports AbortSignal for cancellation, enabling "last change wins" behavior.
33
- *
34
- * @param options - Options including configPath and optional signal
35
- * @returns File paths and hashes of emitted artifacts
36
- * @throws If config loading fails, contract is invalid, or file I/O fails
37
- * @throws signal.reason if cancelled via AbortSignal (typically DOMException with name 'AbortError')
38
- */
39
- async function executeContractEmit(options) {
40
- const { configPath, signal = new AbortController().signal } = options;
41
- const unlessAborted = abortable(signal);
42
- const config = await unlessAborted(loadConfig(configPath));
43
- if (!config.contract) throw errorContractConfigMissing({ why: "Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }" });
44
- const contractConfig = config.contract;
45
- if (!contractConfig.output) throw errorContractConfigMissing({ why: "Contract config must have output path. This should not happen if defineConfig() was used." });
46
- if (typeof contractConfig.source?.load !== "function") throw errorContractConfigMissing({ why: "Contract config must include a valid source provider object" });
47
- let outputPaths;
48
- try {
49
- outputPaths = getEmittedArtifactPaths(contractConfig.output);
50
- } catch (error) {
51
- throw errorContractConfigMissing({ why: error instanceof Error ? error.message : String(error) });
52
- }
53
- const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;
54
- const stack = createControlStack(config);
55
- const sourceContext = {
56
- composedExtensionPacks: stack.extensionPacks.map((p) => p.id),
57
- scalarTypeDescriptors: stack.scalarTypeDescriptors,
58
- authoringContributions: stack.authoringContributions,
59
- codecLookup: stack.codecLookup,
60
- controlMutationDefaults: stack.controlMutationDefaults,
61
- resolvedInputs: contractConfig.source.inputs ?? []
62
- };
63
- let providerResult;
64
- try {
65
- providerResult = await unlessAborted(contractConfig.source.load(sourceContext));
66
- } catch (error) {
67
- if (signal.aborted || isAbortError(error)) throw error;
68
- throw errorRuntime("Failed to resolve contract source", {
69
- why: error instanceof Error ? error.message : String(error),
70
- fix: "Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics."
71
- });
72
- }
73
- if (!isRecord(providerResult) || typeof providerResult.ok !== "boolean") throw errorRuntime("Failed to resolve contract source", {
74
- why: "Contract source provider returned malformed result shape.",
75
- fix: "Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics })."
76
- });
77
- if (providerResult.ok && !("value" in providerResult)) throw errorRuntime("Failed to resolve contract source", {
78
- why: "Contract source provider returned malformed success result: missing value.",
79
- fix: "Ensure contract.source.load success payload is ok(Contract)."
80
- });
81
- if (!providerResult.ok && !isProviderFailureLike(providerResult.failure)) throw errorRuntime("Failed to resolve contract source", {
82
- why: "Contract source provider returned malformed failure result: expected summary and diagnostics.",
83
- fix: "Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? })."
84
- });
85
- if (!providerResult.ok) throw errorRuntime("Failed to resolve contract source", {
86
- why: providerResult.failure.summary,
87
- fix: "Fix contract source diagnostics and return ok(Contract).",
88
- meta: {
89
- diagnostics: providerResult.failure.diagnostics,
90
- ...ifDefined("providerMeta", providerResult.failure.meta)
91
- }
92
- });
93
- const familyInstance = config.family.create(stack);
94
- const rawComponents = [
95
- config.target,
96
- config.adapter,
97
- ...config.extensionPacks ?? []
98
- ];
99
- const frameworkComponents = assertFrameworkComponentsCompatible(config.family.familyId, config.target.targetId, rawComponents);
100
- const enrichedIR = enrichContract(providerResult.value, frameworkComponents);
101
- familyInstance.validateContract(enrichedIR);
102
- const emitResult = await unlessAborted(emit(enrichedIR, stack, config.family.emission, { outputJsonPath }));
103
- await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));
104
- await unlessAborted(writeFile(outputJsonPath, emitResult.contractJson, "utf-8"));
105
- await unlessAborted(writeFile(outputDtsPath, emitResult.contractDts, "utf-8"));
106
- const { validateContractDeps } = await import("./validate-contract-deps-esa-VQ0h.mjs");
107
- const depsValidation = validateContractDeps(emitResult.contractDts, dirname(outputDtsPath));
108
- if (depsValidation.warning) process.stderr.write(`\n⚠ ${depsValidation.warning}\n`);
109
- return {
110
- storageHash: emitResult.storageHash,
111
- ...ifDefined("executionHash", emitResult.executionHash),
112
- profileHash: emitResult.profileHash,
113
- files: {
114
- json: outputJsonPath,
115
- dts: outputDtsPath
116
- }
117
- };
118
- }
119
-
120
- //#endregion
121
- export { executeContractEmit as t };
122
- //# sourceMappingURL=contract-emit-CQfj7xJn.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"contract-emit-CQfj7xJn.mjs","names":["outputPaths: ReturnType<typeof getEmittedArtifactPaths>","providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>"],"sources":["../src/control-api/operations/contract-emit.ts"],"sourcesContent":["import { mkdir, writeFile } 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 { dirname } from 'pathe';\nimport { loadConfig } from '../../config-loader';\nimport { errorContractConfigMissing, errorRuntime } from '../../utils/cli-errors';\nimport { assertFrameworkComponentsCompatible } from '../../utils/framework-components';\nimport { enrichContract } from '../contract-enrichment';\nimport type { ContractEmitOptions, ContractEmitResult } from '../types';\n\ninterface ProviderFailureLike {\n readonly summary: string;\n readonly diagnostics: readonly unknown[];\n readonly meta?: unknown;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return isRecord(error) && typeof error['name'] === 'string' && error['name'] === 'AbortError';\n}\n\nfunction isProviderFailureLike(value: unknown): value is ProviderFailureLike {\n return (\n isRecord(value) && typeof value['summary'] === 'string' && Array.isArray(value['diagnostics'])\n );\n}\n\n/**\n * Executes the contract emit operation.\n *\n * This is an offline operation that:\n * 1. Loads the Prisma Next config from the specified path\n * 2. Resolves the contract source from config\n * 3. Creates a control plane stack and family instance\n * 4. Emits contract artifacts (JSON and DTS)\n * 5. Writes files to the paths specified in config\n *\n * Supports AbortSignal for cancellation, enabling \"last change wins\" behavior.\n *\n * @param options - Options including configPath and optional signal\n * @returns File paths and hashes of emitted artifacts\n * @throws If config loading fails, contract is invalid, or file I/O fails\n * @throws signal.reason if cancelled via AbortSignal (typically DOMException with name 'AbortError')\n */\nexport async function executeContractEmit(\n options: ContractEmitOptions,\n): Promise<ContractEmitResult> {\n const { configPath, signal = new AbortController().signal } = options;\n const unlessAborted = abortable(signal);\n\n // Load config using the existing config loader\n const config = await unlessAborted(loadConfig(configPath));\n\n // Validate contract config is present\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 // Validate output path is present and ends with .json\n if (!contractConfig.output) {\n throw errorContractConfigMissing({\n why: 'Contract config must have output path. This should not happen if defineConfig() was used.',\n });\n }\n\n // Validate source exists and is callable\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(contractConfig.output);\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 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 let providerResult: Awaited<ReturnType<typeof contractConfig.source.load>>;\n try {\n providerResult = await unlessAborted(contractConfig.source.load(sourceContext));\n } catch (error) {\n if (signal.aborted || isAbortError(error)) {\n throw error;\n }\n throw errorRuntime('Failed to resolve contract source', {\n why: error instanceof Error ? error.message : String(error),\n fix: 'Ensure contract.source.load resolves to ok(Contract) or returns structured diagnostics.',\n });\n }\n\n if (!isRecord(providerResult) || typeof providerResult.ok !== 'boolean') {\n throw errorRuntime('Failed to resolve contract source', {\n why: 'Contract source provider returned malformed result shape.',\n fix: 'Ensure contract.source.load resolves to ok(Contract) or notOk({ summary, diagnostics }).',\n });\n }\n\n if (providerResult.ok && !('value' in providerResult)) {\n throw errorRuntime('Failed to resolve contract source', {\n why: 'Contract source provider returned malformed success result: missing value.',\n fix: 'Ensure contract.source.load success payload is ok(Contract).',\n });\n }\n\n if (!providerResult.ok && !isProviderFailureLike(providerResult.failure)) {\n throw errorRuntime('Failed to resolve contract source', {\n why: 'Contract source provider returned malformed failure result: expected summary and diagnostics.',\n fix: 'Ensure contract.source.load failure payload is notOk({ summary, diagnostics, meta? }).',\n });\n }\n\n if (!providerResult.ok) {\n throw errorRuntime('Failed to resolve contract source', {\n why: providerResult.failure.summary,\n fix: 'Fix contract source diagnostics and return ok(Contract).',\n meta: {\n diagnostics: providerResult.failure.diagnostics,\n ...ifDefined('providerMeta', providerResult.failure.meta),\n },\n });\n }\n\n const familyInstance = config.family.create(stack);\n\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 const enrichedIR = enrichContract(providerResult.value as Contract, frameworkComponents);\n\n familyInstance.validateContract(enrichedIR);\n const emitResult = await unlessAborted(\n emit(enrichedIR, stack, config.family.emission, {\n outputJsonPath: outputJsonPath,\n }),\n );\n\n // Create directory if needed and write files (both colocated)\n await unlessAborted(mkdir(dirname(outputJsonPath), { recursive: true }));\n await unlessAborted(writeFile(outputJsonPath, emitResult.contractJson, 'utf-8'));\n await unlessAborted(writeFile(outputDtsPath, emitResult.contractDts, 'utf-8'));\n\n // Validate that contract.d.ts type imports are resolvable\n const { validateContractDeps } = await import('../../utils/validate-contract-deps');\n const depsValidation = validateContractDeps(emitResult.contractDts, dirname(outputDtsPath));\n if (depsValidation.warning) {\n process.stderr.write(`\\n⚠ ${depsValidation.warning}\\n`);\n }\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 };\n}\n"],"mappings":";;;;;;;;;;;;AAmBA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,SAAS,aAAa,OAAyB;AAC7C,QAAO,SAAS,MAAM,IAAI,OAAO,MAAM,YAAY,YAAY,MAAM,YAAY;;AAGnF,SAAS,sBAAsB,OAA8C;AAC3E,QACE,SAAS,MAAM,IAAI,OAAO,MAAM,eAAe,YAAY,MAAM,QAAQ,MAAM,eAAe;;;;;;;;;;;;;;;;;;;AAqBlG,eAAsB,oBACpB,SAC6B;CAC7B,MAAM,EAAE,YAAY,SAAS,IAAI,iBAAiB,CAAC,WAAW;CAC9D,MAAM,gBAAgB,UAAU,OAAO;CAGvC,MAAM,SAAS,MAAM,cAAc,WAAW,WAAW,CAAC;AAG1D,KAAI,CAAC,OAAO,SACV,OAAM,2BAA2B,EAC/B,KAAK,0GACN,CAAC;CAGJ,MAAM,iBAAiB,OAAO;AAG9B,KAAI,CAAC,eAAe,OAClB,OAAM,2BAA2B,EAC/B,KAAK,6FACN,CAAC;AAIJ,KAAI,OAAO,eAAe,QAAQ,SAAS,WACzC,OAAM,2BAA2B,EAC/B,KAAK,+DACN,CAAC;CAGJ,IAAIA;AACJ,KAAI;AACF,gBAAc,wBAAwB,eAAe,OAAO;UACrD,OAAO;AACd,QAAM,2BAA2B,EAC/B,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EAC5D,CAAC;;CAEJ,MAAM,EAAE,UAAU,gBAAgB,SAAS,kBAAkB;CAE7D,MAAM,QAAQ,mBAAmB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iB,WAAW;CAC3C,MAAM,aAAa,MAAM,cACvB,KAAK,YAAY,OAAO,OAAO,OAAO,UAAU,EAC9B,gBACjB,CAAC,CACH;AAGD,OAAM,cAAc,MAAM,QAAQ,eAAe,EAAE,EAAE,WAAW,MAAM,CAAC,CAAC;AACxE,OAAM,cAAc,UAAU,gBAAgB,WAAW,cAAc,QAAQ,CAAC;AAChF,OAAM,cAAc,UAAU,eAAe,WAAW,aAAa,QAAQ,CAAC;CAG9E,MAAM,EAAE,yBAAyB,MAAM,OAAO;CAC9C,MAAM,iBAAiB,qBAAqB,WAAW,aAAa,QAAQ,cAAc,CAAC;AAC3F,KAAI,eAAe,QACjB,SAAQ,OAAO,MAAM,OAAO,eAAe,QAAQ,IAAI;AAGzD,QAAO;EACL,aAAa,WAAW;EACxB,GAAG,UAAU,iBAAiB,WAAW,cAAc;EACvD,aAAa,WAAW;EACxB,OAAO;GACL,MAAM;GACN,KAAK;GACN;EACF"}
@@ -1,4 +0,0 @@
1
- import "./config-loader-_W4T21X1.mjs";
2
- import { t as executeContractEmit } from "./contract-emit-CQfj7xJn.mjs";
3
-
4
- export { executeContractEmit };
@@ -1,430 +0,0 @@
1
- import { t as TerminalUI } from "./terminal-ui-C5k88MmW.mjs";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname, extname, isAbsolute, join, normalize } from "pathe";
4
- import * as clack from "@clack/prompts";
5
- import { execFile } from "node:child_process";
6
- import { promisify } from "node:util";
7
- import { detect } from "package-manager-detector/detect";
8
-
9
- //#region src/commands/init/detect-package-manager.ts
10
- const KNOWN = new Set([
11
- "pnpm",
12
- "npm",
13
- "yarn",
14
- "bun",
15
- "deno"
16
- ]);
17
- async function detectPackageManager(cwd) {
18
- const result = await detect({ cwd });
19
- if (result && KNOWN.has(result.name)) return result.name;
20
- return "npm";
21
- }
22
- function hasProjectManifest(cwd) {
23
- return existsSync(join(cwd, "package.json")) || existsSync(join(cwd, "deno.json")) || existsSync(join(cwd, "deno.jsonc"));
24
- }
25
- function formatRunCommand(pm, bin, args) {
26
- if (pm === "npm") return `npx ${bin} ${args}`;
27
- if (pm === "deno") return `deno run npm:${bin} ${args}`;
28
- return `${pm} ${bin} ${args}`;
29
- }
30
- function formatAddArgs(pm, packages) {
31
- if (pm === "deno") return ["add", ...packages.map((p) => `npm:${p}`)];
32
- return ["add", ...packages];
33
- }
34
- function formatAddDevArgs(pm, packages) {
35
- if (pm === "deno") return [
36
- "add",
37
- "--dev",
38
- ...packages.map((p) => `npm:${p}`)
39
- ];
40
- return [
41
- "add",
42
- "-D",
43
- ...packages
44
- ];
45
- }
46
-
47
- //#endregion
48
- //#region src/commands/init/templates/render.ts
49
- function renderTemplate(templateFile, variableNames, vars) {
50
- let result = readFileSync(join(import.meta.dirname, templateFile), "utf-8");
51
- for (const key of variableNames) {
52
- const value = vars[key];
53
- if (value === void 0) throw new Error(`Template variable '${key}' is not defined`);
54
- result = result.replaceAll(`{{${key}}}`, value);
55
- }
56
- return result;
57
- }
58
-
59
- //#endregion
60
- //#region src/commands/init/templates/agent-skill.ts
61
- const variables$1 = [
62
- "schemaPath",
63
- "schemaDir",
64
- "dbImportPath",
65
- "pkgRun"
66
- ];
67
- function agentSkillMd(target, schemaPath, pkgRun) {
68
- const schemaDir = dirname(schemaPath);
69
- const vars = {
70
- schemaPath,
71
- schemaDir,
72
- dbImportPath: `./${schemaDir}/db`,
73
- pkgRun
74
- };
75
- return renderTemplate(`agent-skill-${target}.md`, variables$1, vars);
76
- }
77
-
78
- //#endregion
79
- //#region src/commands/init/templates/code-templates.ts
80
- function targetPackageName(target) {
81
- return target === "postgres" ? "@prisma-next/postgres" : "@prisma-next/mongo";
82
- }
83
- function defaultSchemaPath(authoring) {
84
- if (authoring === "typescript") return "prisma/contract.ts";
85
- return "prisma/contract.prisma";
86
- }
87
- function starterSchema(target, authoring) {
88
- if (authoring === "typescript") return target === "mongo" ? starterSchemaTsMongo() : starterSchemaTsPostgres();
89
- return target === "mongo" ? starterSchemaPslMongo() : starterSchemaPslPostgres();
90
- }
91
- function starterSchemaPslPostgres() {
92
- return `model User {
93
- id Int @id @default(autoincrement())
94
- email String @unique
95
- name String?
96
- posts Post[]
97
- createdAt DateTime @default(now())
98
- }
99
-
100
- model Post {
101
- id Int @id @default(autoincrement())
102
- title String
103
- content String?
104
- author User @relation(fields: [authorId], references: [id])
105
- authorId Int
106
- createdAt DateTime @default(now())
107
- }
108
- `;
109
- }
110
- function starterSchemaPslMongo() {
111
- return `model User {
112
- id ObjectId @id @map("_id")
113
- email String @unique
114
- name String?
115
- posts Post[]
116
- @@map("users")
117
- }
118
-
119
- model Post {
120
- id ObjectId @id @map("_id")
121
- title String
122
- content String?
123
- author User @relation(fields: [authorId], references: [id])
124
- authorId ObjectId
125
- @@map("posts")
126
- }
127
- `;
128
- }
129
- function starterSchemaTsPostgres() {
130
- return `import sqlFamily from '@prisma-next/family-sql/pack';
131
- import { defineContract } from '@prisma-next/sql-contract-ts/contract-builder';
132
- import postgresPack from '@prisma-next/target-postgres/pack';
133
-
134
- export const contract = defineContract(
135
- { family: sqlFamily, target: postgresPack },
136
- ({ field, model, rel }) => ({
137
- models: {
138
- User: model('User', {
139
- fields: {
140
- id: field.id.uuidv7(),
141
- email: field.text().unique(),
142
- name: field.text().optional(),
143
- createdAt: field.createdAt(),
144
- },
145
- }).relations({
146
- posts: rel.hasMany('Post', { by: 'authorId' }),
147
- }),
148
-
149
- Post: model('Post', {
150
- fields: {
151
- id: field.id.uuidv7(),
152
- title: field.text(),
153
- content: field.text().optional(),
154
- authorId: field.uuid(),
155
- createdAt: field.createdAt(),
156
- },
157
- }).relations({
158
- author: rel.belongsTo('User', { from: 'authorId', to: 'id' }),
159
- }),
160
- },
161
- }),
162
- );
163
- `;
164
- }
165
- function starterSchemaTsMongo() {
166
- return `import mongoFamily from '@prisma-next/family-mongo/pack';
167
- import { defineContract, field, model, rel } from '@prisma-next/mongo-contract-ts/contract-builder';
168
- import mongoTarget from '@prisma-next/target-mongo/pack';
169
-
170
- const User = model('User', {
171
- collection: 'users',
172
- fields: {
173
- _id: field.objectId(),
174
- email: field.string(),
175
- name: field.string().optional(),
176
- },
177
- });
178
-
179
- const Post = model('Post', {
180
- collection: 'posts',
181
- fields: {
182
- _id: field.objectId(),
183
- title: field.string(),
184
- content: field.string().optional(),
185
- authorId: field.objectId(),
186
- },
187
- relations: {
188
- author: rel.belongsTo(User, { from: 'authorId', to: User.ref('_id') }),
189
- },
190
- });
191
-
192
- export const contract = defineContract({
193
- family: mongoFamily,
194
- target: mongoTarget,
195
- models: { User, Post },
196
- });
197
- `;
198
- }
199
- function configFile(target, contractPath) {
200
- return `import 'dotenv/config';
201
- import { defineConfig } from '${targetPackageName(target)}/config';
202
-
203
- export default defineConfig({
204
- contract: ${JSON.stringify(contractPath)},
205
- db: {
206
- connection: process.env['DATABASE_URL']!,
207
- },
208
- });
209
- `;
210
- }
211
- function dbFile(target) {
212
- if (target === "postgres") return `import postgres from '@prisma-next/postgres/runtime';
213
- import type { Contract } from './contract.d';
214
- import contractJson from './contract.json' with { type: 'json' };
215
-
216
- export const db = postgres<Contract>({ contractJson });
217
- `;
218
- return `import mongo from '@prisma-next/mongo/runtime';
219
- import type { Contract } from './contract.d';
220
- import contractJson from './contract.json' with { type: 'json' };
221
-
222
- export const db = mongo<Contract>({ contractJson });
223
- `;
224
- }
225
-
226
- //#endregion
227
- //#region src/commands/init/templates/quick-reference.ts
228
- const variables = [
229
- "schemaPath",
230
- "schemaDir",
231
- "dbImportPath",
232
- "pkgRun"
233
- ];
234
- function quickReferenceMd(target, schemaPath, pkgRun) {
235
- const schemaDir = dirname(schemaPath);
236
- const vars = {
237
- schemaPath,
238
- schemaDir,
239
- dbImportPath: `./${schemaDir}/db`,
240
- pkgRun
241
- };
242
- return renderTemplate(`quick-reference-${target}.md`, variables, vars);
243
- }
244
-
245
- //#endregion
246
- //#region src/commands/init/templates/tsconfig.ts
247
- const REQUIRED_COMPILER_OPTIONS = {
248
- module: "preserve",
249
- moduleResolution: "bundler",
250
- resolveJsonModule: true
251
- };
252
- function defaultTsConfig() {
253
- return JSON.stringify({
254
- compilerOptions: {
255
- target: "ES2022",
256
- ...REQUIRED_COMPILER_OPTIONS,
257
- strict: true,
258
- skipLibCheck: true,
259
- esModuleInterop: true,
260
- outDir: "dist"
261
- },
262
- include: ["**/*.ts"]
263
- }, null, 2);
264
- }
265
- function mergeTsConfig(existing) {
266
- const config = JSON.parse(existing);
267
- const compilerOptions = config["compilerOptions"] ?? {};
268
- for (const [key, value] of Object.entries(REQUIRED_COMPILER_OPTIONS)) compilerOptions[key] = value;
269
- config["compilerOptions"] = compilerOptions;
270
- return JSON.stringify(config, null, 2);
271
- }
272
-
273
- //#endregion
274
- //#region src/commands/init/init.ts
275
- async function runInit(baseDir, options) {
276
- const ui = new TerminalUI();
277
- clack.intro("prisma-next init", { output: process.stderr });
278
- if (!hasProjectManifest(baseDir)) {
279
- ui.error("No package.json or deno.json found. Initialize your project first (e.g. npm init or deno init), then re-run prisma-next init.");
280
- process.exit(1);
281
- }
282
- const pm = await detectPackageManager(baseDir);
283
- const pkgRun = formatRunCommand(pm, "prisma-next", "").trimEnd();
284
- if (existsSync(join(baseDir, "prisma-next.config.ts"))) {
285
- const reinit = await clack.confirm({
286
- message: "This project is already initialized. Re-initialize? This will overwrite all generated files.",
287
- initialValue: false,
288
- output: process.stderr
289
- });
290
- if (clack.isCancel(reinit) || !reinit) {
291
- clack.cancel("Init cancelled.", { output: process.stderr });
292
- process.exit(0);
293
- }
294
- }
295
- const targetResult = await clack.select({
296
- message: "What database are you using?",
297
- options: [{
298
- value: "postgres",
299
- label: "PostgreSQL"
300
- }, {
301
- value: "mongo",
302
- label: "MongoDB"
303
- }],
304
- output: process.stderr
305
- });
306
- if (clack.isCancel(targetResult)) {
307
- clack.cancel("Init cancelled.", { output: process.stderr });
308
- process.exit(0);
309
- }
310
- const target = targetResult;
311
- const authoringResult = await clack.select({
312
- message: "How do you want to write your schema?",
313
- options: [{
314
- value: "psl",
315
- label: "Prisma Schema Language (.prisma)"
316
- }, {
317
- value: "typescript",
318
- label: "TypeScript (.ts)"
319
- }],
320
- output: process.stderr
321
- });
322
- if (clack.isCancel(authoringResult)) {
323
- clack.cancel("Init cancelled.", { output: process.stderr });
324
- process.exit(0);
325
- }
326
- const authoring = authoringResult;
327
- const schemaPathResult = await clack.text({
328
- message: "Where should the schema file go?",
329
- initialValue: defaultSchemaPath(authoring),
330
- validate(value = "") {
331
- const trimmed = value.trim();
332
- if (trimmed.length === 0) return "Path cannot be empty";
333
- if (trimmed.endsWith("/") || trimmed.endsWith("\\")) return "Path must be a file, not a directory";
334
- if (!extname(trimmed)) return "Path must include a file extension (e.g. .prisma or .ts)";
335
- },
336
- output: process.stderr
337
- });
338
- if (clack.isCancel(schemaPathResult)) {
339
- clack.cancel("Init cancelled.", { output: process.stderr });
340
- process.exit(0);
341
- }
342
- const schemaPath = normalize(schemaPathResult.trim());
343
- const schemaDir = dirname(schemaPath);
344
- const configPath = isAbsolute(schemaPath) ? schemaPath : `./${schemaPath}`;
345
- const files = [
346
- {
347
- path: schemaPath,
348
- content: starterSchema(target, authoring)
349
- },
350
- {
351
- path: "prisma-next.config.ts",
352
- content: configFile(target, configPath)
353
- },
354
- {
355
- path: join(schemaDir, "db.ts"),
356
- content: dbFile(target)
357
- },
358
- {
359
- path: "prisma-next.md",
360
- content: quickReferenceMd(target, schemaPath, pkgRun)
361
- },
362
- {
363
- path: ".agents/skills/prisma-next/SKILL.md",
364
- content: agentSkillMd(target, schemaPath, pkgRun)
365
- }
366
- ];
367
- for (const file of files) {
368
- const fullPath = join(baseDir, file.path);
369
- mkdirSync(dirname(fullPath), { recursive: true });
370
- writeFileSync(fullPath, file.content, "utf-8");
371
- }
372
- const tsconfigPath = join(baseDir, "tsconfig.json");
373
- if (existsSync(tsconfigPath)) {
374
- writeFileSync(tsconfigPath, mergeTsConfig(readFileSync(tsconfigPath, "utf-8")), "utf-8");
375
- ui.log("Updated tsconfig.json with required compiler options.");
376
- } else writeFileSync(tsconfigPath, defaultTsConfig(), "utf-8");
377
- const emitCommand = formatRunCommand(pm, "prisma-next", "contract emit");
378
- if (options.noInstall) {
379
- const pkg = targetPackageName(target);
380
- ui.note([
381
- "Run the following commands to complete setup:",
382
- "",
383
- " 1. Install dependencies:",
384
- ` ${pm} ${formatAddArgs(pm, [pkg, "dotenv"]).join(" ")}`,
385
- ` ${pm} ${formatAddDevArgs(pm, ["prisma-next"]).join(" ")}`,
386
- "",
387
- " 2. Emit the contract:",
388
- ` ${emitCommand}`
389
- ].join("\n"), "Manual steps");
390
- } else {
391
- const pkg = targetPackageName(target);
392
- const spinner = ui.spinner();
393
- let installSucceeded = false;
394
- const exec = promisify(execFile);
395
- spinner.start(`Installing ${pkg}, dotenv, and prisma-next...`);
396
- try {
397
- await exec(pm, formatAddArgs(pm, [pkg, "dotenv"]), { cwd: baseDir });
398
- await exec(pm, formatAddDevArgs(pm, ["prisma-next"]), { cwd: baseDir });
399
- spinner.stop(`Installed ${pkg}, dotenv, and prisma-next`);
400
- installSucceeded = true;
401
- } catch (err) {
402
- spinner.stop("Installation failed");
403
- const stderr = err instanceof Error && "stderr" in err ? err.stderr : "";
404
- ui.warn([
405
- "Could not install dependencies automatically.",
406
- ...stderr ? [` ${stderr.trim()}`] : [],
407
- "",
408
- "Run manually:",
409
- ` ${pm} ${formatAddArgs(pm, [pkg, "dotenv"]).join(" ")}`,
410
- ` ${pm} ${formatAddDevArgs(pm, ["prisma-next"]).join(" ")}`
411
- ].join("\n"));
412
- }
413
- if (installSucceeded) {
414
- spinner.start("Emitting contract...");
415
- try {
416
- const { executeContractEmit } = await import("./contract-emit-fhNwwhkQ.mjs");
417
- await executeContractEmit({ configPath: join(baseDir, "prisma-next.config.ts") });
418
- spinner.stop("Contract emitted");
419
- } catch {
420
- spinner.stop("Contract emission failed");
421
- ui.warn(["Could not emit contract automatically. Run manually:", ` ${emitCommand}`].join("\n"));
422
- }
423
- }
424
- }
425
- clack.outro("Done! Open prisma-next.md to get started.", { output: process.stderr });
426
- }
427
-
428
- //#endregion
429
- export { runInit };
430
- //# sourceMappingURL=init-CQfo_4Ro.mjs.map