@prisma-next/cli 0.5.0-dev.3 → 0.5.0-dev.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -21
- package/dist/agent-skill-mongo.md +63 -31
- package/dist/agent-skill-postgres.md +1 -1
- package/dist/cli-errors-By1iVE3z.mjs +34 -0
- package/dist/cli-errors-By1iVE3z.mjs.map +1 -0
- package/dist/{cli-errors-C0JhVj0c.d.mts → cli-errors-DDeVsP2Y.d.mts} +1 -0
- package/dist/cli.mjs +131 -15
- package/dist/cli.mjs.map +1 -1
- package/dist/{client-TG7rbCWT.mjs → client-keSCAgjW.mjs} +43 -19
- package/dist/client-keSCAgjW.mjs.map +1 -0
- package/dist/commands/contract-emit.d.mts.map +1 -1
- package/dist/commands/contract-emit.mjs +7 -2
- package/dist/commands/contract-infer.d.mts.map +1 -1
- package/dist/commands/contract-infer.mjs +8 -2
- package/dist/commands/db-init.d.mts.map +1 -1
- package/dist/commands/db-init.mjs +11 -9
- package/dist/commands/db-init.mjs.map +1 -1
- package/dist/commands/db-schema.mjs +8 -5
- package/dist/commands/db-schema.mjs.map +1 -1
- package/dist/commands/db-sign.mjs +8 -7
- package/dist/commands/db-sign.mjs.map +1 -1
- package/dist/commands/db-update.mjs +10 -9
- package/dist/commands/db-update.mjs.map +1 -1
- package/dist/commands/db-verify.mjs +10 -9
- package/dist/commands/db-verify.mjs.map +1 -1
- package/dist/commands/migration-apply.d.mts +2 -2
- package/dist/commands/migration-apply.d.mts.map +1 -1
- package/dist/commands/migration-apply.mjs +15 -38
- package/dist/commands/migration-apply.mjs.map +1 -1
- package/dist/commands/migration-new.d.mts.map +1 -1
- package/dist/commands/migration-new.mjs +24 -30
- package/dist/commands/migration-new.mjs.map +1 -1
- package/dist/commands/migration-plan.d.mts +14 -5
- package/dist/commands/migration-plan.d.mts.map +1 -1
- package/dist/commands/migration-plan.mjs +45 -47
- package/dist/commands/migration-plan.mjs.map +1 -1
- package/dist/commands/migration-ref.d.mts +6 -4
- package/dist/commands/migration-ref.d.mts.map +1 -1
- package/dist/commands/migration-ref.mjs +31 -40
- package/dist/commands/migration-ref.mjs.map +1 -1
- package/dist/commands/migration-show.d.mts +13 -7
- package/dist/commands/migration-show.d.mts.map +1 -1
- package/dist/commands/migration-show.mjs +28 -29
- package/dist/commands/migration-show.mjs.map +1 -1
- package/dist/commands/migration-status.d.mts +5 -4
- package/dist/commands/migration-status.d.mts.map +1 -1
- package/dist/commands/migration-status.mjs +7 -2
- package/dist/{config-loader-_W4T21X1.mjs → config-loader-ih8ViDb_.mjs} +2 -2
- package/dist/config-loader-ih8ViDb_.mjs.map +1 -0
- package/dist/config-loader.mjs +1 -1
- package/dist/contract-emit-DS5NzZh2.mjs +6 -0
- package/dist/contract-emit-DWtGQYCD.mjs +150 -0
- package/dist/contract-emit-DWtGQYCD.mjs.map +1 -0
- package/dist/contract-emit-RZBWzkop.mjs +329 -0
- package/dist/contract-emit-RZBWzkop.mjs.map +1 -0
- package/dist/{contract-enrichment-CGW6mm-E.mjs → contract-enrichment-4Ptgw3Pe.mjs} +1 -1
- package/dist/{contract-enrichment-CGW6mm-E.mjs.map → contract-enrichment-4Ptgw3Pe.mjs.map} +1 -1
- package/dist/{contract-infer-BP3DrGgz.mjs → contract-infer-GztVCOCJ.mjs} +11 -19
- package/dist/contract-infer-GztVCOCJ.mjs.map +1 -0
- package/dist/exports/control-api.d.mts +78 -21
- package/dist/exports/control-api.d.mts.map +1 -1
- package/dist/exports/control-api.mjs +7 -5
- package/dist/exports/index.mjs +8 -3
- package/dist/exports/index.mjs.map +1 -1
- package/dist/exports/init-output.d.mts +39 -0
- package/dist/exports/init-output.d.mts.map +1 -0
- package/dist/exports/init-output.mjs +3 -0
- package/dist/{framework-components-DfZKQBQ2.mjs → framework-components-Bgcre3Z6.mjs} +2 -2
- package/dist/{framework-components-DfZKQBQ2.mjs.map → framework-components-Bgcre3Z6.mjs.map} +1 -1
- package/dist/init-DAbQMxIR.mjs +2062 -0
- package/dist/init-DAbQMxIR.mjs.map +1 -0
- package/dist/{inspect-live-schema-DWzf4Q_m.mjs → inspect-live-schema-BaR9ISwa.mjs} +9 -9
- package/dist/inspect-live-schema-BaR9ISwa.mjs.map +1 -0
- package/dist/migration-cli.d.mts +41 -11
- package/dist/migration-cli.d.mts.map +1 -1
- package/dist/migration-cli.mjs +308 -84
- package/dist/migration-cli.mjs.map +1 -1
- package/dist/{migration-command-scaffold-CLMD302g.mjs → migration-command-scaffold-D1dWuEWQ.mjs} +7 -7
- package/dist/{migration-command-scaffold-CLMD302g.mjs.map → migration-command-scaffold-D1dWuEWQ.mjs.map} +1 -1
- package/dist/{migration-status-B0HLF7So.mjs → migration-status-CP5k8O5i.mjs} +21 -35
- package/dist/migration-status-CP5k8O5i.mjs.map +1 -0
- package/dist/{migrations-B0dOQlk0.mjs → migrations-MEoKMiV5.mjs} +42 -21
- package/dist/migrations-MEoKMiV5.mjs.map +1 -0
- package/dist/output-BpcQrnnq.mjs +103 -0
- package/dist/output-BpcQrnnq.mjs.map +1 -0
- package/dist/{progress-adapter-B-YvmcDu.mjs → progress-adapter-DgRGldpT.mjs} +1 -1
- package/dist/{progress-adapter-B-YvmcDu.mjs.map → progress-adapter-DgRGldpT.mjs.map} +1 -1
- package/dist/quick-reference-mongo.md +34 -13
- package/dist/quick-reference-postgres.md +11 -9
- package/dist/{result-handler-CIyu0Pdt.mjs → result-handler-BmVh8AeV.mjs} +12 -93
- package/dist/result-handler-BmVh8AeV.mjs.map +1 -0
- package/dist/{terminal-ui-C5k88MmW.mjs → terminal-ui-u2YgKghu.mjs} +76 -2
- package/dist/terminal-ui-u2YgKghu.mjs.map +1 -0
- package/dist/{verify-BxiVp50b.mjs → verify-BT9tgCOH.mjs} +2 -2
- package/dist/{verify-BxiVp50b.mjs.map → verify-BT9tgCOH.mjs.map} +1 -1
- package/package.json +21 -15
- package/src/cli.ts +32 -6
- package/src/commands/contract-emit.ts +67 -163
- package/src/commands/contract-infer.ts +7 -20
- package/src/commands/db-init.ts +1 -0
- package/src/commands/db-update.ts +1 -1
- package/src/commands/init/detect-pnpm-catalog.ts +141 -0
- package/src/commands/init/errors.ts +254 -0
- package/src/commands/init/exit-codes.ts +62 -0
- package/src/commands/init/hygiene-gitattributes.ts +97 -0
- package/src/commands/init/hygiene-gitignore.ts +48 -0
- package/src/commands/init/hygiene-package-scripts.ts +91 -0
- package/src/commands/init/index.ts +112 -7
- package/src/commands/init/init.ts +766 -144
- package/src/commands/init/inputs.ts +421 -0
- package/src/commands/init/output.ts +147 -0
- package/src/commands/init/probe-db.ts +308 -0
- package/src/commands/init/reinit-cleanup.ts +83 -0
- package/src/commands/init/templates/agent-skill-mongo.md +63 -31
- package/src/commands/init/templates/agent-skill-postgres.md +1 -1
- package/src/commands/init/templates/agent-skill.ts +25 -3
- package/src/commands/init/templates/code-templates.ts +125 -32
- package/src/commands/init/templates/env.ts +80 -0
- package/src/commands/init/templates/quick-reference-mongo.md +34 -13
- package/src/commands/init/templates/quick-reference-postgres.md +11 -9
- package/src/commands/init/templates/quick-reference.ts +42 -3
- package/src/commands/init/templates/tsconfig.ts +167 -5
- package/src/commands/inspect-live-schema.ts +10 -5
- package/src/commands/migration-apply.ts +16 -51
- package/src/commands/migration-new.ts +26 -32
- package/src/commands/migration-plan.ts +80 -55
- package/src/commands/migration-ref.ts +40 -54
- package/src/commands/migration-show.ts +53 -36
- package/src/commands/migration-status.ts +33 -50
- package/src/config-path-validation.ts +0 -1
- package/src/control-api/client.ts +21 -0
- package/src/control-api/operations/contract-emit.ts +198 -115
- package/src/control-api/operations/db-init.ts +8 -5
- package/src/control-api/operations/db-update.ts +8 -5
- package/src/control-api/operations/migration-apply.ts +29 -9
- package/src/control-api/types.ts +61 -7
- package/src/exports/control-api.ts +2 -1
- package/src/exports/init-output.ts +10 -0
- package/src/migration-cli.ts +445 -122
- package/src/utils/cli-errors.ts +49 -2
- package/src/utils/command-helpers.ts +13 -26
- package/src/utils/emit-queue.ts +26 -0
- package/src/utils/formatters/graph-migration-mapper.ts +2 -2
- package/src/utils/formatters/migrations.ts +62 -26
- package/src/utils/publish-contract-artifact-pair.ts +134 -0
- package/dist/cli-errors-DHq6GQGu.mjs +0 -5
- package/dist/client-TG7rbCWT.mjs.map +0 -1
- package/dist/config-loader-_W4T21X1.mjs.map +0 -1
- package/dist/contract-emit-CNYyzJwF.mjs +0 -195
- package/dist/contract-emit-CNYyzJwF.mjs.map +0 -1
- package/dist/contract-emit-CQfj7xJn.mjs +0 -122
- package/dist/contract-emit-CQfj7xJn.mjs.map +0 -1
- package/dist/contract-emit-fhNwwhkQ.mjs +0 -4
- package/dist/contract-infer-BP3DrGgz.mjs.map +0 -1
- package/dist/extract-operation-statements-DZUJNmL3.mjs +0 -13
- package/dist/extract-operation-statements-DZUJNmL3.mjs.map +0 -1
- package/dist/extract-sql-ddl-DDMX-9mz.mjs +0 -26
- package/dist/extract-sql-ddl-DDMX-9mz.mjs.map +0 -1
- package/dist/init-CQfo_4Ro.mjs +0 -430
- package/dist/init-CQfo_4Ro.mjs.map +0 -1
- package/dist/inspect-live-schema-DWzf4Q_m.mjs.map +0 -1
- package/dist/migration-status-B0HLF7So.mjs.map +0 -1
- package/dist/migrations-B0dOQlk0.mjs.map +0 -1
- package/dist/result-handler-CIyu0Pdt.mjs.map +0 -1
- package/dist/terminal-ui-C5k88MmW.mjs.map +0 -1
- package/dist/validate-contract-deps-esa-VQ0h.mjs +0 -37
- package/dist/validate-contract-deps-esa-VQ0h.mjs.map +0 -1
- package/src/control-api/operations/extract-operation-statements.ts +0 -14
- package/src/control-api/operations/extract-sql-ddl.ts +0 -47
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as
|
|
3
|
-
import { t as inspectLiveSchema } from "./inspect-live-schema-
|
|
1
|
+
import { t as TerminalUI } from "./terminal-ui-u2YgKghu.mjs";
|
|
2
|
+
import { d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions } from "./result-handler-BmVh8AeV.mjs";
|
|
3
|
+
import { t as inspectLiveSchema } from "./inspect-live-schema-BaR9ISwa.mjs";
|
|
4
4
|
import { Command } from "commander";
|
|
5
|
-
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
6
5
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
7
6
|
import { dirname, relative, resolve } from "pathe";
|
|
8
7
|
import { errorRuntime } from "@prisma-next/errors/execution";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
8
|
+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { printPsl } from "@prisma-next/psl-printer";
|
|
11
10
|
|
|
12
11
|
//#region src/commands/contract-infer-paths.ts
|
|
13
12
|
/**
|
|
@@ -35,20 +34,13 @@ async function executeContractInferCommand(options, ui, startTime) {
|
|
|
35
34
|
url: "https://pris.ly/contract-infer"
|
|
36
35
|
});
|
|
37
36
|
if (!inspectResult.ok) return inspectResult;
|
|
38
|
-
const { config, target, meta } = inspectResult.value;
|
|
39
|
-
if (
|
|
40
|
-
why: "contract
|
|
41
|
-
fix: "Use
|
|
37
|
+
const { config, target, meta, pslContractAst } = inspectResult.value;
|
|
38
|
+
if (!pslContractAst) return notOk(errorRuntime("contract infer is not supported for this family", {
|
|
39
|
+
why: "The configured family does not implement the PslContractInferCapable capability, so an inferred PSL contract cannot be produced from the live database schema.",
|
|
40
|
+
fix: "Use a family that supports contract inference (e.g. SQL/Postgres)."
|
|
42
41
|
}));
|
|
43
|
-
const schema = validatePrintableSqlSchemaIR(inspectResult.value.schema);
|
|
44
42
|
const outputPath = resolveContractInferOutputPath(options, config.contract?.output);
|
|
45
|
-
const
|
|
46
|
-
const pslContent = printPsl(schema, {
|
|
47
|
-
defaultMapping: createPostgresDefaultMapping(),
|
|
48
|
-
typeMap: createPostgresTypeMap(enumInfo.typeNames),
|
|
49
|
-
enumInfo,
|
|
50
|
-
parseRawDefault
|
|
51
|
-
});
|
|
43
|
+
const pslContent = printPsl(pslContractAst);
|
|
52
44
|
if (existsSync(outputPath) && !flags.json && !flags.quiet) ui.stderr(`\u26A0 Overwriting existing file: ${relative(process.cwd(), outputPath)}`);
|
|
53
45
|
mkdirSync(dirname(outputPath), { recursive: true });
|
|
54
46
|
writeFileSync(outputPath, pslContent, "utf-8");
|
|
@@ -87,4 +79,4 @@ function createContractInferCommand() {
|
|
|
87
79
|
|
|
88
80
|
//#endregion
|
|
89
81
|
export { createContractInferCommand as t };
|
|
90
|
-
//# sourceMappingURL=contract-infer-
|
|
82
|
+
//# sourceMappingURL=contract-infer-GztVCOCJ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contract-infer-GztVCOCJ.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 { parseGlobalFlags } from '../utils/global-flags';\nimport { handleResult } from '../utils/result-handler';\nimport { 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 ui: TerminalUI,\n startTime: number,\n): Promise<Result<ContractInferSuccessResult, CliStructuredError>> {\n const flags = parseGlobalFlags(options);\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 ./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 = parseGlobalFlags(options);\n const ui = new TerminalUI({ color: flags.color, interactive: flags.interactive });\n const startTime = Date.now();\n\n const result = await executeContractInferCommand(options, 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;AAEjB,KAAI,QAAQ,OACV,QAAO,QAAQ,QAAQ,KAAK,EAAE,QAAQ,OAAO;AAE/C,KAAI,eAEF,QAAO,QAAQ,QADM,QAAQ,WAAW,eAAe,CACnB,EAAE,kBAAkB;AAE1D,QAAO,QAAQ,WAAW,kBAAkB;;;;;ACS9C,eAAe,4BACb,SACA,IACA,WACiE;CACjE,MAAM,QAAQ,iBAAiB,QAAQ;CACvC,MAAM,gBAAgB,MAAM,kBAAkB,SAAS,OAAO,IAAI,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K,CAE4C,EAClC,OAAO,KAAK,UAAU;AAC1D,OAAI,MAAM,KACR,IAAG,OAAO,KAAK,UAAU,OAAO,MAAM,EAAE,CAAC;IAE3C;AAEF,UAAQ,KAAK,SAAS;GACtB;AAEJ,QAAO"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { Result } from "@prisma-next/utils/result";
|
|
2
2
|
import { ContractSourceDiagnostics, ContractSourceProvider } from "@prisma-next/config/config-types";
|
|
3
|
-
import { ControlAdapterDescriptor, ControlDriverDescriptor, ControlExtensionDescriptor, ControlFamilyDescriptor, ControlStack, ControlTargetDescriptor, CoreSchemaView, MigrationPlanOperation, MigrationPlannerConflict, SignDatabaseResult, SignDatabaseResult as SignDatabaseResult$1, VerifyDatabaseResult, VerifyDatabaseResult as VerifyDatabaseResult$1, VerifyDatabaseSchemaResult, VerifyDatabaseSchemaResult as VerifyDatabaseSchemaResult$1 } from "@prisma-next/framework-components/control";
|
|
3
|
+
import { ControlAdapterDescriptor, ControlDriverDescriptor, ControlExtensionDescriptor, ControlFamilyDescriptor, ControlStack, ControlTargetDescriptor, CoreSchemaView, MigrationPlanOperation, MigrationPlannerConflict, OperationPreview, SignDatabaseResult, SignDatabaseResult as SignDatabaseResult$1, VerifyDatabaseResult, VerifyDatabaseResult as VerifyDatabaseResult$1, VerifyDatabaseSchemaResult, VerifyDatabaseSchemaResult as VerifyDatabaseSchemaResult$1 } from "@prisma-next/framework-components/control";
|
|
4
4
|
import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";
|
|
5
5
|
import { Contract, ContractMarkerRecord } from "@prisma-next/contract/types";
|
|
6
|
+
import { PslDocumentAst } from "@prisma-next/framework-components/psl-ast";
|
|
6
7
|
|
|
7
8
|
//#region src/control-api/types.d.ts
|
|
8
9
|
|
|
@@ -228,7 +229,14 @@ interface DbInitSuccess {
|
|
|
228
229
|
readonly label: string;
|
|
229
230
|
readonly operationClass: string;
|
|
230
231
|
}>;
|
|
231
|
-
|
|
232
|
+
/**
|
|
233
|
+
* Family-agnostic textual preview of the planned operations, e.g.
|
|
234
|
+
* `language: 'sql'` for SQL families and `language: 'mongodb-shell'`
|
|
235
|
+
* for the Mongo family. Replaces the previous `sql?: readonly string[]`
|
|
236
|
+
* field; consumers that previously read `plan.sql` should read
|
|
237
|
+
* `plan.preview?.statements.map((s) => s.text)`.
|
|
238
|
+
*/
|
|
239
|
+
readonly preview?: OperationPreview;
|
|
232
240
|
};
|
|
233
241
|
readonly destination: {
|
|
234
242
|
readonly storageHash: string;
|
|
@@ -282,7 +290,14 @@ interface DbUpdateSuccess {
|
|
|
282
290
|
readonly label: string;
|
|
283
291
|
readonly operationClass: string;
|
|
284
292
|
}>;
|
|
285
|
-
|
|
293
|
+
/**
|
|
294
|
+
* Family-agnostic textual preview of the planned operations, e.g.
|
|
295
|
+
* `language: 'sql'` for SQL families and `language: 'mongodb-shell'`
|
|
296
|
+
* for the Mongo family. Replaces the previous `sql?: readonly string[]`
|
|
297
|
+
* field; consumers that previously read `plan.sql` should read
|
|
298
|
+
* `plan.preview?.statements.map((s) => s.text)`.
|
|
299
|
+
*/
|
|
300
|
+
readonly preview?: OperationPreview;
|
|
286
301
|
};
|
|
287
302
|
readonly destination: {
|
|
288
303
|
readonly storageHash: string;
|
|
@@ -358,7 +373,7 @@ type EmitResult = Result<EmitSuccess, EmitFailure>;
|
|
|
358
373
|
*/
|
|
359
374
|
interface MigrationApplyStep {
|
|
360
375
|
readonly dirName: string;
|
|
361
|
-
readonly from: string;
|
|
376
|
+
readonly from: string | null;
|
|
362
377
|
readonly to: string;
|
|
363
378
|
readonly toContract: Contract;
|
|
364
379
|
readonly operations: readonly MigrationPlanOperation[];
|
|
@@ -395,7 +410,7 @@ interface MigrationApplyOptions {
|
|
|
395
410
|
*/
|
|
396
411
|
interface MigrationApplyAppliedEntry {
|
|
397
412
|
readonly dirName: string;
|
|
398
|
-
readonly from: string;
|
|
413
|
+
readonly from: string | null;
|
|
399
414
|
readonly to: string;
|
|
400
415
|
readonly operationsExecuted: number;
|
|
401
416
|
}
|
|
@@ -427,17 +442,30 @@ interface MigrationApplyFailure {
|
|
|
427
442
|
type MigrationApplyResult = Result<MigrationApplySuccess, MigrationApplyFailure>;
|
|
428
443
|
/**
|
|
429
444
|
* Options for the standalone executeContractEmit function.
|
|
430
|
-
*
|
|
431
|
-
*
|
|
445
|
+
*
|
|
446
|
+
* `executeContractEmit` is the canonical publication path for both the
|
|
447
|
+
* `prisma-next contract emit` CLI command and the `@prisma-next/vite-plugin-contract-emit`
|
|
448
|
+
* Vite plugin. Do not duplicate the load → emit → publish dance elsewhere; if a
|
|
449
|
+
* caller needs additional behavior, extend this options shape and update the
|
|
450
|
+
* single implementation rather than building a parallel publication path.
|
|
451
|
+
*
|
|
452
|
+
* Concurrent calls for the same output JSON path are serialized per-output via
|
|
453
|
+
* a FIFO queue; concurrent calls for distinct outputs run in parallel.
|
|
432
454
|
*/
|
|
433
455
|
interface ContractEmitOptions {
|
|
434
456
|
/** Path to the prisma-next.config.ts file */
|
|
435
457
|
readonly configPath: string;
|
|
436
|
-
/** Optional AbortSignal for
|
|
458
|
+
/** Optional AbortSignal for cancelling the in-flight emit */
|
|
437
459
|
readonly signal?: AbortSignal;
|
|
460
|
+
/** Optional progress callback for observing source-resolution and emit spans */
|
|
461
|
+
readonly onProgress?: OnControlProgress;
|
|
438
462
|
}
|
|
439
463
|
/**
|
|
440
464
|
* Result from the standalone executeContractEmit function.
|
|
465
|
+
*
|
|
466
|
+
* Always describes the bytes that were just published to disk. Failures throw
|
|
467
|
+
* (config / source-resolution / emit / publish) — callers do not need to
|
|
468
|
+
* branch on a result discriminator.
|
|
441
469
|
*/
|
|
442
470
|
interface ContractEmitResult {
|
|
443
471
|
/** Hash of the storage contract (schema-level) */
|
|
@@ -453,6 +481,12 @@ interface ContractEmitResult {
|
|
|
453
481
|
/** Path to the emitted contract.d.ts file */
|
|
454
482
|
readonly dts: string;
|
|
455
483
|
};
|
|
484
|
+
/**
|
|
485
|
+
* Warning surfaced by `validateContractDeps` after a successful publication.
|
|
486
|
+
* Callers (CLI, Vite plugin) decide how to render this; the operation does
|
|
487
|
+
* not write to stderr itself. Undefined when no warning was raised.
|
|
488
|
+
*/
|
|
489
|
+
readonly validationWarning?: string;
|
|
456
490
|
}
|
|
457
491
|
/**
|
|
458
492
|
* Programmatic control client for Prisma Next operations.
|
|
@@ -569,6 +603,23 @@ interface ControlClient {
|
|
|
569
603
|
* @returns CoreSchemaView if the family supports it, undefined otherwise
|
|
570
604
|
*/
|
|
571
605
|
toSchemaView(schemaIR: unknown): CoreSchemaView | undefined;
|
|
606
|
+
/**
|
|
607
|
+
* Infers a PSL contract AST from an introspected schema IR.
|
|
608
|
+
* Delegates to the family instance's inferPslContract method.
|
|
609
|
+
*
|
|
610
|
+
* @param schemaIR - The schema IR from introspect()
|
|
611
|
+
* @returns PslDocumentAst if the family supports the capability, undefined otherwise
|
|
612
|
+
*/
|
|
613
|
+
inferPslContract(schemaIR: unknown): PslDocumentAst | undefined;
|
|
614
|
+
/**
|
|
615
|
+
* Renders a textual preview of a migration plan's operations for the CLI's
|
|
616
|
+
* "DDL preview" output. Delegates to the family instance's
|
|
617
|
+
* `toOperationPreview` method.
|
|
618
|
+
*
|
|
619
|
+
* @param operations - The migration plan operations to render
|
|
620
|
+
* @returns OperationPreview if the family supports the capability, undefined otherwise
|
|
621
|
+
*/
|
|
622
|
+
toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview | undefined;
|
|
572
623
|
/**
|
|
573
624
|
* Emits the contract to JSON and TypeScript declarations.
|
|
574
625
|
* This is an offline operation that does NOT require a database connection.
|
|
@@ -602,23 +653,29 @@ declare function enrichContract(ir: Contract, components: ReadonlyArray<TargetBo
|
|
|
602
653
|
//#endregion
|
|
603
654
|
//#region src/control-api/operations/contract-emit.d.ts
|
|
604
655
|
/**
|
|
605
|
-
*
|
|
656
|
+
* Canonical contract emit operation.
|
|
606
657
|
*
|
|
607
|
-
* This is
|
|
608
|
-
*
|
|
609
|
-
*
|
|
610
|
-
*
|
|
611
|
-
* 4. Emits contract artifacts (JSON and DTS)
|
|
612
|
-
* 5. Writes files to the paths specified in config
|
|
658
|
+
* This is the SINGLE publication path used by both the CLI command
|
|
659
|
+
* (`prisma-next contract emit`) and the Vite plugin
|
|
660
|
+
* (`@prisma-next/vite-plugin-contract-emit`). New callers must go through this
|
|
661
|
+
* function rather than re-implementing load → emit → publish.
|
|
613
662
|
*
|
|
614
|
-
*
|
|
663
|
+
* The whole flow (load config → resolve source → emit bytes → atomic publish)
|
|
664
|
+
* is serialized per output JSON path via `queueEmitByOutput`. Concurrent calls
|
|
665
|
+
* for the same output line up FIFO; the user-visible outcome is "last
|
|
666
|
+
* submission wins on disk" without any supersession bookkeeping. Within a
|
|
667
|
+
* single emit, `publishContractArtifactPair` stages temp files, renames
|
|
668
|
+
* `contract.d.ts` before `contract.json`, and attempts to restore the previous
|
|
669
|
+
* pair if either rename fails — so type-only consumers never observe a
|
|
670
|
+
* mismatched pair.
|
|
615
671
|
*
|
|
616
|
-
* @
|
|
617
|
-
* @
|
|
618
|
-
* @throws If config loading fails, contract is invalid, or file I/O fails
|
|
619
|
-
* @throws signal.reason if cancelled via AbortSignal (typically DOMException with name 'AbortError')
|
|
672
|
+
* @throws {CliStructuredError} on config/source/validation problems
|
|
673
|
+
* @throws {DOMException} `AbortError` if cancelled via `signal`
|
|
620
674
|
*/
|
|
621
675
|
declare function executeContractEmit(options: ContractEmitOptions): Promise<ContractEmitResult>;
|
|
622
676
|
//#endregion
|
|
623
|
-
|
|
677
|
+
//#region src/utils/emit-queue.d.ts
|
|
678
|
+
declare function disposeEmitQueue(outputJsonPath: string): void;
|
|
679
|
+
//#endregion
|
|
680
|
+
export { type ContractEmitOptions, type ContractEmitResult, type ControlActionName, type ControlClient, type ControlClientOptions, type ControlProgressEvent, type ControlStack, type DbInitFailure, type DbInitFailureCode, type DbInitOptions, type DbInitResult, type DbInitSuccess, type DbUpdateFailure, type DbUpdateFailureCode, type DbUpdateOptions, type DbUpdateResult, type DbUpdateSuccess, type EmitContractConfig, type EmitFailure, type EmitFailureCode, type EmitOptions, type EmitResult, type EmitSuccess, type IntrospectOptions, type OnControlProgress, type SchemaVerifyOptions, type SignDatabaseResult, type SignOptions, type VerifyDatabaseResult, type VerifyDatabaseSchemaResult, type VerifyOptions, createControlClient, disposeEmitQueue, enrichContract, executeContractEmit };
|
|
624
681
|
//# sourceMappingURL=control-api.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"control-api.d.mts","names":[],"sources":["../../src/control-api/types.ts","../../src/control-api/client.ts","../../src/control-api/contract-enrichment.ts","../../src/control-api/operations/contract-emit.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"control-api.d.mts","names":[],"sources":["../../src/control-api/types.ts","../../src/control-api/client.ts","../../src/control-api/contract-enrichment.ts","../../src/control-api/operations/contract-emit.ts","../../src/utils/emit-queue.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;AAqCA;;;;;;;;AA2BY,UA3BK,oBAAA,CA2BY;EAuBjB,SAAA,MAAA,EAhDO,uBAkDI,CAAA,GAAA,EAAA,GAAA,CAAA;EAkBX,SAAA,MAAA,EAlEO,uBAkEqB,CAAA,GAAA,EAAA,GAAA,EAAA,GAAoB,CAAA;EAS3C,SAAA,OAAa,EAzEV,wBAmFI,CAAA,GAAiB,EAAA,GAAA,EAAA,GAAA,CAAA;EAMxB;EAsBA,SAAA,MAAW,CAAA,EA5GR,uBA8HI,CAAA,GAAiB,EAAA,GAAA,EAAA,GAAA,EAAA,GAAA,CAAA;EAMxB,SAAA,cAAa,CAAA,EAlIF,aAkJJ,CAlJkB,0BAkJD,CAAA,GAAA,EAAA,GAAA,EAAA,GAAA,CAAA,CAAA;EAMxB;AA8BjB;AAkBA;AAeA;AAgBA;EAmCY,SAAA,UAAA,CAAiB,EAAA,OAAA;AAK7B;;;;AAKiB,KApQL,iBAAA,GAoQK,QAAA,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sBAAsB,QAAQ;;;;;;;;;gBAUtC,cAAc,QAAQ;;;;;;;;;kBAUpB,gBAAgB,QAAQ;;;;;;;;;;oBAWtB,kBAAkB,QAAQ;;;;;;;gBAQ9B,QAAQ;;;;;;;;;;;;0BAaE,wBAAwB,QAAQ;;;;;;;uBAQnC,oBAAoB;;;;;;;;mCASR;;;;;;;;uCASI;;;;;;;;;0CAUG,2BAA2B;;;;;;;;gBASrD,cAAc,QAAQ;;;;;;;;;;;AA1rBtC;;;AAMoB,iBCgBJ,mBAAA,CDhBI,OAAA,ECgByB,oBDhBzB,CAAA,ECgBgD,aDhBhD;;;;;;;;iBE8CJ,cAAA,KACV,sBACQ,cAAc,kDACzB;;;;;;;;;;AFvDH;;;;;;;;AA2BA;AAuBA;AAoBA;AASA;AAgBA;AAsBiB,iBGHK,mBAAA,CHqBE,OAAiB,EGpB9B,mBHoB8B,CAAA,EGnBtC,OHmBsC,CGnB9B,kBHmB8B,CAAA;;;iBIrJzB,gBAAA"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import "../config-loader-
|
|
2
|
-
import
|
|
3
|
-
import { t as
|
|
4
|
-
import
|
|
1
|
+
import "../config-loader-ih8ViDb_.mjs";
|
|
2
|
+
import "../cli-errors-By1iVE3z.mjs";
|
|
3
|
+
import { n as disposeEmitQueue, t as executeContractEmit } from "../contract-emit-RZBWzkop.mjs";
|
|
4
|
+
import "../framework-components-Bgcre3Z6.mjs";
|
|
5
|
+
import { t as enrichContract } from "../contract-enrichment-4Ptgw3Pe.mjs";
|
|
6
|
+
import { t as createControlClient } from "../client-keSCAgjW.mjs";
|
|
5
7
|
|
|
6
|
-
export { createControlClient, enrichContract, executeContractEmit };
|
|
8
|
+
export { createControlClient, disposeEmitQueue, enrichContract, executeContractEmit };
|
package/dist/exports/index.mjs
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
|
-
import "../config-loader-
|
|
2
|
-
import
|
|
3
|
-
import
|
|
1
|
+
import "../config-loader-ih8ViDb_.mjs";
|
|
2
|
+
import "../cli-errors-By1iVE3z.mjs";
|
|
3
|
+
import "../contract-emit-RZBWzkop.mjs";
|
|
4
|
+
import "../framework-components-Bgcre3Z6.mjs";
|
|
5
|
+
import "../terminal-ui-u2YgKghu.mjs";
|
|
6
|
+
import "../result-handler-BmVh8AeV.mjs";
|
|
7
|
+
import { t as createContractEmitCommand } from "../contract-emit-DWtGQYCD.mjs";
|
|
4
8
|
import { join } from "pathe";
|
|
9
|
+
import { existsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
5
10
|
import { tmpdir } from "node:os";
|
|
6
11
|
import { pathToFileURL } from "node:url";
|
|
7
12
|
import { build } from "esbuild";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["value","disallowedImports: string[]","contract: unknown"],"sources":["../../src/load-ts-contract.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { pathToFileURL } from 'node:url';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { Plugin } from 'esbuild';\nimport { build } from 'esbuild';\nimport { join } from 'pathe';\n\nexport interface LoadTsContractOptions {\n readonly allowlist?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_ALLOWLIST = ['@prisma-next/*', 'node:crypto'];\n\nfunction isAllowedImport(importPath: string, allowlist: ReadonlyArray<string>): boolean {\n for (const pattern of allowlist) {\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n if (importPath === prefix || importPath.startsWith(`${prefix}/`)) {\n return true;\n }\n } else if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n if (importPath.startsWith(prefix)) {\n return true;\n }\n } else if (importPath === pattern) {\n return true;\n }\n }\n return false;\n}\n\nfunction validatePurity(value: unknown): void {\n if (typeof value !== 'object' || value === null) {\n return;\n }\n\n const path = new WeakSet();\n\n function check(value: unknown): void {\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (path.has(value)) {\n throw new Error('Contract export contains circular references');\n }\n path.add(value);\n\n try {\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw new Error(`Contract export contains getter/setter at key \"${key}\"`);\n }\n if (descriptor && typeof descriptor.value === 'function') {\n throw new Error(`Contract export contains function at key \"${key}\"`);\n }\n check((value as Record<string, unknown>)[key]);\n }\n } finally {\n path.delete(value);\n }\n }\n\n try {\n check(value);\n JSON.stringify(value);\n } catch (error) {\n if (error instanceof Error) {\n if (error.message.includes('getter') || error.message.includes('circular')) {\n throw error;\n }\n throw new Error(`Contract export is not JSON-serializable: ${error.message}`);\n }\n throw new Error('Contract export is not JSON-serializable');\n }\n}\n\nfunction createImportAllowlistPlugin(allowlist: ReadonlyArray<string>, entryPath: string): Plugin {\n return {\n name: 'import-allowlist',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === 'entry-point') {\n return undefined;\n }\n if (args.path.startsWith('.') || args.path.startsWith('/')) {\n return undefined;\n }\n const isFromEntryPoint = args.importer === entryPath || args.importer === '<stdin>';\n if (isFromEntryPoint && !isAllowedImport(args.path, allowlist)) {\n return {\n path: args.path,\n external: true,\n };\n }\n return undefined;\n });\n },\n };\n}\n\n/**\n * Loads a contract from a TypeScript file and returns it as Contract.\n *\n * **Responsibility: Parsing Only**\n * This function loads and parses a TypeScript contract file. It does NOT normalize the contract.\n * The contract should already be normalized if it was built using the contract builder.\n *\n * Normalization must happen in the contract builder when the contract is created.\n * This function only validates that the contract is JSON-serializable and returns it as-is.\n *\n * @param entryPath - Path to the TypeScript contract file\n * @param options - Optional configuration (import allowlist)\n * @returns The contract as Contract (should already be normalized)\n * @throws Error if the contract cannot be loaded or is not JSON-serializable\n */\nexport async function loadContractFromTs(\n entryPath: string,\n options?: LoadTsContractOptions,\n): Promise<Contract> {\n const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;\n\n if (!existsSync(entryPath)) {\n throw new Error(`Contract file not found: ${entryPath}`);\n }\n\n const tempFile = join(\n tmpdir(),\n `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n try {\n const result = await build({\n entryPoints: [entryPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'es2022',\n outfile: tempFile,\n write: false,\n metafile: true,\n plugins: [createImportAllowlistPlugin(allowlist, entryPath)],\n logLevel: 'error',\n });\n\n if (result.errors.length > 0) {\n const errorMessages = result.errors.map((e: { text: string }) => e.text).join('\\n');\n throw new Error(`Failed to bundle contract file: ${errorMessages}`);\n }\n\n if (!result.outputFiles || result.outputFiles.length === 0) {\n throw new Error('No output files generated from bundling');\n }\n\n const disallowedImports: string[] = [];\n if (result.metafile) {\n const inputs = result.metafile.inputs;\n for (const [, inputData] of Object.entries(inputs)) {\n const imports =\n (inputData as { imports?: Array<{ path: string; external?: boolean }> }).imports || [];\n for (const imp of imports) {\n if (\n imp.external &&\n !imp.path.startsWith('.') &&\n !imp.path.startsWith('/') &&\n !isAllowedImport(imp.path, allowlist)\n ) {\n disallowedImports.push(imp.path);\n }\n }\n }\n }\n\n if (disallowedImports.length > 0) {\n throw new Error(\n `Disallowed imports detected. Only imports matching the allowlist are permitted:\\n Allowlist: ${allowlist.join(', ')}\\n Disallowed imports: ${disallowedImports.join(', ')}\\n\\nOnly @prisma-next/* packages are allowed in contract files.`,\n );\n }\n\n const bundleContent = result.outputFiles[0]?.text;\n if (bundleContent === undefined) {\n throw new Error('Bundle content is undefined');\n }\n writeFileSync(tempFile, bundleContent, 'utf-8');\n\n const module = (await import(/* @vite-ignore */ pathToFileURL(tempFile).href)) as {\n default?: unknown;\n contract?: unknown;\n };\n unlinkSync(tempFile);\n\n let contract: unknown;\n\n if (module.default !== undefined) {\n contract = module.default;\n } else if (module.contract !== undefined) {\n contract = module.contract;\n } else {\n throw new Error(\n `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module as Record<string, unknown>).join(', ') || 'none'}`,\n );\n }\n\n if (typeof contract !== 'object' || contract === null) {\n throw new Error(`Contract export must be an object, got ${typeof contract}`);\n }\n\n validatePurity(contract);\n\n return contract as Contract;\n } catch (error) {\n try {\n if (tempFile) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(`Failed to load contract from ${entryPath}: ${String(error)}`);\n }\n}\n"],"mappings":";;;;;;;;;AAYA,MAAM,oBAAoB,CAAC,kBAAkB,cAAc;AAE3D,SAAS,gBAAgB,YAAoB,WAA2C;AACtF,MAAK,MAAM,WAAW,UACpB,KAAI,QAAQ,SAAS,KAAK,EAAE;EAC1B,MAAM,SAAS,QAAQ,MAAM,GAAG,GAAG;AACnC,MAAI,eAAe,UAAU,WAAW,WAAW,GAAG,OAAO,GAAG,CAC9D,QAAO;YAEA,QAAQ,SAAS,IAAI,EAAE;EAChC,MAAM,SAAS,QAAQ,MAAM,GAAG,GAAG;AACnC,MAAI,WAAW,WAAW,OAAO,CAC/B,QAAO;YAEA,eAAe,QACxB,QAAO;AAGX,QAAO;;AAGT,SAAS,eAAe,OAAsB;AAC5C,KAAI,OAAO,UAAU,YAAY,UAAU,KACzC;CAGF,MAAM,uBAAO,IAAI,SAAS;CAE1B,SAAS,MAAM,SAAsB;AACnC,MAAIA,YAAU,QAAQ,OAAOA,YAAU,SACrC;AAGF,MAAI,KAAK,IAAIA,QAAM,CACjB,OAAM,IAAI,MAAM,+CAA+C;AAEjE,OAAK,IAAIA,QAAM;AAEf,MAAI;AACF,QAAK,MAAM,OAAOA,SAAO;IACvB,MAAM,aAAa,OAAO,yBAAyBA,SAAO,IAAI;AAC9D,QAAI,eAAe,WAAW,OAAO,WAAW,KAC9C,OAAM,IAAI,MAAM,kDAAkD,IAAI,GAAG;AAE3E,QAAI,cAAc,OAAO,WAAW,UAAU,WAC5C,OAAM,IAAI,MAAM,6CAA6C,IAAI,GAAG;AAEtE,UAAOA,QAAkC,KAAK;;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MAAM,gCAAgC,UAAU,IAAI,OAAO,MAAM,GAAG"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["value","disallowedImports: string[]","contract: unknown"],"sources":["../../src/load-ts-contract.ts"],"sourcesContent":["import { existsSync, unlinkSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { pathToFileURL } from 'node:url';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type { Plugin } from 'esbuild';\nimport { build } from 'esbuild';\nimport { join } from 'pathe';\n\nexport interface LoadTsContractOptions {\n readonly allowlist?: ReadonlyArray<string>;\n}\n\nconst DEFAULT_ALLOWLIST = ['@prisma-next/*', 'node:crypto'];\n\nfunction isAllowedImport(importPath: string, allowlist: ReadonlyArray<string>): boolean {\n for (const pattern of allowlist) {\n if (pattern.endsWith('/*')) {\n const prefix = pattern.slice(0, -2);\n if (importPath === prefix || importPath.startsWith(`${prefix}/`)) {\n return true;\n }\n } else if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n if (importPath.startsWith(prefix)) {\n return true;\n }\n } else if (importPath === pattern) {\n return true;\n }\n }\n return false;\n}\n\nfunction validatePurity(value: unknown): void {\n if (typeof value !== 'object' || value === null) {\n return;\n }\n\n const path = new WeakSet();\n\n function check(value: unknown): void {\n if (value === null || typeof value !== 'object') {\n return;\n }\n\n if (path.has(value)) {\n throw new Error('Contract export contains circular references');\n }\n path.add(value);\n\n try {\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && (descriptor.get || descriptor.set)) {\n throw new Error(`Contract export contains getter/setter at key \"${key}\"`);\n }\n if (descriptor && typeof descriptor.value === 'function') {\n throw new Error(`Contract export contains function at key \"${key}\"`);\n }\n check((value as Record<string, unknown>)[key]);\n }\n } finally {\n path.delete(value);\n }\n }\n\n try {\n check(value);\n JSON.stringify(value);\n } catch (error) {\n if (error instanceof Error) {\n if (error.message.includes('getter') || error.message.includes('circular')) {\n throw error;\n }\n throw new Error(`Contract export is not JSON-serializable: ${error.message}`);\n }\n throw new Error('Contract export is not JSON-serializable');\n }\n}\n\nfunction createImportAllowlistPlugin(allowlist: ReadonlyArray<string>, entryPath: string): Plugin {\n return {\n name: 'import-allowlist',\n setup(build) {\n build.onResolve({ filter: /.*/ }, (args) => {\n if (args.kind === 'entry-point') {\n return undefined;\n }\n if (args.path.startsWith('.') || args.path.startsWith('/')) {\n return undefined;\n }\n const isFromEntryPoint = args.importer === entryPath || args.importer === '<stdin>';\n if (isFromEntryPoint && !isAllowedImport(args.path, allowlist)) {\n return {\n path: args.path,\n external: true,\n };\n }\n return undefined;\n });\n },\n };\n}\n\n/**\n * Loads a contract from a TypeScript file and returns it as Contract.\n *\n * **Responsibility: Parsing Only**\n * This function loads and parses a TypeScript contract file. It does NOT normalize the contract.\n * The contract should already be normalized if it was built using the contract builder.\n *\n * Normalization must happen in the contract builder when the contract is created.\n * This function only validates that the contract is JSON-serializable and returns it as-is.\n *\n * @param entryPath - Path to the TypeScript contract file\n * @param options - Optional configuration (import allowlist)\n * @returns The contract as Contract (should already be normalized)\n * @throws Error if the contract cannot be loaded or is not JSON-serializable\n */\nexport async function loadContractFromTs(\n entryPath: string,\n options?: LoadTsContractOptions,\n): Promise<Contract> {\n const allowlist = options?.allowlist ?? DEFAULT_ALLOWLIST;\n\n if (!existsSync(entryPath)) {\n throw new Error(`Contract file not found: ${entryPath}`);\n }\n\n const tempFile = join(\n tmpdir(),\n `prisma-next-contract-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n try {\n const result = await build({\n entryPoints: [entryPath],\n bundle: true,\n format: 'esm',\n platform: 'node',\n target: 'es2022',\n outfile: tempFile,\n write: false,\n metafile: true,\n plugins: [createImportAllowlistPlugin(allowlist, entryPath)],\n logLevel: 'error',\n });\n\n if (result.errors.length > 0) {\n const errorMessages = result.errors.map((e: { text: string }) => e.text).join('\\n');\n throw new Error(`Failed to bundle contract file: ${errorMessages}`);\n }\n\n if (!result.outputFiles || result.outputFiles.length === 0) {\n throw new Error('No output files generated from bundling');\n }\n\n const disallowedImports: string[] = [];\n if (result.metafile) {\n const inputs = result.metafile.inputs;\n for (const [, inputData] of Object.entries(inputs)) {\n const imports =\n (inputData as { imports?: Array<{ path: string; external?: boolean }> }).imports || [];\n for (const imp of imports) {\n if (\n imp.external &&\n !imp.path.startsWith('.') &&\n !imp.path.startsWith('/') &&\n !isAllowedImport(imp.path, allowlist)\n ) {\n disallowedImports.push(imp.path);\n }\n }\n }\n }\n\n if (disallowedImports.length > 0) {\n throw new Error(\n `Disallowed imports detected. Only imports matching the allowlist are permitted:\\n Allowlist: ${allowlist.join(', ')}\\n Disallowed imports: ${disallowedImports.join(', ')}\\n\\nOnly @prisma-next/* packages are allowed in contract files.`,\n );\n }\n\n const bundleContent = result.outputFiles[0]?.text;\n if (bundleContent === undefined) {\n throw new Error('Bundle content is undefined');\n }\n writeFileSync(tempFile, bundleContent, 'utf-8');\n\n const module = (await import(/* @vite-ignore */ pathToFileURL(tempFile).href)) as {\n default?: unknown;\n contract?: unknown;\n };\n unlinkSync(tempFile);\n\n let contract: unknown;\n\n if (module.default !== undefined) {\n contract = module.default;\n } else if (module.contract !== undefined) {\n contract = module.contract;\n } else {\n throw new Error(\n `Contract file must export a contract as default export or named export 'contract'. Found exports: ${Object.keys(module as Record<string, unknown>).join(', ') || 'none'}`,\n );\n }\n\n if (typeof contract !== 'object' || contract === null) {\n throw new Error(`Contract export must be an object, got ${typeof contract}`);\n }\n\n validatePurity(contract);\n\n return contract as Contract;\n } catch (error) {\n try {\n if (tempFile) {\n unlinkSync(tempFile);\n }\n } catch {\n // Ignore cleanup errors\n }\n\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(`Failed to load contract from ${entryPath}: ${String(error)}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAYA,MAAM,oBAAoB,CAAC,kBAAkB,cAAc;AAE3D,SAAS,gBAAgB,YAAoB,WAA2C;AACtF,MAAK,MAAM,WAAW,UACpB,KAAI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W,IAAI,IACzB,CAAC,IAAI,KAAK,WAAW,IAAI,IACzB,CAAC,gBAAgB,IAAI,MAAM,UAAU,CAErC,mBAAkB,KAAK,IAAI,KAAK;;;AAMxC,MAAI,kBAAkB,SAAS,EAC7B,OAAM,IAAI,MACR,iGAAiG,UAAU,KAAK,KAAK,CAAC,0BAA0B,kBAAkB,KAAK,KAAK,CAAC,iEAC9K;EAGH,MAAM,gBAAgB,OAAO,YAAY,IAAI;AAC7C,MAAI,kBAAkB,OACpB,OAAM,IAAI,MAAM,8BAA8B;AAEhD,gBAAc,UAAU,eAAe,QAAQ;EAE/C,MAAM,SAAU,MAAM;;GAA0B,cAAc,SAAS,CAAC;;AAIxE,aAAW,SAAS;EAEpB,IAAIC;AAEJ,MAAI,OAAO,YAAY,OACrB,YAAW,OAAO;WACT,OAAO,aAAa,OAC7B,YAAW,OAAO;MAElB,OAAM,IAAI,MACR,qGAAqG,OAAO,KAAK,OAAkC,CAAC,KAAK,KAAK,IAAI,SACnK;AAGH,MAAI,OAAO,aAAa,YAAY,aAAa,KAC/C,OAAM,IAAI,MAAM,0CAA0C,OAAO,WAAW;AAG9E,iBAAe,SAAS;AAExB,SAAO;UACA,OAAO;AACd,MAAI;AACF,OAAI,SACF,YAAW,SAAS;UAEhB;AAIR,MAAI,iBAAiB,MACnB,OAAM;AAER,QAAM,IAAI,MAAM,gCAAgC,UAAU,IAAI,OAAO,MAAM,GAAG"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import "@clack/prompts";
|
|
2
|
+
import * as arktype_internal_variants_object_ts0 from "arktype/internal/variants/object.ts";
|
|
3
|
+
|
|
4
|
+
//#region src/commands/init/output.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* arktype schema for the structured success document `init --json` writes
|
|
8
|
+
* to stdout (FR1.5). The same shape backs the human-readable outro
|
|
9
|
+
* renderer (FR10), so the two output modes carry identical information.
|
|
10
|
+
*
|
|
11
|
+
* `target` is normalised to the user-facing flag value (`mongodb` rather
|
|
12
|
+
* than the internal `mongo`) so consumers can round-trip the document
|
|
13
|
+
* straight into a follow-up `--target` invocation.
|
|
14
|
+
*
|
|
15
|
+
* The `ok: true` literal is the documented success/error discriminator —
|
|
16
|
+
* see [Style Guide § JSON Semantics](../../../../../../../docs/CLI%20Style%20Guide.md#json-semantics).
|
|
17
|
+
* Error envelopes (`CliErrorEnvelope`) carry `ok: false` so consumers can
|
|
18
|
+
* branch with `if (doc.ok)` without inspecting the rest of the structure.
|
|
19
|
+
*/
|
|
20
|
+
declare const InitOutputSchema: arktype_internal_variants_object_ts0.ObjectType<{
|
|
21
|
+
ok: true;
|
|
22
|
+
target: "postgres" | "mongodb";
|
|
23
|
+
authoring: "psl" | "typescript";
|
|
24
|
+
schemaPath: string;
|
|
25
|
+
filesWritten: string[];
|
|
26
|
+
filesDeleted: string[];
|
|
27
|
+
packagesInstalled: {
|
|
28
|
+
skipped: boolean;
|
|
29
|
+
deps: string[];
|
|
30
|
+
devDeps: string[];
|
|
31
|
+
};
|
|
32
|
+
contractEmitted: boolean;
|
|
33
|
+
nextSteps: string[];
|
|
34
|
+
warnings: string[];
|
|
35
|
+
}, {}>;
|
|
36
|
+
type InitOutput = typeof InitOutputSchema.infer;
|
|
37
|
+
//#endregion
|
|
38
|
+
export { type InitOutput, InitOutputSchema };
|
|
39
|
+
//# sourceMappingURL=init-output.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"init-output.d.mts","names":[],"sources":["../../src/commands/init/output.ts"],"sourcesContent":[],"mappings":";;;;;;;AAkBA;AAwBA;;;;;;;;;;;cAxBa,kBAsBX,oCAAA,CAtB2B;;;;;;;;;;;;;;;;KAwBjB,UAAA,UAAoB,gBAAA,CAAiB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as errorConfigValidation } from "./cli-errors-
|
|
1
|
+
import { r as errorConfigValidation } from "./cli-errors-By1iVE3z.mjs";
|
|
2
2
|
import "@prisma-next/framework-components/components";
|
|
3
3
|
|
|
4
4
|
//#region src/utils/framework-components.ts
|
|
@@ -56,4 +56,4 @@ function assertFrameworkComponentsCompatible(expectedFamilyId, expectedTargetId,
|
|
|
56
56
|
|
|
57
57
|
//#endregion
|
|
58
58
|
export { assertFrameworkComponentsCompatible as t };
|
|
59
|
-
//# sourceMappingURL=framework-components-
|
|
59
|
+
//# sourceMappingURL=framework-components-Bgcre3Z6.mjs.map
|
package/dist/{framework-components-DfZKQBQ2.mjs.map → framework-components-Bgcre3Z6.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"framework-components-
|
|
1
|
+
{"version":3,"file":"framework-components-Bgcre3Z6.mjs","names":[],"sources":["../src/utils/framework-components.ts"],"sourcesContent":["import type { Contract } from '@prisma-next/contract/types';\nimport {\n checkContractComponentRequirements,\n type TargetBoundComponentDescriptor,\n} from '@prisma-next/framework-components/components';\nimport type { ControlStack } from '@prisma-next/framework-components/control';\nimport { errorConfigValidation, errorContractMissingExtensionPacks } from './cli-errors';\n\n/**\n * Asserts that all framework components are compatible with the expected family and target.\n *\n * This function validates that each component in the framework components array:\n * - Has kind 'target', 'adapter', 'extension', or 'driver'\n * - Has familyId matching expectedFamilyId\n * - Has targetId matching expectedTargetId\n *\n * This validation happens at the CLI composition boundary, before passing components\n * to typed planner/runner instances. It fills the gap between runtime validation\n * (via `validateConfig()`) and compile-time type enforcement.\n *\n * @param expectedFamilyId - The expected family ID (e.g., 'sql')\n * @param expectedTargetId - The expected target ID (e.g., 'postgres')\n * @param frameworkComponents - Array of framework components to validate\n * @returns The same array typed as TargetBoundComponentDescriptor\n * @throws CliStructuredError if any component is incompatible\n *\n * @example\n * ```ts\n * const config = await loadConfig();\n * const frameworkComponents = [config.target, config.adapter, ...(config.extensionPacks ?? [])];\n *\n * // Validate and type-narrow components before passing to planner\n * const typedComponents = assertFrameworkComponentsCompatible(\n * config.family.familyId,\n * config.target.targetId,\n * frameworkComponents\n * );\n *\n * const planner = target.migrations.createPlanner(familyInstance);\n * planner.plan({ contract, schema, policy, frameworkComponents: typedComponents });\n * ```\n */\nexport function assertFrameworkComponentsCompatible<\n TFamilyId extends string,\n TTargetId extends string,\n>(\n expectedFamilyId: TFamilyId,\n expectedTargetId: TTargetId,\n frameworkComponents: ReadonlyArray<unknown>,\n): ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>> {\n for (let i = 0; i < frameworkComponents.length; i++) {\n const component = frameworkComponents[i];\n\n // Check that component is an object\n if (typeof component !== 'object' || component === null) {\n throw errorConfigValidation('frameworkComponents[]', {\n why: `Framework component at index ${i} must be an object`,\n });\n }\n\n const record = component as Record<string, unknown>;\n\n // Check kind\n if (!Object.hasOwn(record, 'kind')) {\n throw errorConfigValidation('frameworkComponents[].kind', {\n why: `Framework component at index ${i} must have 'kind' property`,\n });\n }\n\n const kind = record['kind'];\n if (kind !== 'target' && kind !== 'adapter' && kind !== 'extension' && kind !== 'driver') {\n throw errorConfigValidation('frameworkComponents[].kind', {\n why: `Framework component at index ${i} has invalid kind '${String(kind)}' (must be 'target', 'adapter', 'extension', or 'driver')`,\n });\n }\n\n // Check familyId\n if (!Object.hasOwn(record, 'familyId')) {\n throw errorConfigValidation('frameworkComponents[].familyId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'familyId' property`,\n });\n }\n\n const familyId = record['familyId'];\n if (familyId !== expectedFamilyId) {\n throw errorConfigValidation('frameworkComponents[].familyId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) has familyId '${String(familyId)}' but expected '${expectedFamilyId}'`,\n });\n }\n\n // Check targetId\n if (!Object.hasOwn(record, 'targetId')) {\n throw errorConfigValidation('frameworkComponents[].targetId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) must have 'targetId' property`,\n });\n }\n\n const targetId = record['targetId'];\n if (targetId !== expectedTargetId) {\n throw errorConfigValidation('frameworkComponents[].targetId', {\n why: `Framework component at index ${i} (kind: ${String(kind)}) has targetId '${String(targetId)}' but expected '${expectedTargetId}'`,\n });\n }\n }\n\n // Type assertion is safe because we've validated all components above\n return frameworkComponents as ReadonlyArray<TargetBoundComponentDescriptor<TFamilyId, TTargetId>>;\n}\n\n/**\n * Validates that a contract is compatible with the configured target, adapter,\n * and extension packs. Throws on family/target mismatches or missing extension packs.\n *\n * This check ensures the emitted contract matches the CLI config before running\n * commands that depend on the contract (e.g., db verify, db sign).\n *\n * @param contract - The contract to validate (must include targetFamily, target, extensionPacks).\n * @param stack - The control plane stack (target, adapter, driver, extensionPacks).\n *\n * @throws {CliStructuredError} errorConfigValidation when contract.targetFamily or contract.target\n * doesn't match the configured family/target.\n * @throws {CliStructuredError} errorContractMissingExtensionPacks when the contract requires\n * extension packs that are not provided in the config (includes all missing packs in error.meta).\n *\n * @example\n * ```ts\n * import { assertContractRequirementsSatisfied } from './framework-components';\n *\n * const config = await loadConfig();\n * const contract = await loadContractJson(config.contract.output);\n * const stack = createControlStack({ family: config.family, target: config.target, adapter: config.adapter, ... });\n *\n * // Throws if contract is incompatible with config\n * assertContractRequirementsSatisfied({ contract, stack });\n * ```\n */\nexport function assertContractRequirementsSatisfied<\n TFamilyId extends string,\n TTargetId extends string,\n>({\n contract,\n stack,\n}: {\n readonly contract: Pick<Contract, 'targetFamily' | 'target' | 'extensionPacks'>;\n readonly stack: ControlStack<TFamilyId, TTargetId>;\n}): void {\n const providedComponentIds = new Set<string>([\n stack.target.id,\n ...(stack.adapter ? [stack.adapter.id] : []),\n ]);\n for (const extension of stack.extensionPacks) {\n providedComponentIds.add(extension.id);\n }\n\n const result = checkContractComponentRequirements({\n contract,\n expectedTargetFamily: stack.target.familyId,\n expectedTargetId: stack.target.targetId,\n providedComponentIds,\n });\n\n if (result.familyMismatch) {\n throw errorConfigValidation('contract.targetFamily', {\n why: `Contract was emitted for family '${result.familyMismatch.actual}' but CLI config is wired to '${result.familyMismatch.expected}'.`,\n });\n }\n\n if (result.targetMismatch) {\n throw errorConfigValidation('contract.target', {\n why: `Contract target '${result.targetMismatch.actual}' does not match CLI target '${result.targetMismatch.expected}'.`,\n });\n }\n\n if (result.missingExtensionPackIds.length > 0) {\n throw errorContractMissingExtensionPacks({\n missingExtensionPacks: result.missingExtensionPackIds,\n providedComponentIds: [...providedComponentIds],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,SAAgB,oCAId,kBACA,kBACA,qBACqE;AACrE,MAAK,IAAI,IAAI,GAAG,IAAI,oBAAoB,QAAQ,KAAK;EACnD,MAAM,YAAY,oBAAoB;AAGtC,MAAI,OAAO,cAAc,YAAY,cAAc,KACjD,OAAM,sBAAsB,yBAAyB,EACnD,KAAK,gCAAgC,EAAE,qBACxC,CAAC;EAGJ,MAAM,SAAS;AAGf,MAAI,CAAC,OAAO,OAAO,QAAQ,OAAO,CAChC,OAAM,sBAAsB,8BAA8B,EACxD,KAAK,gCAAgC,EAAE,6BACxC,CAAC;EAGJ,MAAM,OAAO,OAAO;AACpB,MAAI,SAAS,YAAY,SAAS,aAAa,SAAS,eAAe,SAAS,SAC9E,OAAM,sBAAsB,8BAA8B,EACxD,KAAK,gCAAgC,EAAE,qBAAqB,OAAO,KAAK,CAAC,4DAC1E,CAAC;AAIJ,MAAI,CAAC,OAAO,OAAO,QAAQ,WAAW,CACpC,OAAM,sBAAsB,kCAAkC,EAC5D,KAAK,gCAAgC,EAAE,UAAU,OAAO,KAAK,CAAC,kCAC/D,CAAC;EAGJ,MAAM,WAAW,OAAO;AACxB,MAAI,aAAa,iBACf,OAAM,sBAAsB,kCAAkC,EAC5D,KAAK,gCAAgC,EAAE,UAAU,OAAO,KAAK,CAAC,kBAAkB,OAAO,SAAS,CAAC,kBAAkB,iBAAiB,IACrI,CAAC;AAIJ,MAAI,CAAC,OAAO,OAAO,QAAQ,WAAW,CACpC,OAAM,sBAAsB,kCAAkC,EAC5D,KAAK,gCAAgC,EAAE,UAAU,OAAO,KAAK,CAAC,kCAC/D,CAAC;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