@prisma-next/cli 0.5.0-dev.3 → 0.5.0-dev.30
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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config-loader-_W4T21X1.mjs","names":["emittedArtifactPaths: ReturnType<typeof getEmittedArtifactPaths>","loadConfigC12","loadConfig"],"sources":["../src/config-path-validation.ts","../src/config-loader.ts"],"sourcesContent":["import {\n type ContractSourceProvider,\n normalizeContractConfig,\n type PrismaNextConfig,\n} from '@prisma-next/config/config-types';\nimport { ConfigValidationError } from '@prisma-next/config/config-validation';\nimport { getEmittedArtifactPaths } from '@prisma-next/emitter';\nimport { resolve } from 'pathe';\n\nfunction throwValidation(field: string, why: string): never {\n throw new ConfigValidationError(field, why);\n}\n\nfunction finalizeContractSource(\n source: ContractSourceProvider,\n configDir: string,\n): ContractSourceProvider {\n const resolvedInputs = source.inputs?.map((input) => resolve(configDir, input));\n if (resolvedInputs === undefined) {\n return source;\n }\n\n return {\n ...source,\n inputs: resolvedInputs,\n };\n}\n\nfunction validateNoOutputsAreInputs(\n inputs: readonly string[] | undefined,\n output: string | undefined,\n): void {\n if (inputs === undefined || output === undefined) {\n return;\n }\n\n let emittedArtifactPaths: ReturnType<typeof getEmittedArtifactPaths>;\n try {\n emittedArtifactPaths = getEmittedArtifactPaths(output);\n } catch (error) {\n throwValidation('contract.output', error instanceof Error ? error.message : String(error));\n }\n\n const emittedPaths = new Set([emittedArtifactPaths.jsonPath, emittedArtifactPaths.dtsPath]);\n\n for (const input of inputs) {\n if (emittedPaths.has(input)) {\n throwValidation(\n 'contract.source.inputs[]',\n 'Config.contract.source.inputs must not include emitted artifact paths derived from contract.output',\n );\n }\n }\n}\n\nexport function finalizeConfig(config: PrismaNextConfig, configDir: string): PrismaNextConfig {\n if (!config.contract) {\n return config;\n }\n\n const contract = normalizeContractConfig(config.contract);\n const source = finalizeContractSource(contract.source, configDir);\n const output = resolve(configDir, contract.output);\n\n validateNoOutputsAreInputs(source.inputs, output);\n\n return {\n ...config,\n contract: {\n ...contract,\n source,\n output,\n },\n };\n}\n","import type { PrismaNextConfig } from '@prisma-next/config/config-types';\nimport { ConfigValidationError, validateConfig } from '@prisma-next/config/config-validation';\nimport {\n errorConfigFileNotFound,\n errorConfigValidation,\n errorUnexpected,\n} from '@prisma-next/errors/control';\nimport { ifDefined } from '@prisma-next/utils/defined';\nimport { loadConfig as loadConfigC12 } from 'c12';\nimport { dirname, resolve } from 'pathe';\nimport { finalizeConfig } from './config-path-validation';\n\nasync function loadValidatedConfig(configPath?: string): Promise<PrismaNextConfig> {\n const cwd = process.cwd();\n const resolvedConfigPath = configPath ? resolve(cwd, configPath) : undefined;\n const configCwd = resolvedConfigPath ? dirname(resolvedConfigPath) : cwd;\n\n const result = await loadConfigC12<PrismaNextConfig>({\n name: 'prisma-next',\n ...ifDefined('configFile', resolvedConfigPath),\n cwd: configCwd,\n });\n\n // When a specific config file was requested, verify it was actually loaded\n // (c12 falls back to searching by name if the specified file doesn't exist)\n if (resolvedConfigPath && result.configFile !== resolvedConfigPath) {\n throw errorConfigFileNotFound(resolvedConfigPath);\n }\n\n // Check if config is missing or empty (c12 may return empty object when file doesn't exist)\n if (!result.config || Object.keys(result.config).length === 0) {\n // Use c12's configFile if available, otherwise use explicit configPath, otherwise omit path\n const displayPath = result.configFile || resolvedConfigPath || configPath;\n throw errorConfigFileNotFound(displayPath);\n }\n\n // Validate config structure\n validateConfig(result.config);\n\n const loadedConfigDir = result.configFile ? dirname(result.configFile) : configCwd;\n return finalizeConfig(result.config, loadedConfigDir);\n}\n\n/**\n * Loads the Prisma Next config from a TypeScript file.\n * Supports both default export and named export.\n * Uses c12 to automatically handle TypeScript compilation and config file discovery.\n *\n * @param configPath - Optional path to config file. Defaults to `./prisma-next.config.ts` in current directory.\n * @returns The loaded config object.\n * @throws Error if config file doesn't exist or is invalid.\n */\nexport async function loadConfig(configPath?: string): Promise<PrismaNextConfig> {\n try {\n return await loadValidatedConfig(configPath);\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw errorConfigValidation(error.field, {\n why: error.why,\n });\n }\n\n // Re-throw structured errors as-is\n if (\n error instanceof Error &&\n 'code' in error &&\n typeof (error as { code: string }).code === 'string'\n ) {\n throw error;\n }\n\n if (error instanceof Error) {\n // Check for file not found errors\n if (\n error.message.includes('not found') ||\n error.message.includes('Cannot find') ||\n error.message.includes('ENOENT')\n ) {\n // Use resolved path if available, otherwise use original configPath\n const displayPath = configPath ? resolve(process.cwd(), configPath) : undefined;\n throw errorConfigFileNotFound(displayPath, {\n why: error.message,\n });\n }\n // For other errors, wrap in unexpected error\n throw errorUnexpected(error.message, {\n why: `Failed to load config: ${error.message}`,\n });\n }\n throw errorUnexpected(String(error));\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,gBAAgB,OAAe,KAAoB;AAC1D,OAAM,IAAI,sBAAsB,OAAO,IAAI;;AAG7C,SAAS,uBACP,QACA,WACwB;CACxB,MAAM,iBAAiB,OAAO,QAAQ,KAAK,UAAU,QAAQ,WAAW,MAAM,CAAC;AAC/E,KAAI,mBAAmB,OACrB,QAAO;AAGT,QAAO;EACL,GAAG;EACH,QAAQ;EACT;;AAGH,SAAS,2BACP,QACA,QACM;AACN,KAAI,WAAW,UAAa,WAAW,OACrC;CAGF,IAAIA;AACJ,KAAI;AACF,yBAAuB,wBAAwB,OAAO;UAC/C,OAAO;AACd,kBAAgB,mBAAmB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CAAC;;CAG5F,MAAM,eAAe,IAAI,IAAI,CAAC,qBAAqB,UAAU,qBAAqB,QAAQ,CAAC;AAE3F,MAAK,MAAM,SAAS,OAClB,KAAI,aAAa,IAAI,MAAM,CACzB,iBACE,4BACA,qGACD;;AAKP,SAAgB,eAAe,QAA0B,WAAqC;AAC5F,KAAI,CAAC,OAAO,SACV,QAAO;CAGT,MAAM,WAAW,wBAAwB,OAAO,SAAS;CACzD,MAAM,SAAS,uBAAuB,SAAS,QAAQ,UAAU;CACjE,MAAM,SAAS,QAAQ,WAAW,SAAS,OAAO;AAElD,4BAA2B,OAAO,QAAQ,OAAO;AAEjD,QAAO;EACL,GAAG;EACH,UAAU;GACR,GAAG;GACH;GACA;GACD;EACF;;;;;AC7DH,eAAe,oBAAoB,YAAgD;CACjF,MAAM,MAAM,QAAQ,KAAK;CACzB,MAAM,qBAAqB,aAAa,QAAQ,KAAK,WAAW,GAAG;CACnE,MAAM,YAAY,qBAAqB,QAAQ,mBAAmB,GAAG;CAErE,MAAM,SAAS,MAAMC,WAAgC;EACnD,MAAM;EACN,GAAG,UAAU,cAAc,mBAAmB;EAC9C,KAAK;EACN,CAAC;AAIF,KAAI,sBAAsB,OAAO,eAAe,mBAC9C,OAAM,wBAAwB,mBAAmB;AAInD,KAAI,CAAC,OAAO,UAAU,OAAO,KAAK,OAAO,OAAO,CAAC,WAAW,EAG1D,OAAM,wBADc,OAAO,cAAc,sBAAsB,WACrB;AAI5C,gBAAe,OAAO,OAAO;CAE7B,MAAM,kBAAkB,OAAO,aAAa,QAAQ,OAAO,WAAW,GAAG;AACzE,QAAO,eAAe,OAAO,QAAQ,gBAAgB;;;;;;;;;;;AAYvD,eAAsBC,aAAW,YAAgD;AAC/E,KAAI;AACF,SAAO,MAAM,oBAAoB,WAAW;UACrC,OAAO;AACd,MAAI,iBAAiB,sBACnB,OAAM,sBAAsB,MAAM,OAAO,EACvC,KAAK,MAAM,KACZ,CAAC;AAIJ,MACE,iBAAiB,SACjB,UAAU,SACV,OAAQ,MAA2B,SAAS,SAE5C,OAAM;AAGR,MAAI,iBAAiB,OAAO;AAE1B,OACE,MAAM,QAAQ,SAAS,YAAY,IACnC,MAAM,QAAQ,SAAS,cAAc,IACrC,MAAM,QAAQ,SAAS,SAAS,CAIhC,OAAM,wBADc,aAAa,QAAQ,QAAQ,KAAK,EAAE,WAAW,GAAG,QAC3B,EACzC,KAAK,MAAM,SACZ,CAAC;AAGJ,SAAM,gBAAgB,MAAM,SAAS,EACnC,KAAK,0BAA0B,MAAM,WACtC,CAAC;;AAEJ,QAAM,gBAAgB,OAAO,MAAM,CAAC"}
|
|
@@ -1,195 +0,0 @@
|
|
|
1
|
-
import { t as loadConfig } from "./config-loader-_W4T21X1.mjs";
|
|
2
|
-
import { _ as errorUnexpected$1, a as errorContractValidationFailed, m as errorRuntime, t as CliStructuredError$1 } from "./cli-errors-DHq6GQGu.mjs";
|
|
3
|
-
import { t as createControlClient } from "./client-TG7rbCWT.mjs";
|
|
4
|
-
import { _ as formatStyledHeader, d as setCommandExamples, m as parseGlobalFlags, n as addGlobalOptions, t as handleResult, u as setCommandDescriptions, v as formatSuccessMessage, x as isVerbose } from "./result-handler-CIyu0Pdt.mjs";
|
|
5
|
-
import { t as createProgressAdapter } from "./progress-adapter-B-YvmcDu.mjs";
|
|
6
|
-
import { t as TerminalUI } from "./terminal-ui-C5k88MmW.mjs";
|
|
7
|
-
import { Command } from "commander";
|
|
8
|
-
import { mkdirSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { getEmittedArtifactPaths } from "@prisma-next/emitter";
|
|
10
|
-
import { errorContractConfigMissing } from "@prisma-next/errors/control";
|
|
11
|
-
import { notOk, ok } from "@prisma-next/utils/result";
|
|
12
|
-
import { dirname, relative, resolve } from "pathe";
|
|
13
|
-
import { ifDefined } from "@prisma-next/utils/defined";
|
|
14
|
-
|
|
15
|
-
//#region src/utils/formatters/emit.ts
|
|
16
|
-
/**
|
|
17
|
-
* Formats human-readable output for contract emit.
|
|
18
|
-
*/
|
|
19
|
-
function formatEmitOutput(result, flags) {
|
|
20
|
-
if (flags.quiet) return "";
|
|
21
|
-
const lines = [];
|
|
22
|
-
const jsonPath = relative(process.cwd(), result.files.json);
|
|
23
|
-
const dtsPath = relative(process.cwd(), result.files.dts);
|
|
24
|
-
lines.push(`✔ Emitted contract.json → ${jsonPath}`);
|
|
25
|
-
lines.push(`✔ Emitted contract.d.ts → ${dtsPath}`);
|
|
26
|
-
lines.push(` storageHash: ${result.storageHash}`);
|
|
27
|
-
if (result.executionHash) lines.push(` executionHash: ${result.executionHash}`);
|
|
28
|
-
if (result.profileHash) lines.push(` profileHash: ${result.profileHash}`);
|
|
29
|
-
if (isVerbose(flags, 1)) lines.push(` Total time: ${result.timings.total}ms`);
|
|
30
|
-
return lines.join("\n");
|
|
31
|
-
}
|
|
32
|
-
/**
|
|
33
|
-
* Formats JSON output for contract emit.
|
|
34
|
-
*/
|
|
35
|
-
function formatEmitJson(result) {
|
|
36
|
-
const output = {
|
|
37
|
-
ok: true,
|
|
38
|
-
storageHash: result.storageHash,
|
|
39
|
-
...ifDefined("executionHash", result.executionHash),
|
|
40
|
-
...result.profileHash ? { profileHash: result.profileHash } : {},
|
|
41
|
-
outDir: result.outDir,
|
|
42
|
-
files: result.files,
|
|
43
|
-
timings: result.timings
|
|
44
|
-
};
|
|
45
|
-
return JSON.stringify(output, null, 2);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
//#endregion
|
|
49
|
-
//#region src/commands/contract-emit.ts
|
|
50
|
-
function mapDiagnosticsToIssues(failure) {
|
|
51
|
-
return (failure.diagnostics?.diagnostics ?? []).map((diagnostic) => {
|
|
52
|
-
const location = diagnostic.sourceId && diagnostic.span ? ` (${diagnostic.sourceId}:${diagnostic.span.start.line}:${diagnostic.span.start.column})` : diagnostic.sourceId ? ` (${diagnostic.sourceId})` : "";
|
|
53
|
-
return {
|
|
54
|
-
kind: diagnostic.code,
|
|
55
|
-
message: `${diagnostic.message}${location}`
|
|
56
|
-
};
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Maps an EmitFailure to a CliStructuredError for consistent error handling.
|
|
61
|
-
*/
|
|
62
|
-
function mapEmitFailure(failure, context) {
|
|
63
|
-
if (failure.code === "CONTRACT_SOURCE_INVALID") {
|
|
64
|
-
const issues = mapDiagnosticsToIssues(failure);
|
|
65
|
-
return errorRuntime(failure.summary, {
|
|
66
|
-
why: failure.why ?? "Contract source provider failed",
|
|
67
|
-
fix: "Check your contract source provider in prisma-next.config.ts and ensure it returns Result<Contract, Diagnostics>",
|
|
68
|
-
...issues.length > 0 ? { meta: { issues } } : {}
|
|
69
|
-
});
|
|
70
|
-
}
|
|
71
|
-
if (failure.code === "CONTRACT_VALIDATION_FAILED") return errorContractValidationFailed(failure.why ?? "Contract validation failed while emitting", context?.configPath ? { where: { path: context.configPath } } : void 0);
|
|
72
|
-
if (failure.code === "EMIT_FAILED") return errorRuntime(failure.summary, {
|
|
73
|
-
why: failure.why ?? "Failed to emit contract",
|
|
74
|
-
fix: "Check your contract configuration and ensure the source is valid"
|
|
75
|
-
});
|
|
76
|
-
const exhaustive = failure.code;
|
|
77
|
-
throw new Error(`Unhandled EmitFailure code: ${exhaustive}`);
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Executes the contract emit command and returns a structured Result.
|
|
81
|
-
*/
|
|
82
|
-
async function executeContractEmitCommand(options, flags, ui, startTime) {
|
|
83
|
-
let config;
|
|
84
|
-
try {
|
|
85
|
-
config = await loadConfig(options.config);
|
|
86
|
-
} catch (error) {
|
|
87
|
-
if (error instanceof CliStructuredError$1) return notOk(error);
|
|
88
|
-
return notOk(errorUnexpected$1(error instanceof Error ? error.message : String(error), { why: "Failed to load config" }));
|
|
89
|
-
}
|
|
90
|
-
const configPath = options.config ? relative(process.cwd(), resolve(options.config)) : "prisma-next.config.ts";
|
|
91
|
-
if (!config.contract) return notOk(errorContractConfigMissing({ why: "Config.contract is required for emit. Define it in your config: contract: { source: ..., output: ... }" }));
|
|
92
|
-
const contractConfig = config.contract;
|
|
93
|
-
if (!contractConfig.output) return notOk(errorContractConfigMissing({ why: "Contract config must have output path. This should not happen if defineConfig() was used." }));
|
|
94
|
-
let outputPaths;
|
|
95
|
-
try {
|
|
96
|
-
outputPaths = getEmittedArtifactPaths(contractConfig.output);
|
|
97
|
-
} catch (error) {
|
|
98
|
-
return notOk(errorContractConfigMissing({ why: error instanceof Error ? error.message : String(error) }));
|
|
99
|
-
}
|
|
100
|
-
const { jsonPath: outputJsonPath, dtsPath: outputDtsPath } = outputPaths;
|
|
101
|
-
if (!flags.json && !flags.quiet) {
|
|
102
|
-
const contractPath = relative(process.cwd(), outputJsonPath);
|
|
103
|
-
const typesPath = relative(process.cwd(), outputDtsPath);
|
|
104
|
-
const header = formatStyledHeader({
|
|
105
|
-
command: "contract emit",
|
|
106
|
-
description: "Emit your contract artifacts",
|
|
107
|
-
url: "https://pris.ly/contract-emit",
|
|
108
|
-
details: [
|
|
109
|
-
{
|
|
110
|
-
label: "config",
|
|
111
|
-
value: configPath
|
|
112
|
-
},
|
|
113
|
-
{
|
|
114
|
-
label: "contract",
|
|
115
|
-
value: contractPath
|
|
116
|
-
},
|
|
117
|
-
{
|
|
118
|
-
label: "types",
|
|
119
|
-
value: typesPath
|
|
120
|
-
}
|
|
121
|
-
],
|
|
122
|
-
flags
|
|
123
|
-
});
|
|
124
|
-
ui.stderr(header);
|
|
125
|
-
}
|
|
126
|
-
const client = createControlClient({
|
|
127
|
-
family: config.family,
|
|
128
|
-
target: config.target,
|
|
129
|
-
adapter: config.adapter,
|
|
130
|
-
extensionPacks: config.extensionPacks ?? []
|
|
131
|
-
});
|
|
132
|
-
const onProgress = createProgressAdapter({
|
|
133
|
-
ui,
|
|
134
|
-
flags
|
|
135
|
-
});
|
|
136
|
-
try {
|
|
137
|
-
const result = await client.emit({
|
|
138
|
-
contractConfig: {
|
|
139
|
-
source: contractConfig.source,
|
|
140
|
-
output: outputJsonPath
|
|
141
|
-
},
|
|
142
|
-
onProgress
|
|
143
|
-
});
|
|
144
|
-
if (!result.ok) return notOk(mapEmitFailure(result.failure, { configPath }));
|
|
145
|
-
mkdirSync(dirname(outputJsonPath), { recursive: true });
|
|
146
|
-
mkdirSync(dirname(outputDtsPath), { recursive: true });
|
|
147
|
-
writeFileSync(outputJsonPath, result.value.contractJson, "utf-8");
|
|
148
|
-
writeFileSync(outputDtsPath, result.value.contractDts, "utf-8");
|
|
149
|
-
const { validateContractDeps } = await import("./validate-contract-deps-esa-VQ0h.mjs");
|
|
150
|
-
const depsValidation = validateContractDeps(result.value.contractDts, dirname(outputDtsPath));
|
|
151
|
-
if (depsValidation.warning) ui.warn(depsValidation.warning);
|
|
152
|
-
return ok({
|
|
153
|
-
storageHash: result.value.storageHash,
|
|
154
|
-
...result.value.executionHash ? { executionHash: result.value.executionHash } : {},
|
|
155
|
-
profileHash: result.value.profileHash,
|
|
156
|
-
outDir: dirname(outputJsonPath),
|
|
157
|
-
files: {
|
|
158
|
-
json: outputJsonPath,
|
|
159
|
-
dts: outputDtsPath
|
|
160
|
-
},
|
|
161
|
-
timings: { total: Date.now() - startTime }
|
|
162
|
-
});
|
|
163
|
-
} catch (error) {
|
|
164
|
-
if (CliStructuredError$1.is(error)) return notOk(error);
|
|
165
|
-
return notOk(errorUnexpected$1("Unexpected error during contract emit", { why: error instanceof Error ? error.message : String(error) }));
|
|
166
|
-
} finally {
|
|
167
|
-
await client.close();
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
function createContractEmitCommand() {
|
|
171
|
-
const command = new Command("emit");
|
|
172
|
-
setCommandDescriptions(command, "Emit your contract artifacts", "Reads your contract source (TypeScript or Prisma schema) and emits contract.json and\ncontract.d.ts. The contract.json contains the canonical contract structure, and\ncontract.d.ts provides TypeScript types for type-safe query building.");
|
|
173
|
-
setCommandExamples(command, ["prisma-next contract emit", "prisma-next contract emit --config ./custom-config.ts"]);
|
|
174
|
-
addGlobalOptions(command).option("--config <path>", "Path to prisma-next.config.ts").action(async (options) => {
|
|
175
|
-
const flags = parseGlobalFlags(options);
|
|
176
|
-
const ui = new TerminalUI({
|
|
177
|
-
color: flags.color,
|
|
178
|
-
interactive: flags.interactive
|
|
179
|
-
});
|
|
180
|
-
const exitCode = handleResult(await executeContractEmitCommand(options, flags, ui, Date.now()), flags, ui, (emitResult) => {
|
|
181
|
-
if (flags.json) ui.output(formatEmitJson(emitResult));
|
|
182
|
-
else {
|
|
183
|
-
const output = formatEmitOutput(emitResult, flags);
|
|
184
|
-
if (output) ui.log(output);
|
|
185
|
-
if (!flags.quiet) ui.success(formatSuccessMessage(flags));
|
|
186
|
-
}
|
|
187
|
-
});
|
|
188
|
-
process.exit(exitCode);
|
|
189
|
-
});
|
|
190
|
-
return command;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
//#endregion
|
|
194
|
-
export { createContractEmitCommand as t };
|
|
195
|
-
//# sourceMappingURL=contract-emit-CNYyzJwF.mjs.map
|
|
@@ -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,cAA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D,CAAC,CACH;WACO;AACR,QAAM,OAAO,OAAO;;;AAIxB,SAAgB,4BAAqC;CACnD,MAAM,UAAU,IAAI,QAAQ,OAAO;AACnC,wBACE,SACA,gCACA,+OAGD;AACD,oBAAmB,SAAS,CAC1B,6BACA,wDACD,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,OAAO;CAExC,MAA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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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"contract-infer-BP3DrGgz.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, validatePrintableSqlSchemaIR } from '@prisma-next/psl-printer';\nimport {\n createPostgresDefaultMapping,\n createPostgresTypeMap,\n extractEnumInfo,\n parseRawDefault,\n} from '@prisma-next/psl-printer/postgres';\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 } = inspectResult.value;\n\n if (target.familyId !== 'sql') {\n return notOk(\n errorRuntime(`contract infer is not supported for family \"${target.familyId}\"`, {\n why: 'contract infer currently supports SQL targets only',\n fix: 'Use an SQL target (e.g. Postgres) with this command',\n }),\n );\n }\n\n const schema = validatePrintableSqlSchemaIR(inspectResult.value.schema);\n const outputPath = resolveContractInferOutputPath(options, config.contract?.output);\n const enumInfo = extractEnumInfo(schema.annotations);\n const pslContent = printPsl(schema, {\n defaultMapping: createPostgresDefaultMapping(),\n typeMap: createPostgresTypeMap(enumInfo.typeNames),\n enumInfo,\n parseRawDefault,\n });\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;C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8B,UAAU;AAGpD,QAAO,GAAG;EACR,IAAI;EACJ,SAAS;EACT;EACA,KAAK,EACH,MAAM,SACP;EACD;EACA,SAAS,EACP,OAAO,KAAK,KAAK,GAAG,WACrB;EACF,CAAC;;AAGJ,SAAgB,6BAAsC;CACpD,MAAM,UAAU,IAAI,QAAQ,QAAQ;AACpC,wBACE,SACA,sDACA,yLAGD;AACD,oBAAmB,SAAS;EAC1B;EACA;EACA;EACD,CAAC;AACF,kBAAiB,QAAQ,CACtB,OAAO,cAAc,6BAA6B,CAClD,OAAO,mBAAmB,gCAAgC,CAC1D,OAAO,mBAAmB,wDAAwD,CAClF,OAAO,OAAO,YAAkC;EAC/C,MAAM,QAAQ,iBAAiB,QAAQ;EACvC,MAAM,KAAK,IAAI,WAAW;GAAE,OAAO,MAAM;GAAO,aAAa,MAAM;GAAa,CAAC;EAIjF,MAAM,WAAW,aADF,MAAM,4BAA4B,SAAS,IAFxC,KAAK,KAAK,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,13 +0,0 @@
|
|
|
1
|
-
import { t as extractSqlDdl } from "./extract-sql-ddl-DDMX-9mz.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/control-api/operations/extract-operation-statements.ts
|
|
4
|
-
function extractOperationStatements(familyId, operations) {
|
|
5
|
-
switch (familyId) {
|
|
6
|
-
case "sql": return extractSqlDdl(operations);
|
|
7
|
-
default: return;
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
//#endregion
|
|
12
|
-
export { extractOperationStatements as t };
|
|
13
|
-
//# sourceMappingURL=extract-operation-statements-DZUJNmL3.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"extract-operation-statements-DZUJNmL3.mjs","names":[],"sources":["../src/control-api/operations/extract-operation-statements.ts"],"sourcesContent":["import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\nimport { extractSqlDdl } from './extract-sql-ddl';\n\nexport function extractOperationStatements(\n familyId: string,\n operations: readonly MigrationPlanOperation[],\n): string[] | undefined {\n switch (familyId) {\n case 'sql':\n return extractSqlDdl(operations);\n default:\n return undefined;\n }\n}\n"],"mappings":";;;AAGA,SAAgB,2BACd,UACA,YACsB;AACtB,SAAQ,UAAR;EACE,KAAK,MACH,QAAO,cAAc,WAAW;EAClC,QACE"}
|
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
//#region src/control-api/operations/extract-sql-ddl.ts
|
|
2
|
-
function isDdlStatement(sqlStatement) {
|
|
3
|
-
const trimmed = sqlStatement.trim().toLowerCase();
|
|
4
|
-
return trimmed.startsWith("create ") || trimmed.startsWith("alter ") || trimmed.startsWith("drop ");
|
|
5
|
-
}
|
|
6
|
-
function hasExecuteSteps(operation) {
|
|
7
|
-
const candidate = operation;
|
|
8
|
-
if (!("execute" in candidate) || !Array.isArray(candidate["execute"])) return false;
|
|
9
|
-
return candidate["execute"].every((step) => typeof step === "object" && step !== null && "sql" in step);
|
|
10
|
-
}
|
|
11
|
-
/**
|
|
12
|
-
* Extracts a best-effort SQL DDL preview for CLI plan output.
|
|
13
|
-
* This helper is presentation-only and is never used to decide migration correctness.
|
|
14
|
-
*/
|
|
15
|
-
function extractSqlDdl(operations) {
|
|
16
|
-
const statements = [];
|
|
17
|
-
for (const operation of operations) {
|
|
18
|
-
if (!hasExecuteSteps(operation)) continue;
|
|
19
|
-
for (const step of operation.execute) if (typeof step.sql === "string" && isDdlStatement(step.sql)) statements.push(step.sql.trim());
|
|
20
|
-
}
|
|
21
|
-
return statements;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
//#endregion
|
|
25
|
-
export { extractSqlDdl as t };
|
|
26
|
-
//# sourceMappingURL=extract-sql-ddl-DDMX-9mz.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"extract-sql-ddl-DDMX-9mz.mjs","names":["statements: string[]"],"sources":["../src/control-api/operations/extract-sql-ddl.ts"],"sourcesContent":["import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\n\n/**\n * Shape of an SQL execute step on SqlMigrationPlanOperation.\n * Used for runtime type narrowing without importing the concrete SQL type.\n */\ninterface SqlExecuteStep {\n readonly sql: string;\n}\n\nfunction isDdlStatement(sqlStatement: string): boolean {\n const trimmed = sqlStatement.trim().toLowerCase();\n return (\n trimmed.startsWith('create ') || trimmed.startsWith('alter ') || trimmed.startsWith('drop ')\n );\n}\n\nfunction hasExecuteSteps(\n operation: MigrationPlanOperation,\n): operation is MigrationPlanOperation & { readonly execute: readonly SqlExecuteStep[] } {\n const candidate = operation as unknown as Record<string, unknown>;\n if (!('execute' in candidate) || !Array.isArray(candidate['execute'])) {\n return false;\n }\n return candidate['execute'].every(\n (step: unknown) => typeof step === 'object' && step !== null && 'sql' in step,\n );\n}\n\n/**\n * Extracts a best-effort SQL DDL preview for CLI plan output.\n * This helper is presentation-only and is never used to decide migration correctness.\n */\nexport function extractSqlDdl(operations: readonly MigrationPlanOperation[]): string[] {\n const statements: string[] = [];\n for (const operation of operations) {\n if (!hasExecuteSteps(operation)) {\n continue;\n }\n for (const step of operation.execute) {\n if (typeof step.sql === 'string' && isDdlStatement(step.sql)) {\n statements.push(step.sql.trim());\n }\n }\n }\n return statements;\n}\n"],"mappings":";AAUA,SAAS,eAAe,cAA+B;CACrD,MAAM,UAAU,aAAa,MAAM,CAAC,aAAa;AACjD,QACE,QAAQ,WAAW,UAAU,IAAI,QAAQ,WAAW,SAAS,IAAI,QAAQ,WAAW,QAAQ;;AAIhG,SAAS,gBACP,WACuF;CACvF,MAAM,YAAY;AAClB,KAAI,EAAE,aAAa,cAAc,CAAC,MAAM,QAAQ,UAAU,WAAW,CACnE,QAAO;AAET,QAAO,UAAU,WAAW,OACzB,SAAkB,OAAO,SAAS,YAAY,SAAS,QAAQ,SAAS,KAC1E;;;;;;AAOH,SAAgB,cAAc,YAAyD;CACrF,MAAMA,aAAuB,EAAE;AAC/B,MAAK,MAAM,aAAa,YAAY;AAClC,MAAI,CAAC,gBAAgB,UAAU,CAC7B;AAEF,OAAK,MAAM,QAAQ,UAAU,QAC3B,KAAI,OAAO,KAAK,QAAQ,YAAY,eAAe,KAAK,IAAI,CAC1D,YAAW,KAAK,KAAK,IAAI,MAAM,CAAC;;AAItC,QAAO"}
|