@prisma-next/migration-tools 0.11.0-dev.33 → 0.11.0-dev.34
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 +4 -4
- package/dist/errors-CoEN114u.mjs.map +1 -1
- package/dist/exports/aggregate.d.mts +2 -2
- package/dist/exports/aggregate.mjs +4 -4
- package/dist/exports/enumerate-migration-spaces.mjs +2 -2
- package/dist/exports/errors.d.mts +2 -2
- package/dist/exports/graph.d.mts +1 -1
- package/dist/exports/hash.d.mts +7 -8
- package/dist/exports/hash.d.mts.map +1 -1
- package/dist/exports/hash.mjs +1 -1
- package/dist/exports/io.d.mts.map +1 -1
- package/dist/exports/io.mjs +1 -1
- package/dist/exports/metadata.d.mts +2 -2
- package/dist/exports/migration-graph.d.mts +2 -2
- package/dist/exports/migration-graph.mjs +1 -1
- package/dist/exports/migration.d.mts +5 -6
- package/dist/exports/migration.d.mts.map +1 -1
- package/dist/exports/migration.mjs +12 -30
- package/dist/exports/migration.mjs.map +1 -1
- package/dist/exports/ref-resolution.d.mts +1 -1
- package/dist/exports/spaces.mjs +4 -4
- package/dist/{graph-C7AJPGV5.d.mts → graph-ZAIvH6p4.d.mts} +1 -2
- package/dist/graph-ZAIvH6p4.d.mts.map +1 -0
- package/dist/{hash-Cr4WIr4Z.mjs → hash--Y7vCpN3.mjs} +8 -9
- package/dist/hash--Y7vCpN3.mjs.map +1 -0
- package/dist/{io-gHmDrSjQ.mjs → io-Dc64lvaL.mjs} +2 -8
- package/dist/io-Dc64lvaL.mjs.map +1 -0
- package/dist/metadata-BCH1rNsk.d.mts +2 -0
- package/dist/{migration-graph-C2iNX8dk.mjs → migration-graph-D5JeadSE.mjs} +4 -20
- package/dist/migration-graph-D5JeadSE.mjs.map +1 -0
- package/dist/{migration-graph-ABYqVsmv.d.mts → migration-graph-D97XMWVH.d.mts} +5 -5
- package/dist/{migration-graph-ABYqVsmv.d.mts.map → migration-graph-D97XMWVH.d.mts.map} +1 -1
- package/dist/{read-contract-space-contract-CwwlqKl_.mjs → read-contract-space-contract-_EvvV5Gl.mjs} +2 -2
- package/dist/{read-contract-space-contract-CwwlqKl_.mjs.map → read-contract-space-contract-_EvvV5Gl.mjs.map} +1 -1
- package/dist/{verify-contract-spaces-DxXWxGR0.mjs → verify-contract-spaces-DIdQLGo7.mjs} +2 -2
- package/dist/{verify-contract-spaces-DxXWxGR0.mjs.map → verify-contract-spaces-DIdQLGo7.mjs.map} +1 -1
- package/package.json +6 -6
- package/src/errors.ts +2 -2
- package/src/exports/metadata.ts +1 -1
- package/src/graph.ts +0 -1
- package/src/hash.ts +7 -8
- package/src/io.ts +0 -8
- package/src/metadata.ts +1 -1
- package/src/migration-base.ts +10 -30
- package/src/migration-graph.ts +4 -18
- package/dist/graph-C7AJPGV5.d.mts.map +0 -1
- package/dist/hash-Cr4WIr4Z.mjs.map +0 -1
- package/dist/io-gHmDrSjQ.mjs.map +0 -1
- package/dist/metadata-B4Wy6zor.d.mts +0 -2
- package/dist/migration-graph-C2iNX8dk.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -17,7 +17,7 @@ On-disk migration persistence, hash verification, and history reconstruction for
|
|
|
17
17
|
|
|
18
18
|
`computeMigrationHash` in `hash.ts` uses explicit framing:
|
|
19
19
|
|
|
20
|
-
1. Strip non-identity
|
|
20
|
+
1. Strip the non-identity field (`migrationHash`) from
|
|
21
21
|
the metadata envelope, then canonicalize the stripped envelope and the
|
|
22
22
|
ops array.
|
|
23
23
|
2. SHA-256 each canonical part independently.
|
|
@@ -27,7 +27,7 @@ This avoids delimiter-ambiguity and pins `migrationHash` to a 2-tuple over
|
|
|
27
27
|
the on-disk storage shape. Per [ADR 199 — Storage-only migration identity],
|
|
28
28
|
contracts are anchored by the storage-hash bookends (`from`, `to`) inside
|
|
29
29
|
the metadata envelope — the full contract IRs themselves are not part of
|
|
30
|
-
the manifest.
|
|
30
|
+
the manifest.
|
|
31
31
|
|
|
32
32
|
[ADR 199 — Storage-only migration identity]: ../../../docs/architecture%20docs/adrs/ADR%20199%20-%20Storage-only%20migration%20identity.md
|
|
33
33
|
|
|
@@ -60,7 +60,7 @@ graph TD
|
|
|
60
60
|
CLI["CLI commands<br/>(migration new, plan, apply, show, status)"] --> IO["io.ts<br/>File I/O"]
|
|
61
61
|
CLI --> HASH["hash.ts<br/>Migration hashing"]
|
|
62
62
|
CLI --> GRAPH["migration-graph.ts<br/>Graph operations"]
|
|
63
|
-
IO --> META["metadata.ts<br/>MigrationMetadata
|
|
63
|
+
IO --> META["metadata.ts<br/>MigrationMetadata"]
|
|
64
64
|
IO --> PKG["package.ts<br/>MigrationPackage, MigrationOps"]
|
|
65
65
|
HASH --> IO
|
|
66
66
|
HASH --> CAN["@prisma-next/framework-components/utils<br/>canonicalizeJson"]
|
|
@@ -88,7 +88,7 @@ graph TD
|
|
|
88
88
|
|
|
89
89
|
| Subpath | Contents |
|
|
90
90
|
|---|---|
|
|
91
|
-
| `./metadata` | `MigrationMetadata
|
|
91
|
+
| `./metadata` | `MigrationMetadata` |
|
|
92
92
|
| `./package` | `MigrationPackage`, `MigrationOps` |
|
|
93
93
|
| `./graph` | `MigrationGraph`, `MigrationEdge` |
|
|
94
94
|
| `./io` | `writeMigrationPackage`, `readMigrationPackage`, `readMigrationsDir`, `formatMigrationDirName` |
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors-CoEN114u.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { basename, dirname, relative } from 'pathe';\nimport type { MigrationGraph } from './graph';\n\n/**\n * Build the canonical \"re-emit this package\" remediation hint.\n *\n * Every on-disk migration package ships its own `migration.ts` author-time\n * file. Running it regenerates `migration.json` and `ops.json` with the\n * correct hash + metadata, so it is the right primitive whenever a single\n * package's on-disk artifacts are missing, malformed, or otherwise corrupt.\n * Pointing users at `migration plan` would emit a *new* package rather than\n * heal the broken one.\n */\nfunction reemitHint(dir: string, fallback?: string): string {\n const relativeDir = relative(process.cwd(), dir);\n const reemit = `Re-emit the package by running \\`node \"${relativeDir}/migration.ts\"\\``;\n return fallback ? `${reemit}, ${fallback}` : `${reemit}.`;\n}\n\n/**\n * Structured error for migration tooling operations.\n *\n * Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under\n * the MIGRATION namespace. These are tooling-time errors (file I/O, hash\n * verification, migration history reconstruction), distinct from the runtime\n * MIGRATION.* codes for apply-time failures (PRECHECK_FAILED, POSTCHECK_FAILED,\n * etc.).\n *\n * Fields:\n * - code: Stable machine-readable code (MIGRATION.SUBCODE)\n * - category: Always 'MIGRATION'\n * - why: Explains the cause in plain language\n * - fix: Actionable remediation step\n * - details: Machine-readable structured data for agents\n */\nexport class MigrationToolsError extends Error {\n readonly code: string;\n readonly category = 'MIGRATION' as const;\n readonly why: string;\n readonly fix: string;\n readonly details: Record<string, unknown> | undefined;\n\n constructor(\n code: string,\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly details?: Record<string, unknown>;\n },\n ) {\n super(summary);\n this.name = 'MigrationToolsError';\n this.code = code;\n this.why = options.why;\n this.fix = options.fix;\n this.details = options.details;\n }\n\n static is(error: unknown): error is MigrationToolsError {\n if (!(error instanceof Error)) return false;\n const candidate = error as MigrationToolsError;\n return candidate.name === 'MigrationToolsError' && typeof candidate.code === 'string';\n }\n}\n\nexport function errorDirectoryExists(dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.DIR_EXISTS', 'Migration directory already exists', {\n why: `The directory \"${dir}\" already exists. Each migration must have a unique directory.`,\n fix: 'Use --name to pick a different name, or delete the existing directory and re-run.',\n details: { dir },\n });\n}\n\nexport function errorMissingFile(file: string, dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.FILE_MISSING', `Missing ${file}`, {\n why: `Expected \"${file}\" in \"${dir}\" but the file does not exist.`,\n fix: reemitHint(\n dir,\n 'or delete the directory if the migration is unwanted and the source TypeScript is gone.',\n ),\n details: { file, dir },\n });\n}\n\nexport function errorInvalidJson(filePath: string, parseError: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_JSON', 'Invalid JSON in migration file', {\n why: `Failed to parse \"${filePath}\": ${parseError}`,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, parseError },\n });\n}\n\nexport function errorInvalidManifest(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_MANIFEST', 'Invalid migration manifest', {\n why: `Migration manifest at \"${filePath}\" is invalid: ${reason}`,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, reason },\n });\n}\n\nexport function errorInvalidOperationEntry(index: number, reason: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.INVALID_OPERATION_ENTRY',\n 'Migration operation entry is malformed',\n {\n why: `Operation at index ${index} returned by the migration class failed schema validation: ${reason}.`,\n fix: \"Update the migration class so each entry of `operations` carries `id` (string), `label` (string), and `operationClass` (one of 'additive' | 'widening' | 'destructive' | 'data').\",\n details: { index, reason },\n },\n );\n}\n\nexport function errorInvalidSlug(slug: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_NAME', 'Invalid migration name', {\n why: `The slug \"${slug}\" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,\n fix: 'Provide a name with at least one alphanumeric character, e.g. --name add_users.',\n details: { slug },\n });\n}\n\nexport function errorInvalidDestName(destName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_DEST_NAME', 'Invalid copy destination name', {\n why: `The destination name \"${destName}\" must be a single path segment (no \"..\" or directory separators).`,\n fix: 'Use a simple file name such as \"contract.json\" for each destination in the copy list.',\n details: { destName },\n });\n}\n\nexport function errorInvalidSpaceId(spaceId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.INVALID_SPACE_ID',\n 'Invalid contract space identifier',\n {\n why: `The space id \"${spaceId}\" does not match the required pattern /^[a-z][a-z0-9_-]{0,63}$/. Space ids are used as filesystem directory names under \\`migrations/\\`, so the pattern is conservative on purpose.`,\n fix: 'Pick a lowercase identifier that begins with a letter and contains only lowercase letters, digits, hyphens, or underscores; max 64 characters total.',\n details: { spaceId },\n },\n );\n}\n\nexport function errorDescriptorHeadHashMismatch(args: {\n readonly extensionId: string;\n readonly recomputedHash: string;\n readonly headRefHash: string;\n}): MigrationToolsError {\n const { extensionId, recomputedHash, headRefHash } = args;\n return new MigrationToolsError(\n 'MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH',\n \"Extension descriptor's headRef.hash does not match its contractJson\",\n {\n why: `Extension \"${extensionId}\" publishes a \\`contractSpace\\` whose \\`headRef.hash\\` (${headRefHash}) does not match the canonical hash recomputed from \\`contractSpace.contractJson\\` (${recomputedHash}). This means the extension descriptor was published with stale \\`headRef.hash\\` — typically because the contract was bumped without rerunning the extension's emit pipeline.`,\n fix: 'Re-run the extension authoring pipeline so `contractJson.storage.storageHash` and `headRef.hash` agree, then republish the extension. If you are the extension author and you intentionally bumped `contractJson`, recompute and update `headRef.hash` (and refresh any on-disk migration metadata that derives from it).',\n details: { extensionId, recomputedHash, headRefHash },\n },\n );\n}\n\nexport function errorDuplicateSpaceId(spaceId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_SPACE_ID',\n 'Duplicate contract space identifier',\n {\n why: `The space id \"${spaceId}\" appears more than once in the per-space planner input. Each space id must be unique across the inputs (the per-space planner emits one output entry per id).`,\n fix: 'Deduplicate the inputs before passing them to `planAllSpaces` — typically by checking your `extensionPacks` declaration for repeated entries.',\n details: { spaceId },\n },\n );\n}\n\nexport function errorSameSourceAndTarget(dir: string, hash: string): MigrationToolsError {\n const dirName = basename(dir);\n return new MigrationToolsError(\n 'MIGRATION.SAME_SOURCE_AND_TARGET',\n 'Migration without data-transform operations has same source and target',\n {\n why: `Migration \"${dirName}\" has from === to === \"${hash}\" and declares no data-transform operations. Self-edges are only allowed when the migration runs at least one dataTransform — otherwise the migration is a no-op.`,\n fix: reemitHint(\n dir,\n 'and either change the contract so from ≠ to, add a dataTransform op, or delete the directory if the migration is unwanted.',\n ),\n details: { dirName, hash },\n },\n );\n}\n\nexport function errorAmbiguousTarget(\n branchTips: readonly string[],\n context?: {\n divergencePoint: string;\n branches: readonly {\n tip: string;\n edges: readonly { dirName: string; from: string; to: string }[];\n }[];\n },\n): MigrationToolsError {\n const divergenceInfo = context\n ? `\\nDivergence point: ${context.divergencePoint}\\nBranches:\\n${context.branches.map((b) => ` → ${b.tip} (${b.edges.length} edge(s): ${b.edges.map((e) => e.dirName).join(' → ') || 'direct'})`).join('\\n')}`\n : '';\n return new MigrationToolsError('MIGRATION.AMBIGUOUS_TARGET', 'Ambiguous migration target', {\n why: `The migration history has diverged into multiple branches: ${branchTips.join(', ')}. This typically happens when two developers plan migrations from the same starting point.${divergenceInfo}`,\n fix: 'Use `ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `migration plan`, or use --from <hash> to explicitly select a starting point.',\n details: {\n branchTips,\n ...(context ? { divergencePoint: context.divergencePoint, branches: context.branches } : {}),\n },\n });\n}\n\nexport function errorNoInitialMigration(nodes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_INITIAL_MIGRATION', 'No initial migration found', {\n why: `No migration starts from the empty contract state (known hashes: ${nodes.join(', ')}). At least one migration must originate from the empty state.`,\n fix: 'Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.',\n details: { nodes },\n });\n}\n\nexport function errorInvalidRefs(refsPath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REFS', 'Invalid refs.json', {\n why: `refs.json at \"${refsPath}\" is invalid: ${reason}`,\n fix: 'Ensure refs.json is a flat object mapping valid ref names to contract hash strings.',\n details: { path: refsPath, reason },\n });\n}\n\nexport function errorInvalidRefFile(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_FILE', 'Invalid ref file', {\n why: `Ref file at \"${filePath}\" is invalid: ${reason}`,\n fix: 'Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.',\n details: { path: filePath, reason },\n });\n}\n\nexport function errorInvalidRefName(refName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_NAME', 'Invalid ref name', {\n why: `Ref name \"${refName}\" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no \".\" or \"..\" segments).`,\n fix: `Use a valid ref name (e.g., \"staging\", \"envs/production\").`,\n details: { refName },\n });\n}\n\nexport function errorNoTarget(reachableHashes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_TARGET', 'No migration target could be resolved', {\n why: `The migration history contains cycles and no target can be resolved automatically (reachable hashes: ${reachableHashes.join(', ')}). This typically happens after rollback migrations (e.g., C1→C2→C1).`,\n fix: 'Use --from <hash> to specify the planning origin explicitly.',\n details: { reachableHashes },\n });\n}\n\nexport function errorInvalidRefValue(value: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_VALUE', 'Invalid ref value', {\n why: `Ref value \"${value}\" is not a valid contract hash. Values must be in the format \"sha256:<64 hex chars>\" or \"sha256:empty\".`,\n fix: 'Use a valid storage hash from `prisma-next contract emit` output or an existing migration.',\n details: { value },\n });\n}\n\nexport function errorDuplicateMigrationHash(migrationHash: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_MIGRATION_HASH',\n 'Duplicate migrationHash in migration graph',\n {\n why: `Multiple migrations share migrationHash \"${migrationHash}\". Each migration must have a unique content-addressed identity.`,\n fix: 'Regenerate one of the conflicting migrations so each migrationHash is unique, then re-run migration commands.',\n details: { migrationHash },\n },\n );\n}\n\nexport function errorInvalidInvariantId(invariantId: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_INVARIANT_ID', 'Invalid invariantId', {\n why: `invariantId ${JSON.stringify(invariantId)} is invalid. Ids must be non-empty and contain no whitespace or control characters (including Unicode whitespace like NBSP); other content (kebab-case, camelCase, namespaced, Unicode letters) is allowed.`,\n fix: 'Pick an invariantId without spaces, tabs, newlines, or control characters — e.g. \"backfill-user-phone\", \"users/backfill-phone\", or \"BackfillUserPhone\".',\n details: { invariantId },\n });\n}\n\nexport function errorDuplicateInvariantInEdge(invariantId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_INVARIANT_IN_EDGE',\n 'Duplicate invariantId on a single migration',\n {\n why: `invariantId \"${invariantId}\" is declared by more than one dataTransform on the same migration. The marker stores invariants as a set and the routing layer treats them as edge-level, so two ops cannot share a routing identity.`,\n fix: 'Rename one of the conflicting dataTransform invariantIds, or drop invariantId on the op that does not need to be routing-visible.',\n details: { invariantId },\n },\n );\n}\n\nexport function errorProvidedInvariantsMismatch(\n filePath: string,\n stored: readonly string[],\n derived: readonly string[],\n): MigrationToolsError {\n const storedSet = new Set(stored);\n const derivedSet = new Set(derived);\n const missing = [...derivedSet].filter((id) => !storedSet.has(id));\n const extra = [...storedSet].filter((id) => !derivedSet.has(id));\n // When sets agree but arrays don't, the only difference is ordering — call\n // it out so the reader doesn't stare at two visually-identical arrays.\n // Canonical providedInvariants is sorted ascending; a manifest with the\n // same ids in a different order is still a mismatch (the hash check would\n // also fail), but the human-readable diagnostic is otherwise unhelpful.\n const orderingOnly = missing.length === 0 && extra.length === 0;\n const why = orderingOnly\n ? `migration.json at \"${filePath}\" stores providedInvariants ${JSON.stringify(stored)}, but the canonical value derived from ops.json is ${JSON.stringify(derived)} — same ids, different order. Canonical providedInvariants is sorted ascending.`\n : `migration.json at \"${filePath}\" stores providedInvariants ${JSON.stringify(stored)}, but the value derived from ops.json is ${JSON.stringify(derived)}. The manifest copy was likely hand-edited without re-emitting.`;\n return new MigrationToolsError(\n 'MIGRATION.PROVIDED_INVARIANTS_MISMATCH',\n 'providedInvariants on migration.json disagrees with ops.json',\n {\n why,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, stored, derived, difference: { missing, extra } },\n },\n );\n}\n\n/**\n * Wire-shape edge surfaced through the JSON envelope's\n * `meta.structuralPath` of `MIGRATION.NO_INVARIANT_PATH`. Slim by design —\n * authoring metadata (`createdAt`, `labels`) lives on `MigrationEdge` but\n * is intentionally dropped here so the envelope stays stable across\n * graph-internal refactors.\n *\n * Stability: any field added here is part of the public CLI JSON contract.\n * Callers (CLI consumers, agents) must be able to treat\n * `(dirName, migrationHash, from, to, invariants)` as the canonical shape.\n */\nexport interface NoInvariantPathStructuralEdge {\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly invariants: readonly string[];\n}\n\nexport function errorNoInvariantPath(args: {\n readonly refName?: string;\n readonly required: readonly string[];\n readonly missing: readonly string[];\n readonly structuralPath: readonly NoInvariantPathStructuralEdge[];\n}): MigrationToolsError {\n const { refName, required, missing, structuralPath } = args;\n const refClause = refName ? `Ref \"${refName}\"` : 'Target';\n const missingList = missing.map((id) => JSON.stringify(id)).join(', ');\n const requiredList = required.map((id) => JSON.stringify(id)).join(', ');\n return new MigrationToolsError(\n 'MIGRATION.NO_INVARIANT_PATH',\n 'No path covers the required invariants',\n {\n why: `${refClause} requires invariants the reachable path doesn't cover. required=[${requiredList}], missing=[${missingList}].`,\n fix: 'Add a migration on the path that runs `dataTransform({ invariantId: \"<id>\", … })` for each missing invariant, or retarget the ref to a hash whose path already provides them.',\n details: {\n required,\n missing,\n structuralPath,\n ...ifDefined('refName', refName),\n },\n },\n );\n}\n\nexport function errorUnknownInvariant(args: {\n readonly refName?: string;\n readonly unknown: readonly string[];\n readonly declared: readonly string[];\n}): MigrationToolsError {\n const { refName, unknown, declared } = args;\n const refClause = refName ? `Ref \"${refName}\" declares` : 'Declares';\n const unknownList = unknown.map((id) => JSON.stringify(id)).join(', ');\n return new MigrationToolsError(\n 'MIGRATION.UNKNOWN_INVARIANT',\n 'Ref declares invariants no migration in the graph provides',\n {\n why: `${refClause} invariants no migration in the graph provides. unknown=[${unknownList}].`,\n fix: 'Either the ref has a typo, or the declaring migration has not been authored/attested yet. Re-check the ref file and the migrations directory.',\n details: {\n unknown,\n declared,\n ...ifDefined('refName', refName),\n },\n },\n );\n}\n\nexport function errorMigrationHashMismatch(\n dir: string,\n storedHash: string,\n computedHash: string,\n): MigrationToolsError {\n // Render a cwd-relative path in the human-readable diagnostic so users\n // running CLI commands from the project root see a familiar short path.\n // Keep the absolute path in `details.dir` for machine consumers.\n const relativeDir = relative(process.cwd(), dir);\n return new MigrationToolsError('MIGRATION.HASH_MISMATCH', 'Migration package is corrupt', {\n why: `Stored migrationHash \"${storedHash}\" does not match the recomputed hash \"${computedHash}\" for \"${relativeDir}\". The migration.json or ops.json has been edited or partially written since emit.`,\n fix: reemitHint(dir, 'or restore the directory from version control.'),\n details: { dir, storedHash, computedHash },\n });\n}\n\nexport function errorHashNotInGraph(hash: string, graph: MigrationGraph): MigrationToolsError {\n const reachableHashes = [...graph.nodes].sort();\n const reachableList = reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none)';\n return new MigrationToolsError(\n 'MIGRATION.HASH_NOT_IN_GRAPH',\n `Hash \"${hash}\" is not a node in the migration graph`,\n {\n why: `The migration graph contains nodes ${reachableList}; \"${hash}\" isn't one of them.`,\n fix: `Pass a hash that's the from-or-to of an on-disk migration bundle, use --from with a graph-node hash, or run \"prisma-next migration plan\" to introduce it.`,\n details: { hash, reachableHashes },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAS,WAAW,KAAa,UAA2B;CAE1D,MAAM,SAAS,0CADK,SAAS,QAAQ,IAAI,GAAG,GACuB,EAAE;CACrE,OAAO,WAAW,GAAG,OAAO,IAAI,aAAa,GAAG,OAAO;AACzD;;;;;;;;;;;;;;;;;AAkBA,IAAa,sBAAb,cAAyC,MAAM;CAC7C;CACA,WAAoB;CACpB;CACA;CACA;CAEA,YACE,MACA,SACA,SAKA;EACA,MAAM,OAAO;EAC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AK,UAAU,EAAE,CAAC,EAAE,KAAK,IAKiC,EAAE,cAAc,YAAY;EAC5H,KAAK;EACL,SAAS;GACP;GACA;GACA;GACA,GAAG,UAAU,WAAW,OAAO;EACjC;CACF,CACF;AACF;AAEA,SAAgB,sBAAsB,MAId;CACtB,MAAM,EAAE,SAAS,SAAS,aAAa;CAGvC,OAAO,IAAI,oBACT,+BACA,8DACA;EACE,KAAK,GANS,UAAU,QAAQ,QAAQ,cAAc,WAMpC,2DALF,QAAQ,KAAK,OAAO,KAAK,UAAU,EAAE,CAAC,EAAE,KAAK,IAK0B,EAAE;EACzF,KAAK;EACL,SAAS;GACP;GACA;GACA,GAAG,UAAU,WAAW,OAAO;EACjC;CACF,CACF;AACF;AAEA,SAAgB,2BACd,KACA,YACA,cACqB;CAKrB,OAAO,IAAI,oBAAoB,2BAA2B,gCAAgC;EACxF,KAAK,yBAAyB,WAAW,wCAAwC,aAAa,SAF5E,SAAS,QAAQ,IAAI,GAAG,GAEuE,EAAE;EACnH,KAAK,WAAW,KAAK,gDAAgD;EACrE,SAAS;GAAE;GAAK;GAAY;EAAa;CAC3C,CAAC;AACH;AAEA,SAAgB,oBAAoB,MAAc,OAA4C;CAC5F,MAAM,kBAAkB,CAAC,GAAG,MAAM,KAAK,EAAE,KAAK;CAC9C,MAAM,gBAAgB,gBAAgB,SAAS,IAAI,gBAAgB,KAAK,IAAI,IAAI;CAChF,OAAO,IAAI,oBACT,+BACA,SAAS,KAAK,yCACd;EACE,KAAK,sCAAsC,cAAc,KAAK,KAAK;EACnE,KAAK;EACL,SAAS;GAAE;GAAM;EAAgB;CACnC,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"errors-CoEN114u.mjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["import { ifDefined } from '@prisma-next/utils/defined';\nimport { basename, dirname, relative } from 'pathe';\nimport type { MigrationGraph } from './graph';\n\n/**\n * Build the canonical \"re-emit this package\" remediation hint.\n *\n * Every on-disk migration package ships its own `migration.ts` author-time\n * file. Running it regenerates `migration.json` and `ops.json` with the\n * correct hash + metadata, so it is the right primitive whenever a single\n * package's on-disk artifacts are missing, malformed, or otherwise corrupt.\n * Pointing users at `migration plan` would emit a *new* package rather than\n * heal the broken one.\n */\nfunction reemitHint(dir: string, fallback?: string): string {\n const relativeDir = relative(process.cwd(), dir);\n const reemit = `Re-emit the package by running \\`node \"${relativeDir}/migration.ts\"\\``;\n return fallback ? `${reemit}, ${fallback}` : `${reemit}.`;\n}\n\n/**\n * Structured error for migration tooling operations.\n *\n * Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under\n * the MIGRATION namespace. These are tooling-time errors (file I/O, hash\n * verification, migration history reconstruction), distinct from the runtime\n * MIGRATION.* codes for apply-time failures (PRECHECK_FAILED, POSTCHECK_FAILED,\n * etc.).\n *\n * Fields:\n * - code: Stable machine-readable code (MIGRATION.SUBCODE)\n * - category: Always 'MIGRATION'\n * - why: Explains the cause in plain language\n * - fix: Actionable remediation step\n * - details: Machine-readable structured data for agents\n */\nexport class MigrationToolsError extends Error {\n readonly code: string;\n readonly category = 'MIGRATION' as const;\n readonly why: string;\n readonly fix: string;\n readonly details: Record<string, unknown> | undefined;\n\n constructor(\n code: string,\n summary: string,\n options: {\n readonly why: string;\n readonly fix: string;\n readonly details?: Record<string, unknown>;\n },\n ) {\n super(summary);\n this.name = 'MigrationToolsError';\n this.code = code;\n this.why = options.why;\n this.fix = options.fix;\n this.details = options.details;\n }\n\n static is(error: unknown): error is MigrationToolsError {\n if (!(error instanceof Error)) return false;\n const candidate = error as MigrationToolsError;\n return candidate.name === 'MigrationToolsError' && typeof candidate.code === 'string';\n }\n}\n\nexport function errorDirectoryExists(dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.DIR_EXISTS', 'Migration directory already exists', {\n why: `The directory \"${dir}\" already exists. Each migration must have a unique directory.`,\n fix: 'Use --name to pick a different name, or delete the existing directory and re-run.',\n details: { dir },\n });\n}\n\nexport function errorMissingFile(file: string, dir: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.FILE_MISSING', `Missing ${file}`, {\n why: `Expected \"${file}\" in \"${dir}\" but the file does not exist.`,\n fix: reemitHint(\n dir,\n 'or delete the directory if the migration is unwanted and the source TypeScript is gone.',\n ),\n details: { file, dir },\n });\n}\n\nexport function errorInvalidJson(filePath: string, parseError: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_JSON', 'Invalid JSON in migration file', {\n why: `Failed to parse \"${filePath}\": ${parseError}`,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, parseError },\n });\n}\n\nexport function errorInvalidManifest(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_MANIFEST', 'Invalid migration manifest', {\n why: `Migration manifest at \"${filePath}\" is invalid: ${reason}`,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, reason },\n });\n}\n\nexport function errorInvalidOperationEntry(index: number, reason: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.INVALID_OPERATION_ENTRY',\n 'Migration operation entry is malformed',\n {\n why: `Operation at index ${index} returned by the migration class failed schema validation: ${reason}.`,\n fix: \"Update the migration class so each entry of `operations` carries `id` (string), `label` (string), and `operationClass` (one of 'additive' | 'widening' | 'destructive' | 'data').\",\n details: { index, reason },\n },\n );\n}\n\nexport function errorInvalidSlug(slug: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_NAME', 'Invalid migration name', {\n why: `The slug \"${slug}\" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,\n fix: 'Provide a name with at least one alphanumeric character, e.g. --name add_users.',\n details: { slug },\n });\n}\n\nexport function errorInvalidDestName(destName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_DEST_NAME', 'Invalid copy destination name', {\n why: `The destination name \"${destName}\" must be a single path segment (no \"..\" or directory separators).`,\n fix: 'Use a simple file name such as \"contract.json\" for each destination in the copy list.',\n details: { destName },\n });\n}\n\nexport function errorInvalidSpaceId(spaceId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.INVALID_SPACE_ID',\n 'Invalid contract space identifier',\n {\n why: `The space id \"${spaceId}\" does not match the required pattern /^[a-z][a-z0-9_-]{0,63}$/. Space ids are used as filesystem directory names under \\`migrations/\\`, so the pattern is conservative on purpose.`,\n fix: 'Pick a lowercase identifier that begins with a letter and contains only lowercase letters, digits, hyphens, or underscores; max 64 characters total.',\n details: { spaceId },\n },\n );\n}\n\nexport function errorDescriptorHeadHashMismatch(args: {\n readonly extensionId: string;\n readonly recomputedHash: string;\n readonly headRefHash: string;\n}): MigrationToolsError {\n const { extensionId, recomputedHash, headRefHash } = args;\n return new MigrationToolsError(\n 'MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH',\n \"Extension descriptor's headRef.hash does not match its contractJson\",\n {\n why: `Extension \"${extensionId}\" publishes a \\`contractSpace\\` whose \\`headRef.hash\\` (${headRefHash}) does not match the canonical hash recomputed from \\`contractSpace.contractJson\\` (${recomputedHash}). This means the extension descriptor was published with stale \\`headRef.hash\\` — typically because the contract was bumped without rerunning the extension's emit pipeline.`,\n fix: 'Re-run the extension authoring pipeline so `contractJson.storage.storageHash` and `headRef.hash` agree, then republish the extension. If you are the extension author and you intentionally bumped `contractJson`, recompute and update `headRef.hash` (and refresh any on-disk migration metadata that derives from it).',\n details: { extensionId, recomputedHash, headRefHash },\n },\n );\n}\n\nexport function errorDuplicateSpaceId(spaceId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_SPACE_ID',\n 'Duplicate contract space identifier',\n {\n why: `The space id \"${spaceId}\" appears more than once in the per-space planner input. Each space id must be unique across the inputs (the per-space planner emits one output entry per id).`,\n fix: 'Deduplicate the inputs before passing them to `planAllSpaces` — typically by checking your `extensionPacks` declaration for repeated entries.',\n details: { spaceId },\n },\n );\n}\n\nexport function errorSameSourceAndTarget(dir: string, hash: string): MigrationToolsError {\n const dirName = basename(dir);\n return new MigrationToolsError(\n 'MIGRATION.SAME_SOURCE_AND_TARGET',\n 'Migration without data-transform operations has same source and target',\n {\n why: `Migration \"${dirName}\" has from === to === \"${hash}\" and declares no data-transform operations. Self-edges are only allowed when the migration runs at least one dataTransform — otherwise the migration is a no-op.`,\n fix: reemitHint(\n dir,\n 'and either change the contract so from ≠ to, add a dataTransform op, or delete the directory if the migration is unwanted.',\n ),\n details: { dirName, hash },\n },\n );\n}\n\nexport function errorAmbiguousTarget(\n branchTips: readonly string[],\n context?: {\n divergencePoint: string;\n branches: readonly {\n tip: string;\n edges: readonly { dirName: string; from: string; to: string }[];\n }[];\n },\n): MigrationToolsError {\n const divergenceInfo = context\n ? `\\nDivergence point: ${context.divergencePoint}\\nBranches:\\n${context.branches.map((b) => ` → ${b.tip} (${b.edges.length} edge(s): ${b.edges.map((e) => e.dirName).join(' → ') || 'direct'})`).join('\\n')}`\n : '';\n return new MigrationToolsError('MIGRATION.AMBIGUOUS_TARGET', 'Ambiguous migration target', {\n why: `The migration history has diverged into multiple branches: ${branchTips.join(', ')}. This typically happens when two developers plan migrations from the same starting point.${divergenceInfo}`,\n fix: 'Use `ref set <name> <hash>` to target a specific branch, delete one of the conflicting migration directories and re-run `migration plan`, or use --from <hash> to explicitly select a starting point.',\n details: {\n branchTips,\n ...(context ? { divergencePoint: context.divergencePoint, branches: context.branches } : {}),\n },\n });\n}\n\nexport function errorNoInitialMigration(nodes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_INITIAL_MIGRATION', 'No initial migration found', {\n why: `No migration starts from the empty contract state (known hashes: ${nodes.join(', ')}). At least one migration must originate from the empty state.`,\n fix: 'Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.',\n details: { nodes },\n });\n}\n\nexport function errorInvalidRefs(refsPath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REFS', 'Invalid refs.json', {\n why: `refs.json at \"${refsPath}\" is invalid: ${reason}`,\n fix: 'Ensure refs.json is a flat object mapping valid ref names to contract hash strings.',\n details: { path: refsPath, reason },\n });\n}\n\nexport function errorInvalidRefFile(filePath: string, reason: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_FILE', 'Invalid ref file', {\n why: `Ref file at \"${filePath}\" is invalid: ${reason}`,\n fix: 'Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.',\n details: { path: filePath, reason },\n });\n}\n\nexport function errorInvalidRefName(refName: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_NAME', 'Invalid ref name', {\n why: `Ref name \"${refName}\" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no \".\" or \"..\" segments).`,\n fix: `Use a valid ref name (e.g., \"staging\", \"envs/production\").`,\n details: { refName },\n });\n}\n\nexport function errorNoTarget(reachableHashes: readonly string[]): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.NO_TARGET', 'No migration target could be resolved', {\n why: `The migration history contains cycles and no target can be resolved automatically (reachable hashes: ${reachableHashes.join(', ')}). This typically happens after rollback migrations (e.g., C1→C2→C1).`,\n fix: 'Use --from <hash> to specify the planning origin explicitly.',\n details: { reachableHashes },\n });\n}\n\nexport function errorInvalidRefValue(value: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_REF_VALUE', 'Invalid ref value', {\n why: `Ref value \"${value}\" is not a valid contract hash. Values must be in the format \"sha256:<64 hex chars>\" or \"sha256:empty\".`,\n fix: 'Use a valid storage hash from `prisma-next contract emit` output or an existing migration.',\n details: { value },\n });\n}\n\nexport function errorDuplicateMigrationHash(migrationHash: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_MIGRATION_HASH',\n 'Duplicate migrationHash in migration graph',\n {\n why: `Multiple migrations share migrationHash \"${migrationHash}\". Each migration must have a unique content-addressed identity.`,\n fix: 'Regenerate one of the conflicting migrations so each migrationHash is unique, then re-run migration commands.',\n details: { migrationHash },\n },\n );\n}\n\nexport function errorInvalidInvariantId(invariantId: string): MigrationToolsError {\n return new MigrationToolsError('MIGRATION.INVALID_INVARIANT_ID', 'Invalid invariantId', {\n why: `invariantId ${JSON.stringify(invariantId)} is invalid. Ids must be non-empty and contain no whitespace or control characters (including Unicode whitespace like NBSP); other content (kebab-case, camelCase, namespaced, Unicode letters) is allowed.`,\n fix: 'Pick an invariantId without spaces, tabs, newlines, or control characters — e.g. \"backfill-user-phone\", \"users/backfill-phone\", or \"BackfillUserPhone\".',\n details: { invariantId },\n });\n}\n\nexport function errorDuplicateInvariantInEdge(invariantId: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.DUPLICATE_INVARIANT_IN_EDGE',\n 'Duplicate invariantId on a single migration',\n {\n why: `invariantId \"${invariantId}\" is declared by more than one dataTransform on the same migration. The marker stores invariants as a set and the routing layer treats them as edge-level, so two ops cannot share a routing identity.`,\n fix: 'Rename one of the conflicting dataTransform invariantIds, or drop invariantId on the op that does not need to be routing-visible.',\n details: { invariantId },\n },\n );\n}\n\nexport function errorProvidedInvariantsMismatch(\n filePath: string,\n stored: readonly string[],\n derived: readonly string[],\n): MigrationToolsError {\n const storedSet = new Set(stored);\n const derivedSet = new Set(derived);\n const missing = [...derivedSet].filter((id) => !storedSet.has(id));\n const extra = [...storedSet].filter((id) => !derivedSet.has(id));\n // When sets agree but arrays don't, the only difference is ordering — call\n // it out so the reader doesn't stare at two visually-identical arrays.\n // Canonical providedInvariants is sorted ascending; a manifest with the\n // same ids in a different order is still a mismatch (the hash check would\n // also fail), but the human-readable diagnostic is otherwise unhelpful.\n const orderingOnly = missing.length === 0 && extra.length === 0;\n const why = orderingOnly\n ? `migration.json at \"${filePath}\" stores providedInvariants ${JSON.stringify(stored)}, but the canonical value derived from ops.json is ${JSON.stringify(derived)} — same ids, different order. Canonical providedInvariants is sorted ascending.`\n : `migration.json at \"${filePath}\" stores providedInvariants ${JSON.stringify(stored)}, but the value derived from ops.json is ${JSON.stringify(derived)}. The manifest copy was likely hand-edited without re-emitting.`;\n return new MigrationToolsError(\n 'MIGRATION.PROVIDED_INVARIANTS_MISMATCH',\n 'providedInvariants on migration.json disagrees with ops.json',\n {\n why,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, stored, derived, difference: { missing, extra } },\n },\n );\n}\n\n/**\n * Wire-shape edge surfaced through the JSON envelope's\n * `meta.structuralPath` of `MIGRATION.NO_INVARIANT_PATH`. Slim by design —\n * authoring metadata (`createdAt`) lives on `MigrationEdge` but is\n * intentionally dropped here so the envelope stays stable across\n * graph-internal refactors.\n *\n * Stability: any field added here is part of the public CLI JSON contract.\n * Callers (CLI consumers, agents) must be able to treat\n * `(dirName, migrationHash, from, to, invariants)` as the canonical shape.\n */\nexport interface NoInvariantPathStructuralEdge {\n readonly dirName: string;\n readonly migrationHash: string;\n readonly from: string;\n readonly to: string;\n readonly invariants: readonly string[];\n}\n\nexport function errorNoInvariantPath(args: {\n readonly refName?: string;\n readonly required: readonly string[];\n readonly missing: readonly string[];\n readonly structuralPath: readonly NoInvariantPathStructuralEdge[];\n}): MigrationToolsError {\n const { refName, required, missing, structuralPath } = args;\n const refClause = refName ? `Ref \"${refName}\"` : 'Target';\n const missingList = missing.map((id) => JSON.stringify(id)).join(', ');\n const requiredList = required.map((id) => JSON.stringify(id)).join(', ');\n return new MigrationToolsError(\n 'MIGRATION.NO_INVARIANT_PATH',\n 'No path covers the required invariants',\n {\n why: `${refClause} requires invariants the reachable path doesn't cover. required=[${requiredList}], missing=[${missingList}].`,\n fix: 'Add a migration on the path that runs `dataTransform({ invariantId: \"<id>\", … })` for each missing invariant, or retarget the ref to a hash whose path already provides them.',\n details: {\n required,\n missing,\n structuralPath,\n ...ifDefined('refName', refName),\n },\n },\n );\n}\n\nexport function errorUnknownInvariant(args: {\n readonly refName?: string;\n readonly unknown: readonly string[];\n readonly declared: readonly string[];\n}): MigrationToolsError {\n const { refName, unknown, declared } = args;\n const refClause = refName ? `Ref \"${refName}\" declares` : 'Declares';\n const unknownList = unknown.map((id) => JSON.stringify(id)).join(', ');\n return new MigrationToolsError(\n 'MIGRATION.UNKNOWN_INVARIANT',\n 'Ref declares invariants no migration in the graph provides',\n {\n why: `${refClause} invariants no migration in the graph provides. unknown=[${unknownList}].`,\n fix: 'Either the ref has a typo, or the declaring migration has not been authored/attested yet. Re-check the ref file and the migrations directory.',\n details: {\n unknown,\n declared,\n ...ifDefined('refName', refName),\n },\n },\n );\n}\n\nexport function errorMigrationHashMismatch(\n dir: string,\n storedHash: string,\n computedHash: string,\n): MigrationToolsError {\n // Render a cwd-relative path in the human-readable diagnostic so users\n // running CLI commands from the project root see a familiar short path.\n // Keep the absolute path in `details.dir` for machine consumers.\n const relativeDir = relative(process.cwd(), dir);\n return new MigrationToolsError('MIGRATION.HASH_MISMATCH', 'Migration package is corrupt', {\n why: `Stored migrationHash \"${storedHash}\" does not match the recomputed hash \"${computedHash}\" for \"${relativeDir}\". The migration.json or ops.json has been edited or partially written since emit.`,\n fix: reemitHint(dir, 'or restore the directory from version control.'),\n details: { dir, storedHash, computedHash },\n });\n}\n\nexport function errorHashNotInGraph(hash: string, graph: MigrationGraph): MigrationToolsError {\n const reachableHashes = [...graph.nodes].sort();\n const reachableList = reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none)';\n return new MigrationToolsError(\n 'MIGRATION.HASH_NOT_IN_GRAPH',\n `Hash \"${hash}\" is not a node in the migration graph`,\n {\n why: `The migration graph contains nodes ${reachableList}; \"${hash}\" isn't one of them.`,\n fix: `Pass a hash that's the from-or-to of an on-disk migration bundle, use --from with a graph-node hash, or run \"prisma-next migration plan\" to introduce it.`,\n details: { hash, reachableHashes },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAS,WAAW,KAAa,UAA2B;CAE1D,MAAM,SAAS,0CADK,SAAS,QAAQ,IAAI,GAAG,GACuB,EAAE;CACrE,OAAO,WAAW,GAAG,OAAO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ackage } from "../package-DIttKL7X.mjs";
|
|
2
|
-
import { n as MigrationGraph } from "../graph-
|
|
3
|
-
import { t as PathDecision } from "../migration-graph-
|
|
2
|
+
import { n as MigrationGraph } from "../graph-ZAIvH6p4.mjs";
|
|
3
|
+
import { t as PathDecision } from "../migration-graph-D97XMWVH.mjs";
|
|
4
4
|
import { ControlFamilyInstance, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlannerConflict, TargetMigrationsCapability } from "@prisma-next/framework-components/control";
|
|
5
5
|
import { Result } from "@prisma-next/utils/result";
|
|
6
6
|
import { Contract } from "@prisma-next/contract/types";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as MigrationToolsError } from "../errors-CoEN114u.mjs";
|
|
2
|
-
import { s as readMigrationsDir } from "../io-
|
|
2
|
+
import { s as readMigrationsDir } from "../io-Dc64lvaL.mjs";
|
|
3
3
|
import "../constants-DWV9_o2Z.mjs";
|
|
4
|
-
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-
|
|
5
|
-
import { c as spaceMigrationDirectory, r as APP_SPACE_ID, t as listContractSpaceDirectories } from "../verify-contract-spaces-
|
|
6
|
-
import { n as readContractSpaceHeadRef, t as readContractSpaceContract } from "../read-contract-space-contract-
|
|
4
|
+
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-D5JeadSE.mjs";
|
|
5
|
+
import { c as spaceMigrationDirectory, r as APP_SPACE_ID, t as listContractSpaceDirectories } from "../verify-contract-spaces-DIdQLGo7.mjs";
|
|
6
|
+
import { n as readContractSpaceHeadRef, t as readContractSpaceContract } from "../read-contract-space-contract-_EvvV5Gl.mjs";
|
|
7
7
|
import { notOk, ok } from "@prisma-next/utils/result";
|
|
8
8
|
//#region src/aggregate/extract-storage-element-names.ts
|
|
9
9
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { s as readMigrationsDir } from "../io-
|
|
1
|
+
import { s as readMigrationsDir } from "../io-Dc64lvaL.mjs";
|
|
2
2
|
import { r as readRefs } from "../refs-HhOkD8BT.mjs";
|
|
3
|
-
import { c as spaceMigrationDirectory, i as RESERVED_SPACE_SUBDIR_NAMES, l as spaceRefsDirectory, r as APP_SPACE_ID, s as isValidSpaceId, t as listContractSpaceDirectories } from "../verify-contract-spaces-
|
|
3
|
+
import { c as spaceMigrationDirectory, i as RESERVED_SPACE_SUBDIR_NAMES, l as spaceRefsDirectory, r as APP_SPACE_ID, s as isValidSpaceId, t as listContractSpaceDirectories } from "../verify-contract-spaces-DIdQLGo7.mjs";
|
|
4
4
|
//#region src/enumerate-migration-spaces.ts
|
|
5
5
|
/**
|
|
6
6
|
* Index `migrations/<space>/refs/*.json` by the contract hash each ref
|
|
@@ -37,8 +37,8 @@ declare function errorDescriptorHeadHashMismatch(args: {
|
|
|
37
37
|
/**
|
|
38
38
|
* Wire-shape edge surfaced through the JSON envelope's
|
|
39
39
|
* `meta.structuralPath` of `MIGRATION.NO_INVARIANT_PATH`. Slim by design —
|
|
40
|
-
* authoring metadata (`createdAt
|
|
41
|
-
*
|
|
40
|
+
* authoring metadata (`createdAt`) lives on `MigrationEdge` but is
|
|
41
|
+
* intentionally dropped here so the envelope stays stable across
|
|
42
42
|
* graph-internal refactors.
|
|
43
43
|
*
|
|
44
44
|
* Stability: any field added here is part of the public CLI JSON contract.
|
package/dist/exports/graph.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as MigrationGraph, t as MigrationEdge } from "../graph-
|
|
1
|
+
import { n as MigrationGraph, t as MigrationEdge } from "../graph-ZAIvH6p4.mjs";
|
|
2
2
|
export { type MigrationEdge, type MigrationGraph };
|
package/dist/exports/hash.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as OnDiskMigrationPackage, t as MigrationOps } from "../package-DIttKL7X.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { t as MigrationMetadata } from "../metadata-BCH1rNsk.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/hash.d.ts
|
|
5
5
|
interface VerifyResult {
|
|
@@ -9,13 +9,12 @@ interface VerifyResult {
|
|
|
9
9
|
readonly computedHash: string;
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
|
-
* Content-addressed migration hash over (metadata envelope
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* authored alongside the migration, never inlined here.
|
|
12
|
+
* Content-addressed migration hash over (metadata envelope, ops). See
|
|
13
|
+
* ADR 199 — Storage-only migration identity for the rationale: the
|
|
14
|
+
* storage-hash bookends (`from`, `to`) inside the envelope anchor the
|
|
15
|
+
* contract identity by hash. The full contract IRs are not part of the
|
|
16
|
+
* manifest — they live in sibling `*-contract.json` files authored
|
|
17
|
+
* alongside the migration, never inlined here.
|
|
19
18
|
*
|
|
20
19
|
* The integrity check is purely structural, not semantic. The function
|
|
21
20
|
* canonicalizes its inputs via `sortKeys` (recursive) + `JSON.stringify`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hash.d.mts","names":[],"sources":["../../src/hash.ts"],"mappings":";;;;UAKiB,YAAA;EAAA,SACN,EAAA;EAAA,SACA,MAAA;EAAA,SACA,UAAA;EAAA,SACA,YAAA;AAAA;;;;;;AAAY;
|
|
1
|
+
{"version":3,"file":"hash.d.mts","names":[],"sources":["../../src/hash.ts"],"mappings":";;;;UAKiB,YAAA;EAAA,SACN,EAAA;EAAA,SACA,MAAA;EAAA,SACA,UAAA;EAAA,SACA,YAAA;AAAA;;;;;;AAAY;AAkCvB;;;;;;;;;;;;;;;AAEmB;AAsBnB;;;;;iBAxBgB,oBAAA,CACd,QAAA,EAAU,IAAA,CAAK,iBAAA;EAAA,SAAiD,aAAA;AAAA,GAChE,GAAA,EAAK,YAAA;AAsBuE;;;;;;;;;AAAA,iBAA9D,mBAAA,CAAoB,GAAA,EAAK,sBAAA,GAAyB,YAAY"}
|
package/dist/exports/hash.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as verifyMigrationHash, t as computeMigrationHash } from "../hash
|
|
1
|
+
import { n as verifyMigrationHash, t as computeMigrationHash } from "../hash--Y7vCpN3.mjs";
|
|
2
2
|
export { computeMigrationHash, verifyMigrationHash };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"io.d.mts","names":[],"sources":["../../src/io.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"io.d.mts","names":[],"sources":["../../src/io.ts"],"mappings":";;;;iBAuCsB,qBAAA,CACpB,GAAA,UACA,QAAA,EAAU,iBAAA,EACV,GAAA,EAAK,YAAA,GACJ,OAAA;AAJH;;;;;;;;;;;;;;;AAIU;AAgDV;;;;;;;;;AAGU;AA2BV;;;;AAlFA,iBAoDsB,2BAAA,CACpB,SAAA,UACA,GAAA,EAAK,gBAAA,GACJ,OAAO;;;;;;AA8BmB;AA6B7B;;;;;;;;;;AAGU;AAUV;;;;iBA7CsB,6CAAA,CACpB,SAAA,UACA,GAAA,EAAK,gBAAA,GACJ,OAAO;EAAA,SAAY,OAAA;AAAA;;;AA6CZ;AAIV;;;;;;;;iBApBsB,mBAAA,CACpB,OAAA,UACA,KAAA;EAAA,SAA2B,UAAA;EAAA,SAA6B,QAAA;AAAA,MACvD,OAAO;AAAA,iBAUY,sBAAA,CACpB,GAAA,UACA,QAAA,EAAU,iBAAA,GACT,OAAO;AAAA,iBAIY,iBAAA,CAAkB,GAAA,UAAa,GAAA,EAAK,YAAA,GAAe,OAAO;AAAA,iBAI1D,oBAAA,CAAqB,GAAA,WAAc,OAAO,CAAC,sBAAA;AAAA,iBAiG3C,iBAAA,CACpB,cAAA,WACC,OAAO,UAAU,sBAAA;AAAA,iBA+BJ,sBAAA,CAAuB,SAAA,EAAW,IAAI,EAAE,IAAA"}
|
package/dist/exports/io.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as materialiseMigrationPackage, c as writeMigrationMetadata, i as materialiseExtensionMigrationPackageIfMissing, l as writeMigrationOps, n as copyFilesWithRename, o as readMigrationPackage, r as formatMigrationDirName, s as readMigrationsDir, u as writeMigrationPackage } from "../io-
|
|
1
|
+
import { a as materialiseMigrationPackage, c as writeMigrationMetadata, i as materialiseExtensionMigrationPackageIfMissing, l as writeMigrationOps, n as copyFilesWithRename, o as readMigrationPackage, r as formatMigrationDirName, s as readMigrationsDir, u as writeMigrationPackage } from "../io-Dc64lvaL.mjs";
|
|
2
2
|
export { copyFilesWithRename, formatMigrationDirName, materialiseExtensionMigrationPackageIfMissing, materialiseMigrationPackage, readMigrationPackage, readMigrationsDir, writeMigrationMetadata, writeMigrationOps, writeMigrationPackage };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { type
|
|
1
|
+
import { t as MigrationMetadata } from "../metadata-BCH1rNsk.mjs";
|
|
2
|
+
export { type MigrationMetadata };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as MigrationGraph } from "../graph-
|
|
2
|
-
import { a as findLeaf, c as findPathWithInvariants, i as findLatestMigration, l as findReachableLeaves, n as detectCycles, o as findPath, r as detectOrphans, s as findPathWithDecision, t as PathDecision, u as reconstructGraph } from "../migration-graph-
|
|
1
|
+
import { n as MigrationGraph } from "../graph-ZAIvH6p4.mjs";
|
|
2
|
+
import { a as findLeaf, c as findPathWithInvariants, i as findLatestMigration, l as findReachableLeaves, n as detectCycles, o as findPath, r as detectOrphans, s as findPathWithDecision, t as PathDecision, u as reconstructGraph } from "../migration-graph-D97XMWVH.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/graph-membership.d.ts
|
|
5
5
|
declare function isGraphNode(hash: string, graph: MigrationGraph): boolean;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { c as errorHashNotInGraph } from "../errors-CoEN114u.mjs";
|
|
2
2
|
import "../constants-DWV9_o2Z.mjs";
|
|
3
|
-
import { a as findPath, c as findReachableLeaves, i as findLeaf, l as reconstructGraph, n as detectOrphans, o as findPathWithDecision, r as findLatestMigration, s as findPathWithInvariants, t as detectCycles } from "../migration-graph-
|
|
3
|
+
import { a as findPath, c as findReachableLeaves, i as findLeaf, l as reconstructGraph, n as detectOrphans, o as findPathWithDecision, r as findLatestMigration, s as findPathWithInvariants, t as detectCycles } from "../migration-graph-D5JeadSE.mjs";
|
|
4
4
|
//#region src/graph-membership.ts
|
|
5
5
|
function isGraphNode(hash, graph) {
|
|
6
6
|
if (hash === "sha256:empty") return true;
|
|
@@ -1,11 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as MigrationMetadata$1 } from "../metadata-BCH1rNsk.mjs";
|
|
2
2
|
import { ControlStack, MigrationPlan, MigrationPlanOperation } from "@prisma-next/framework-components/control";
|
|
3
3
|
|
|
4
4
|
//#region src/migration-base.d.ts
|
|
5
5
|
interface MigrationMeta {
|
|
6
6
|
readonly from: string | null;
|
|
7
7
|
readonly to: string;
|
|
8
|
-
readonly labels?: readonly string[];
|
|
9
8
|
}
|
|
10
9
|
/**
|
|
11
10
|
* Base class for migrations.
|
|
@@ -77,10 +76,10 @@ interface MigrationArtifacts {
|
|
|
77
76
|
* Pure conversion from a `Migration` instance (plus the previously
|
|
78
77
|
* scaffolded metadata, when one exists on disk) to the in-memory
|
|
79
78
|
* artifacts that downstream tooling persists. Owns metadata validation,
|
|
80
|
-
* metadata synthesis/preservation,
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
* `
|
|
79
|
+
* metadata synthesis/preservation, and the content-addressed
|
|
80
|
+
* `migrationHash` computation, but performs no file I/O — callers handle
|
|
81
|
+
* reads (to source `existing`) and writes (to persist `opsJson` /
|
|
82
|
+
* `metadataJson`).
|
|
84
83
|
*/
|
|
85
84
|
declare function buildMigrationArtifacts(instance: Migration, existing: Partial<MigrationMetadata$1> | null): MigrationArtifacts;
|
|
86
85
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.d.mts","names":[],"sources":["../../src/migration-base.ts"],"mappings":";;;;UAeiB,aAAA;EAAA,SACN,IAAA;EAAA,SACA,
|
|
1
|
+
{"version":3,"file":"migration.d.mts","names":[],"sources":["../../src/migration-base.ts"],"mappings":";;;;UAeiB,aAAA;EAAA,SACN,IAAA;EAAA,SACA,EAAE;AAAA;;;AAAA;AAsBb;;;;;;uBAAsB,SAAA,oBACD,sBAAA,GAAyB,sBAAA,mFAGjC,aAAA;EAAA,kBAEO,QAAA;EAae;;;;;;;;;EAAA,mBAFd,KAAA,EAAO,YAAA,CAAa,SAAA,EAAW,SAAA;cAEtC,KAAA,GAAQ,YAAA,CAAa,SAAA,EAAW,SAAA;EAjB5C;;;;;;EAAA,aA2Ba,UAAA,CAAA,YAAuB,UAAA;EAZc;;;;;EAAA,SAmBzC,QAAA,CAAA,GAAY,aAAA;EAAA,IAEjB,MAAA,CAAA;IAAA,SAAqB,WAAA;EAAA;EAAA,IAKrB,WAAA,CAAA;IAAA,SAA0B,WAAA;EAAA;AAAA;;;AAAW;AAY3C;;;;iBAAgB,kBAAA,CAAmB,aAAqB;AAsBxD;;;;;;;;;AAGuB;AA4CvB;AA/CA,UAAiB,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,QAAA,EAAU,mBAAiB;EAAA,SAC3B,YAAA;AAAA;;;;;;;;;;iBA4CK,uBAAA,CACd,QAAA,EAAU,SAAA,EACV,QAAA,EAAU,OAAA,CAAQ,mBAAA,WACjB,kBAAA"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { p as errorInvalidOperationEntry } from "../errors-CoEN114u.mjs";
|
|
2
|
-
import { t as computeMigrationHash } from "../hash
|
|
2
|
+
import { t as computeMigrationHash } from "../hash--Y7vCpN3.mjs";
|
|
3
3
|
import { t as deriveProvidedInvariants } from "../invariants-lbJddL-S.mjs";
|
|
4
4
|
import { t as MigrationOpSchema } from "../op-schema-D5qkXfEf.mjs";
|
|
5
5
|
import { type } from "arktype";
|
|
@@ -8,8 +8,7 @@ import { fileURLToPath } from "node:url";
|
|
|
8
8
|
//#region src/migration-base.ts
|
|
9
9
|
const MigrationMetaSchema = type({
|
|
10
10
|
from: "string > 0 | null",
|
|
11
|
-
to: "string"
|
|
12
|
-
"labels?": type("string").array()
|
|
11
|
+
to: "string"
|
|
13
12
|
});
|
|
14
13
|
/**
|
|
15
14
|
* Base class for migrations.
|
|
@@ -64,12 +63,11 @@ function isDirectEntrypoint(importMetaUrl) {
|
|
|
64
63
|
* operations list, and the previously-scaffolded metadata (if any).
|
|
65
64
|
*
|
|
66
65
|
* When a `migration.json` already exists for this package (the common
|
|
67
|
-
* case: it was scaffolded by `migration plan`), preserve
|
|
68
|
-
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
* `migration.ts` run from scratch), synthesize a minimal but
|
|
66
|
+
* case: it was scaffolded by `migration plan`), preserve `createdAt`
|
|
67
|
+
* set there — that field is owned by the CLI scaffolder, not the authored
|
|
68
|
+
* class. Only the `describe()`-derived fields (`from`, `to`) and the
|
|
69
|
+
* operations change as the author iterates. When no metadata exists yet
|
|
70
|
+
* (a bare `migration.ts` run from scratch), synthesize a minimal but
|
|
73
71
|
* schema-conformant record so the resulting package can still be read,
|
|
74
72
|
* verified, and applied.
|
|
75
73
|
*
|
|
@@ -80,10 +78,8 @@ function buildAttestedMetadata(meta, ops, existing) {
|
|
|
80
78
|
const baseMetadata = {
|
|
81
79
|
from: meta.from,
|
|
82
80
|
to: meta.to,
|
|
83
|
-
labels: meta.labels ?? existing?.labels ?? [],
|
|
84
81
|
providedInvariants: deriveProvidedInvariants(ops),
|
|
85
|
-
createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
86
|
-
hints: normalizeHints(existing?.hints)
|
|
82
|
+
createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
87
83
|
};
|
|
88
84
|
const migrationHash = computeMigrationHash(baseMetadata, ops);
|
|
89
85
|
return {
|
|
@@ -92,27 +88,13 @@ function buildAttestedMetadata(meta, ops, existing) {
|
|
|
92
88
|
};
|
|
93
89
|
}
|
|
94
90
|
/**
|
|
95
|
-
* Project `existing.hints` down to the known `MigrationHints` shape, dropping
|
|
96
|
-
* any legacy keys that may linger in metadata scaffolded by older CLI
|
|
97
|
-
* versions (e.g. `planningStrategy`). Picking fields explicitly instead of
|
|
98
|
-
* spreading keeps refreshed `migration.json` files schema-clean regardless
|
|
99
|
-
* of what was on disk before.
|
|
100
|
-
*/
|
|
101
|
-
function normalizeHints(existing) {
|
|
102
|
-
return {
|
|
103
|
-
used: existing?.used ?? [],
|
|
104
|
-
applied: existing?.applied ?? [],
|
|
105
|
-
plannerVersion: existing?.plannerVersion ?? "2.0.0"
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
/**
|
|
109
91
|
* Pure conversion from a `Migration` instance (plus the previously
|
|
110
92
|
* scaffolded metadata, when one exists on disk) to the in-memory
|
|
111
93
|
* artifacts that downstream tooling persists. Owns metadata validation,
|
|
112
|
-
* metadata synthesis/preservation,
|
|
113
|
-
*
|
|
114
|
-
*
|
|
115
|
-
* `
|
|
94
|
+
* metadata synthesis/preservation, and the content-addressed
|
|
95
|
+
* `migrationHash` computation, but performs no file I/O — callers handle
|
|
96
|
+
* reads (to source `existing`) and writes (to persist `opsJson` /
|
|
97
|
+
* `metadataJson`).
|
|
116
98
|
*/
|
|
117
99
|
function buildMigrationArtifacts(instance, existing) {
|
|
118
100
|
const ops = instance.operations;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migration.mjs","names":[],"sources":["../../src/migration-base.ts"],"sourcesContent":["import { realpathSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport type {\n ControlStack,\n MigrationPlan,\n MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport { type } from 'arktype';\nimport { errorInvalidOperationEntry } from './errors';\nimport { computeMigrationHash } from './hash';\nimport { deriveProvidedInvariants } from './invariants';\nimport type {
|
|
1
|
+
{"version":3,"file":"migration.mjs","names":[],"sources":["../../src/migration-base.ts"],"sourcesContent":["import { realpathSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport type {\n ControlStack,\n MigrationPlan,\n MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport { type } from 'arktype';\nimport { errorInvalidOperationEntry } from './errors';\nimport { computeMigrationHash } from './hash';\nimport { deriveProvidedInvariants } from './invariants';\nimport type { MigrationMetadata } from './metadata';\nimport { MigrationOpSchema } from './op-schema';\nimport type { MigrationOps } from './package';\n\nexport interface MigrationMeta {\n readonly from: string | null;\n readonly to: string;\n}\n\n// `from` rejects empty strings to mirror `MigrationMetadataSchema` in\n// `./io.ts`. Without this match, an authored migration could `describe()` with\n// `from: ''` and pass `buildMigrationArtifacts`'s validation, only to have\n// `readMigrationPackage` reject the resulting `migration.json` later — the\n// two validators must agree on the legal value space.\nconst MigrationMetaSchema = type({\n from: 'string > 0 | null',\n to: 'string',\n});\n\n/**\n * Base class for migrations.\n *\n * A `Migration` subclass is itself a `MigrationPlan`: CLI commands and the\n * runner can consume it directly via `targetId`, `operations`, `origin`, and\n * `destination`. The metadata-shaped inputs come from `describe()`, which\n * every migration must implement — `migration.json` is required for a\n * migration to be valid.\n */\nexport abstract class Migration<\n TOperation extends MigrationPlanOperation = MigrationPlanOperation,\n TFamilyId extends string = string,\n TTargetId extends string = string,\n> implements MigrationPlan\n{\n abstract readonly targetId: string;\n\n /**\n * Assembled `ControlStack` injected by the orchestrator (`runMigration`).\n *\n * Subclasses (e.g. `PostgresMigration`) read the stack to materialize their\n * adapter once per instance. Optional at the abstract level so unit tests can\n * construct `Migration` instances purely for `operations` / `describe`\n * assertions without needing a real stack; concrete subclasses that need the\n * stack at runtime should narrow the parameter to required.\n */\n protected readonly stack: ControlStack<TFamilyId, TTargetId> | undefined;\n\n constructor(stack?: ControlStack<TFamilyId, TTargetId>) {\n this.stack = stack;\n }\n\n /**\n * Ordered list of operations this migration performs.\n *\n * Implemented as a getter so that subclasses can either precompute the list\n * in their constructor or build it lazily per access.\n */\n abstract get operations(): readonly TOperation[];\n\n /**\n * Metadata inputs used to build `migration.json` and to derive the plan's\n * origin/destination identities. Every migration must provide this —\n * omitting it would produce an invalid on-disk migration package.\n */\n abstract describe(): MigrationMeta;\n\n get origin(): { readonly storageHash: string } | null {\n const from = this.describe().from;\n return from === null ? null : { storageHash: from };\n }\n\n get destination(): { readonly storageHash: string } {\n return { storageHash: this.describe().to };\n }\n}\n\n/**\n * Returns true when `import.meta.url` resolves to the same file that was\n * invoked as the node entrypoint (`process.argv[1]`). Used by\n * `MigrationCLI.run` (in `@prisma-next/cli/migration-cli`) to no-op when\n * the migration module is being imported (e.g. by another script) rather\n * than executed directly.\n */\nexport function isDirectEntrypoint(importMetaUrl: string): boolean {\n const metaFilename = fileURLToPath(importMetaUrl);\n const argv1 = process.argv[1];\n if (!argv1) return false;\n try {\n return realpathSync(metaFilename) === realpathSync(argv1);\n } catch {\n return false;\n }\n}\n\n/**\n * In-memory artifacts produced from a `Migration` instance: the\n * serialized `ops.json` body, the `migration.json` metadata object, and\n * its serialized form. Returned by `buildMigrationArtifacts` so callers\n * (today: `MigrationCLI.run` in `@prisma-next/cli/migration-cli`) can\n * decide how to persist them — write to disk, print in dry-run, ship\n * over the wire — without coupling artifact construction to file I/O.\n *\n * `metadataJson` is `JSON.stringify(metadata, null, 2)` — the canonical\n * on-disk shape that the arktype loader-schema in `./io` validates.\n */\nexport interface MigrationArtifacts {\n readonly opsJson: string;\n readonly metadata: MigrationMetadata;\n readonly metadataJson: string;\n}\n\n/**\n * Build the attested metadata from `describe()`-derived metadata, the\n * operations list, and the previously-scaffolded metadata (if any).\n *\n * When a `migration.json` already exists for this package (the common\n * case: it was scaffolded by `migration plan`), preserve `createdAt`\n * set there — that field is owned by the CLI scaffolder, not the authored\n * class. Only the `describe()`-derived fields (`from`, `to`) and the\n * operations change as the author iterates. When no metadata exists yet\n * (a bare `migration.ts` run from scratch), synthesize a minimal but\n * schema-conformant record so the resulting package can still be read,\n * verified, and applied.\n *\n * The `migrationHash` is recomputed against the current metadata + ops so\n * the on-disk artifacts are always fully attested.\n */\nfunction buildAttestedMetadata(\n meta: MigrationMeta,\n ops: MigrationOps,\n existing: Partial<MigrationMetadata> | null,\n): MigrationMetadata {\n const baseMetadata: Omit<MigrationMetadata, 'migrationHash'> = {\n from: meta.from,\n to: meta.to,\n providedInvariants: deriveProvidedInvariants(ops),\n createdAt: existing?.createdAt ?? new Date().toISOString(),\n };\n\n const migrationHash = computeMigrationHash(baseMetadata, ops);\n return { ...baseMetadata, migrationHash };\n}\n\n/**\n * Pure conversion from a `Migration` instance (plus the previously\n * scaffolded metadata, when one exists on disk) to the in-memory\n * artifacts that downstream tooling persists. Owns metadata validation,\n * metadata synthesis/preservation, and the content-addressed\n * `migrationHash` computation, but performs no file I/O — callers handle\n * reads (to source `existing`) and writes (to persist `opsJson` /\n * `metadataJson`).\n */\nexport function buildMigrationArtifacts(\n instance: Migration,\n existing: Partial<MigrationMetadata> | null,\n): MigrationArtifacts {\n const ops = instance.operations;\n if (!Array.isArray(ops)) {\n throw new Error('operations must be an array');\n }\n\n for (let index = 0; index < ops.length; index++) {\n const result = MigrationOpSchema(ops[index]);\n if (result instanceof type.errors) {\n throw errorInvalidOperationEntry(index, result.summary);\n }\n }\n\n const rawMeta: unknown = instance.describe();\n const parsed = MigrationMetaSchema(rawMeta);\n if (parsed instanceof type.errors) {\n throw new Error(`describe() returned invalid metadata: ${parsed.summary}`);\n }\n\n const metadata = buildAttestedMetadata(parsed, ops, existing);\n\n return {\n opsJson: JSON.stringify(ops, null, 2),\n metadata,\n metadataJson: JSON.stringify(metadata, null, 2),\n };\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,sBAAsB,KAAK;CAC/B,MAAM;CACN,IAAI;AACN,CAAC;;;;;;;;;;AAWD,IAAsB,YAAtB,MAKA;;;;;;;;;;CAYE;CAEA,YAAY,OAA4C;EACtD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pC;EACA,cAAc,KAAK,UAAU,UAAU,MAAM,CAAC;CAChD;AACF"}
|
package/dist/exports/spaces.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { r as errorDescriptorHeadHashMismatch, s as errorDuplicateSpaceId } from "../errors-CoEN114u.mjs";
|
|
2
|
-
import { s as readMigrationsDir } from "../io-
|
|
2
|
+
import { s as readMigrationsDir } from "../io-Dc64lvaL.mjs";
|
|
3
3
|
import "../constants-DWV9_o2Z.mjs";
|
|
4
|
-
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-
|
|
5
|
-
import { a as SPACE_REFS_DIRNAME, c as spaceMigrationDirectory, i as RESERVED_SPACE_SUBDIR_NAMES, l as spaceRefsDirectory, n as verifyContractSpaces, o as assertValidSpaceId, r as APP_SPACE_ID, s as isValidSpaceId, t as listContractSpaceDirectories } from "../verify-contract-spaces-
|
|
6
|
-
import { n as readContractSpaceHeadRef, t as readContractSpaceContract } from "../read-contract-space-contract-
|
|
4
|
+
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-D5JeadSE.mjs";
|
|
5
|
+
import { a as SPACE_REFS_DIRNAME, c as spaceMigrationDirectory, i as RESERVED_SPACE_SUBDIR_NAMES, l as spaceRefsDirectory, n as verifyContractSpaces, o as assertValidSpaceId, r as APP_SPACE_ID, s as isValidSpaceId, t as listContractSpaceDirectories } from "../verify-contract-spaces-DIdQLGo7.mjs";
|
|
6
|
+
import { n as readContractSpaceHeadRef, t as readContractSpaceContract } from "../read-contract-space-contract-_EvvV5Gl.mjs";
|
|
7
7
|
import { join } from "pathe";
|
|
8
8
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
9
9
|
import { canonicalizeJson } from "@prisma-next/framework-components/utils";
|
|
@@ -9,7 +9,6 @@ interface MigrationEdge {
|
|
|
9
9
|
readonly migrationHash: string;
|
|
10
10
|
readonly dirName: string;
|
|
11
11
|
readonly createdAt: string;
|
|
12
|
-
readonly labels: readonly string[];
|
|
13
12
|
/**
|
|
14
13
|
* Sorted, deduplicated list of `invariantId`s this edge provides.
|
|
15
14
|
* An empty array means the migration declares no routing-visible
|
|
@@ -25,4 +24,4 @@ interface MigrationGraph {
|
|
|
25
24
|
}
|
|
26
25
|
//#endregion
|
|
27
26
|
export { MigrationGraph as n, MigrationEdge as t };
|
|
28
|
-
//# sourceMappingURL=graph-
|
|
27
|
+
//# sourceMappingURL=graph-ZAIvH6p4.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph-ZAIvH6p4.d.mts","names":[],"sources":["../src/graph.ts"],"mappings":";;AAIA;;;UAAiB,aAAA;EAAA,SACN,IAAA;EAAA,SACA,EAAA;EAAA,SACA,aAAA;EAAA,SACA,OAAA;EAAA,SACA,SAAA;EAMA;;AAAU;AAGrB;;EAHW,SAAA,UAAA;AAAA;AAAA,UAGM,cAAA;EAAA,SACN,KAAA,EAAO,WAAA;EAAA,SACP,YAAA,EAAc,WAAA,kBAA6B,aAAA;EAAA,SAC3C,YAAA,EAAc,WAAA,kBAA6B,aAAA;EAAA,SAC3C,eAAA,EAAiB,WAAA,SAAoB,aAAA;AAAA"}
|
|
@@ -5,13 +5,12 @@ function sha256Hex(input) {
|
|
|
5
5
|
return createHash("sha256").update(input).digest("hex");
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
|
-
* Content-addressed migration hash over (metadata envelope
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* authored alongside the migration, never inlined here.
|
|
8
|
+
* Content-addressed migration hash over (metadata envelope, ops). See
|
|
9
|
+
* ADR 199 — Storage-only migration identity for the rationale: the
|
|
10
|
+
* storage-hash bookends (`from`, `to`) inside the envelope anchor the
|
|
11
|
+
* contract identity by hash. The full contract IRs are not part of the
|
|
12
|
+
* manifest — they live in sibling `*-contract.json` files authored
|
|
13
|
+
* alongside the migration, never inlined here.
|
|
15
14
|
*
|
|
16
15
|
* The integrity check is purely structural, not semantic. The function
|
|
17
16
|
* canonicalizes its inputs via `sortKeys` (recursive) + `JSON.stringify`
|
|
@@ -33,7 +32,7 @@ function sha256Hex(input) {
|
|
|
33
32
|
* yet) and at verify time (rehashing an already-attested record).
|
|
34
33
|
*/
|
|
35
34
|
function computeMigrationHash(metadata, ops) {
|
|
36
|
-
const { migrationHash: _migrationHash,
|
|
35
|
+
const { migrationHash: _migrationHash, ...strippedMeta } = metadata;
|
|
37
36
|
return `sha256:${sha256Hex(canonicalizeJson([canonicalizeJson(strippedMeta), canonicalizeJson(ops)].map(sha256Hex)))}`;
|
|
38
37
|
}
|
|
39
38
|
/**
|
|
@@ -62,4 +61,4 @@ function verifyMigrationHash(pkg) {
|
|
|
62
61
|
//#endregion
|
|
63
62
|
export { verifyMigrationHash as n, computeMigrationHash as t };
|
|
64
63
|
|
|
65
|
-
//# sourceMappingURL=hash
|
|
64
|
+
//# sourceMappingURL=hash--Y7vCpN3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hash--Y7vCpN3.mjs","names":[],"sources":["../src/hash.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport type { MigrationMetadata } from './metadata';\nimport type { MigrationOps, OnDiskMigrationPackage } from './package';\n\nexport interface VerifyResult {\n readonly ok: boolean;\n readonly reason?: 'mismatch';\n readonly storedHash: string;\n readonly computedHash: string;\n}\n\nfunction sha256Hex(input: string): string {\n return createHash('sha256').update(input).digest('hex');\n}\n\n/**\n * Content-addressed migration hash over (metadata envelope, ops). See\n * ADR 199 — Storage-only migration identity for the rationale: the\n * storage-hash bookends (`from`, `to`) inside the envelope anchor the\n * contract identity by hash. The full contract IRs are not part of the\n * manifest — they live in sibling `*-contract.json` files authored\n * alongside the migration, never inlined here.\n *\n * The integrity check is purely structural, not semantic. The function\n * canonicalizes its inputs via `sortKeys` (recursive) + `JSON.stringify`\n * and hashes the result. Target-specific operation payloads (`step.sql`,\n * Mongo's pipeline AST, …) are hashed verbatim — no per-target\n * normalization is required, because what's being verified is \"do the\n * on-disk bytes still produce their recorded hash\", not \"do two\n * semantically-equivalent migrations hash the same\". The latter is an\n * emit-drift concern (ADR 192 step 2).\n *\n * The symmetry across write and read holds because `JSON.parse(\n * JSON.stringify(x))` round-trips JSON-safe values losslessly and\n * `sortKeys` is idempotent and deterministic — write-time and read-time\n * canonicalization produce the same canonical bytes regardless of\n * source-side key ordering or whitespace.\n *\n * The `migrationHash` field on the metadata is stripped before hashing\n * so the function can be used both at write time (when no hash exists\n * yet) and at verify time (rehashing an already-attested record).\n */\nexport function computeMigrationHash(\n metadata: Omit<MigrationMetadata, 'migrationHash'> & { readonly migrationHash?: string },\n ops: MigrationOps,\n): string {\n const { migrationHash: _migrationHash, ...strippedMeta } = metadata;\n\n const canonicalMetadata = canonicalizeJson(strippedMeta);\n const canonicalOps = canonicalizeJson(ops);\n\n const partHashes = [canonicalMetadata, canonicalOps].map(sha256Hex);\n const hash = sha256Hex(canonicalizeJson(partHashes));\n\n return `sha256:${hash}`;\n}\n\n/**\n * Re-hash an in-memory migration package and compare against the stored\n * `migrationHash`. See `computeMigrationHash` for the canonicalization rules.\n *\n * Returns `{ ok: true }` when the package is internally consistent, or\n * `{ ok: false, reason: 'mismatch', storedHash, computedHash }` when it is\n * not — typically a sign of FS corruption, partial writes, or a post-emit\n * hand edit.\n */\nexport function verifyMigrationHash(pkg: OnDiskMigrationPackage): VerifyResult {\n const computed = computeMigrationHash(pkg.metadata, pkg.ops);\n\n if (pkg.metadata.migrationHash === computed) {\n return {\n ok: true,\n storedHash: pkg.metadata.migrationHash,\n computedHash: computed,\n };\n }\n\n return {\n ok: false,\n reason: 'mismatch',\n storedHash: pkg.metadata.migrationHash,\n computedHash: computed,\n };\n}\n"],"mappings":";;;AAYA,SAAS,UAAU,OAAuB;CACxC,OAAO,WAAW,QAAQ,EAAE,OAAO,KAAK,EAAE,OAAO,KAAK;AACxD;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,qBACd,UACA,KACQ;CACR,MAAM,EAAE,eAAe,gBAAgB,GAAG,iBAAiB;CAQ3D,OAAO,UAFM,UAAU,iBADJ,CAHO,iBAAiB,YAGP,GAFf,iBAAiB,GAEY,CAAC,EAAE,IAAI,SACR,CAAC,CAE9B;AACtB;;;;;;;;;;AAWA,SAAgB,oBAAoB,KAA2C;CAC7E,MAAM,WAAW,qBAAqB,IAAI,UAAU,IAAI,GAAG;CAE3D,IAAI,IAAI,SAAS,kBAAkB,UACjC,OAAO;EACL,IAAI;EACJ,YAAY,IAAI,SAAS;EACzB,cAAc;CAChB;CAGF,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,YAAY,IAAI,SAAS;EACzB,cAAc;CAChB;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as errorInvalidSlug, b as errorMissingFile, d as errorInvalidJson, f as errorInvalidManifest, i as errorDirectoryExists, l as errorInvalidDestName, w as errorProvidedInvariantsMismatch, y as errorMigrationHashMismatch } from "./errors-CoEN114u.mjs";
|
|
2
|
-
import { n as verifyMigrationHash } from "./hash
|
|
2
|
+
import { n as verifyMigrationHash } from "./hash--Y7vCpN3.mjs";
|
|
3
3
|
import { t as deriveProvidedInvariants } from "./invariants-lbJddL-S.mjs";
|
|
4
4
|
import { n as MigrationOpsSchema } from "./op-schema-D5qkXfEf.mjs";
|
|
5
5
|
import { basename, dirname, join, resolve } from "pathe";
|
|
@@ -17,12 +17,6 @@ const MigrationMetadataSchema = type({
|
|
|
17
17
|
from: "string > 0 | null",
|
|
18
18
|
to: "string",
|
|
19
19
|
migrationHash: "string",
|
|
20
|
-
hints: type({
|
|
21
|
-
used: "string[]",
|
|
22
|
-
applied: "string[]",
|
|
23
|
-
plannerVersion: "string"
|
|
24
|
-
}),
|
|
25
|
-
labels: "string[]",
|
|
26
20
|
providedInvariants: "string[]",
|
|
27
21
|
createdAt: "string"
|
|
28
22
|
});
|
|
@@ -221,4 +215,4 @@ function formatMigrationDirName(timestamp, slug) {
|
|
|
221
215
|
//#endregion
|
|
222
216
|
export { materialiseMigrationPackage as a, writeMigrationMetadata as c, materialiseExtensionMigrationPackageIfMissing as i, writeMigrationOps as l, copyFilesWithRename as n, readMigrationPackage as o, formatMigrationDirName as r, readMigrationsDir as s, MANIFEST_FILE as t, writeMigrationPackage as u };
|
|
223
217
|
|
|
224
|
-
//# sourceMappingURL=io-
|
|
218
|
+
//# sourceMappingURL=io-Dc64lvaL.mjs.map
|