@prisma-next/migration-tools 0.5.0-dev.66 → 0.5.0-dev.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/{constants-B87kJAGj.mjs → constants-DWV9_o2Z.mjs} +2 -2
  2. package/dist/{constants-B87kJAGj.mjs.map → constants-DWV9_o2Z.mjs.map} +1 -1
  3. package/dist/{errors-DQsXvidG.mjs → errors-EPL_9p9f.mjs} +13 -8
  4. package/dist/errors-EPL_9p9f.mjs.map +1 -0
  5. package/dist/exports/aggregate.d.mts +534 -0
  6. package/dist/exports/aggregate.d.mts.map +1 -0
  7. package/dist/exports/aggregate.mjs +598 -0
  8. package/dist/exports/aggregate.mjs.map +1 -0
  9. package/dist/exports/constants.d.mts.map +1 -1
  10. package/dist/exports/constants.mjs +2 -3
  11. package/dist/exports/errors.d.mts +6 -1
  12. package/dist/exports/errors.d.mts.map +1 -1
  13. package/dist/exports/errors.mjs +2 -3
  14. package/dist/exports/graph.d.mts +1 -1
  15. package/dist/exports/graph.mjs +1 -1
  16. package/dist/exports/hash.d.mts +2 -2
  17. package/dist/exports/hash.d.mts.map +1 -1
  18. package/dist/exports/hash.mjs +2 -3
  19. package/dist/exports/invariants.d.mts +14 -4
  20. package/dist/exports/invariants.d.mts.map +1 -1
  21. package/dist/exports/invariants.mjs +2 -4
  22. package/dist/exports/io.d.mts +26 -2
  23. package/dist/exports/io.d.mts.map +1 -1
  24. package/dist/exports/io.mjs +2 -5
  25. package/dist/exports/metadata.d.mts +1 -1
  26. package/dist/exports/metadata.mjs +1 -1
  27. package/dist/exports/migration-graph.d.mts +2 -2
  28. package/dist/exports/migration-graph.d.mts.map +1 -1
  29. package/dist/exports/migration-graph.mjs +1 -525
  30. package/dist/exports/migration-ts.d.mts.map +1 -1
  31. package/dist/exports/migration-ts.mjs +1 -3
  32. package/dist/exports/migration-ts.mjs.map +1 -1
  33. package/dist/exports/migration.d.mts +1 -1
  34. package/dist/exports/migration.d.mts.map +1 -1
  35. package/dist/exports/migration.mjs +5 -6
  36. package/dist/exports/migration.mjs.map +1 -1
  37. package/dist/exports/package.d.mts +1 -1
  38. package/dist/exports/package.mjs +1 -1
  39. package/dist/exports/refs.d.mts.map +1 -1
  40. package/dist/exports/refs.mjs +2 -3
  41. package/dist/exports/refs.mjs.map +1 -1
  42. package/dist/exports/spaces.d.mts +341 -238
  43. package/dist/exports/spaces.d.mts.map +1 -1
  44. package/dist/exports/spaces.mjs +138 -348
  45. package/dist/exports/spaces.mjs.map +1 -1
  46. package/dist/{graph-Czaj8O2q.d.mts → graph-HMWAldoR.d.mts} +1 -1
  47. package/dist/graph-HMWAldoR.d.mts.map +1 -0
  48. package/dist/{hash-G0bAfIGh.mjs → hash-By50zM_E.mjs} +2 -4
  49. package/dist/hash-By50zM_E.mjs.map +1 -0
  50. package/dist/{invariants-4Avb_Yhy.mjs → invariants-Duc8f9NM.mjs} +17 -7
  51. package/dist/invariants-Duc8f9NM.mjs.map +1 -0
  52. package/dist/{io-CDJaWGbt.mjs → io-D13dLvUh.mjs} +46 -14
  53. package/dist/io-D13dLvUh.mjs.map +1 -0
  54. package/dist/migration-graph-DGNnKDY5.mjs +523 -0
  55. package/dist/migration-graph-DGNnKDY5.mjs.map +1 -0
  56. package/dist/{op-schema-BiF1ZYqH.mjs → op-schema-D5qkXfEf.mjs} +2 -3
  57. package/dist/{op-schema-BiF1ZYqH.mjs.map → op-schema-D5qkXfEf.mjs.map} +1 -1
  58. package/dist/{package-B3Yl6DTr.d.mts → package-BjiZ7KDy.d.mts} +1 -1
  59. package/dist/package-BjiZ7KDy.d.mts.map +1 -0
  60. package/dist/read-contract-space-contract-C3-1eyaI.mjs +298 -0
  61. package/dist/read-contract-space-contract-C3-1eyaI.mjs.map +1 -0
  62. package/package.json +13 -9
  63. package/src/aggregate/loader.ts +409 -0
  64. package/src/aggregate/marker-types.ts +16 -0
  65. package/src/aggregate/planner-types.ts +137 -0
  66. package/src/aggregate/planner.ts +158 -0
  67. package/src/aggregate/project-schema-to-space.ts +64 -0
  68. package/src/aggregate/strategies/graph-walk.ts +92 -0
  69. package/src/aggregate/strategies/synth.ts +122 -0
  70. package/src/aggregate/types.ts +89 -0
  71. package/src/aggregate/verifier.ts +230 -0
  72. package/src/assert-descriptor-self-consistency.ts +70 -0
  73. package/src/compute-extension-space-apply-path.ts +152 -0
  74. package/src/concatenate-space-apply-inputs.ts +2 -2
  75. package/src/detect-space-contract-drift.ts +22 -26
  76. package/src/{emit-pinned-space-artefacts.ts → emit-contract-space-artefacts.ts} +14 -33
  77. package/src/errors.ts +11 -5
  78. package/src/exports/aggregate.ts +37 -0
  79. package/src/exports/errors.ts +1 -0
  80. package/src/exports/io.ts +1 -0
  81. package/src/exports/spaces.ts +23 -10
  82. package/src/gather-disk-contract-space-state.ts +62 -0
  83. package/src/invariants.ts +14 -3
  84. package/src/io.ts +42 -0
  85. package/src/plan-all-spaces.ts +3 -7
  86. package/src/read-contract-space-contract.ts +44 -0
  87. package/src/read-contract-space-head-ref.ts +63 -0
  88. package/src/space-layout.ts +4 -11
  89. package/src/verify-contract-spaces.ts +45 -49
  90. package/dist/errors-DQsXvidG.mjs.map +0 -1
  91. package/dist/exports/migration-graph.mjs.map +0 -1
  92. package/dist/graph-Czaj8O2q.d.mts.map +0 -1
  93. package/dist/hash-G0bAfIGh.mjs.map +0 -1
  94. package/dist/invariants-4Avb_Yhy.mjs.map +0 -1
  95. package/dist/io-CDJaWGbt.mjs.map +0 -1
  96. package/dist/package-B3Yl6DTr.d.mts.map +0 -1
  97. package/src/read-pinned-contract-hash.ts +0 -77
  98. /package/dist/{metadata-CSjwljJx.d.mts → metadata-BnLFiI6B.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"spaces.mjs","names":["extensions: SpaceApplyInput<TOp>[]","appSpace: SpaceApplyInput<TOp> | undefined","hasErrnoCode","raw: string","parsed: unknown","entries: { readonly name: string; readonly isDirectory: boolean }[]","violations: SpaceVerifierViolation[]","kindOrder: Record<SpaceVerifierViolation['kind'], number>"],"sources":["../../src/space-layout.ts","../../src/concatenate-space-apply-inputs.ts","../../src/detect-space-contract-drift.ts","../../src/emit-pinned-space-artefacts.ts","../../src/plan-all-spaces.ts","../../src/read-pinned-contract-hash.ts","../../src/verify-contract-spaces.ts"],"sourcesContent":["import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { join } from 'pathe';\nimport { errorInvalidSpaceId } from './errors';\n\nexport { APP_SPACE_ID };\n\n/**\n * Branded string carrying a compile-time guarantee that the value has\n * been validated by {@link assertValidSpaceId}. Downstream filesystem\n * helpers (e.g. {@link spaceMigrationDirectory}) accept this type to\n * make \"validated\" tracking visible at the type level rather than\n * relying purely on a runtime check.\n */\nexport type ValidSpaceId = string & { readonly __brand: 'ValidSpaceId' };\n\n/**\n * Pattern a contract-space identifier must match. The constraint is\n * filesystem-friendly: lowercase letters / digits / hyphen / underscore,\n * starts with a letter, max 64 characters.\n *\n * @see specs/framework-mechanism.spec.md § 3.\n */\nconst SPACE_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;\n\nexport function isValidSpaceId(spaceId: string): spaceId is ValidSpaceId {\n return SPACE_ID_PATTERN.test(spaceId);\n}\n\nexport function assertValidSpaceId(spaceId: string): asserts spaceId is ValidSpaceId {\n if (!isValidSpaceId(spaceId)) {\n throw errorInvalidSpaceId(spaceId);\n }\n}\n\n/**\n * Resolve the migrations subdirectory for a given contract space.\n *\n * - **App space** (`spaceId === APP_SPACE_ID`) keeps today's layout: the\n * project's `migrations/` directory is the migrations directory, no\n * subdirectory.\n * - **Extension space** lands under `<projectMigrationsDir>/<spaceId>/`.\n * The space id is validated against {@link SPACE_ID_PATTERN} because\n * it becomes a filesystem directory name verbatim.\n *\n * `projectMigrationsDir` is the project's top-level `migrations/`\n * directory; the helper does not assume anything about its absolute /\n * relative shape and is symmetric with `pathe.join`.\n */\nexport function spaceMigrationDirectory(projectMigrationsDir: string, spaceId: string): string {\n if (spaceId === APP_SPACE_ID) {\n return projectMigrationsDir;\n }\n assertValidSpaceId(spaceId);\n return join(projectMigrationsDir, spaceId);\n}\n","import { errorDuplicateSpaceId } from './errors';\nimport { APP_SPACE_ID } from './space-layout';\n\n/**\n * Per-space input the runner consumes when applying a migration.\n *\n * The shape is target-agnostic: callers (today the SQL family; later\n * any other family) bind `TOp` to their own per-target operation type\n * (e.g. `SqlMigrationPlanOperation<TTargetDetails>` for the SQL family)\n * and the helper preserves it through the concatenation.\n *\n * - `migrationDirectory` is the on-disk migration directory for the\n * space — `<projectRoot>/migrations` for `'app'` and\n * `<projectRoot>/migrations/<space-id>` for an extension space.\n * - `currentMarkerHash` and `currentMarkerInvariants` are the values\n * read from the `prisma_contract.marker` row keyed by `space = <space-id>`\n * (T1.1). `null` hash = no marker row yet.\n * - `path` is the per-space operation list resolved from\n * `findPathWithDecision(currentMarker, ref.hash, effectiveRequired)`\n * per ADR 208, materialised against the on-disk migration packages.\n *\n * @see specs/framework-mechanism.spec.md § 4 — Runner.\n */\nexport interface SpaceApplyInput<TOp> {\n readonly spaceId: string;\n readonly migrationDirectory: string;\n readonly currentMarkerHash: string | null;\n readonly currentMarkerInvariants: readonly string[];\n readonly path: readonly TOp[];\n}\n\n/**\n * Order a set of per-space apply inputs into the canonical cross-space\n * sequence the runner applies under a single transaction.\n *\n * Cross-space ordering convention (sub-spec § 4):\n *\n * 1. **Extension spaces first**, alphabetically by `spaceId`.\n * 2. **App space last** — only one `'app'` entry expected, at most.\n *\n * Rationale: extensions install their own structural objects (types,\n * functions, helper tables) before the app's structural ops reference\n * them. Putting app-space last lets app-space ops freely depend on any\n * extension-space declaration in the same transaction.\n *\n * Determinism (NFR6): the output order is independent of the input\n * order, so two callers with the same set of `extensionPacks` produce\n * identical apply sequences.\n *\n * Atomicity: rejects duplicate `spaceId`s with\n * `MIGRATION.DUPLICATE_SPACE_ID` before producing any output. This\n * mirrors {@link import('./plan-all-spaces').planAllSpaces} so the\n * planner-side and runner-side helpers reject malformed inputs the same\n * way (callers don't need a separate dedup pass).\n *\n * Synchronous, pure, no I/O: callers resolve marker rows and `path`\n * before invoking this helper. The actual DB application — driving the\n * transaction, committing marker writes, recording the per-space marker\n * rows — happens at the SQL-family consumption site (per the\n * helper-location convention from R3).\n */\nexport function concatenateSpaceApplyInputs<TOp>(\n inputs: readonly SpaceApplyInput<TOp>[],\n): readonly SpaceApplyInput<TOp>[] {\n const seen = new Set<string>();\n for (const input of inputs) {\n if (seen.has(input.spaceId)) {\n throw errorDuplicateSpaceId(input.spaceId);\n }\n seen.add(input.spaceId);\n }\n\n const extensions: SpaceApplyInput<TOp>[] = [];\n let appSpace: SpaceApplyInput<TOp> | undefined;\n for (const input of inputs) {\n if (input.spaceId === APP_SPACE_ID) {\n appSpace = input;\n } else {\n extensions.push(input);\n }\n }\n\n extensions.sort((a, b) => {\n if (a.spaceId < b.spaceId) return -1;\n if (a.spaceId > b.spaceId) return 1;\n return 0;\n });\n\n return appSpace ? [...extensions, appSpace] : extensions;\n}\n","/**\n * Inputs for {@link detectSpaceContractDrift}.\n *\n * Both hashes are produced by the caller (the SQL-family wiring at the\n * consumption site) using the canonical contract hashing pipeline.\n * Keeping the helper pure lets `migration-tools` stay framework-neutral\n * — the SQL family already speaks `Contract<SqlStorage>`, the Mongo\n * family speaks its own contract type, and both reduce to a hash string\n * before drift detection runs.\n *\n * `pinnedHash` is `null` when no pinned `contract.json` exists yet for\n * the space (the descriptor declares an extension that has never been\n * emitted into the user's repo). That's the \"first emit\" case — no\n * drift to surface; the migrate emit will create the pinned files.\n *\n * @see specs/framework-mechanism.spec.md § 3 — Drift detection (T1.9).\n */\nexport interface DetectSpaceContractDriftInputs {\n readonly descriptorHash: string;\n readonly pinnedHash: string | null;\n}\n\n/**\n * Result discriminant for {@link detectSpaceContractDrift}.\n *\n * - `noDrift`: descriptor hash and pinned hash agree byte-for-byte.\n * The migrate emit can proceed with no warning.\n * - `firstEmit`: no pinned `contract.json` on disk yet. The extension\n * was just added to `extensionPacks`; this run will create the\n * pinned files. No warning either — the user's intent is to install\n * the extension, not to \"drift\" from a state they haven't pinned.\n * - `drift`: descriptor hash differs from pinned hash. The caller\n * surfaces a non-fatal warning naming the extension and the\n * diff direction (descriptor → pinned). The migrate emit proceeds\n * normally so the bump is materialised this run; the warning just\n * confirms the bump is being captured.\n *\n * `spaceId`, `descriptorHash`, and `pinnedHash` are threaded through\n * verbatim so the caller (logger / TerminalUI / strict-mode envelope)\n * has everything it needs to format the warning message without\n * re-reading the descriptor or the pinned file.\n */\nexport type SpaceContractDriftResult = {\n readonly kind: 'noDrift' | 'firstEmit' | 'drift';\n readonly spaceId: string;\n readonly descriptorHash: string;\n readonly pinnedHash: string | null;\n};\n\n/**\n * Pure drift-detection primitive for a single contract space.\n *\n * Runs once per loaded extension space, just before computing the\n * `priorContract` that feeds {@link import('./plan-all-spaces').planAllSpaces}.\n * Hash equality is byte-for-byte (no normalisation) — both sides are\n * already canonical hashes produced by the same pipeline, so any\n * difference is meaningful drift.\n *\n * Synchronous, pure, no I/O. The caller (SQL family in M2 R1) reads\n * the pinned `contract.json` and computes its hash, then invokes this\n * helper alongside the descriptor's `headRef.hash`. Composes naturally\n * with {@link import('./read-pinned-contract-hash').readPinnedContractHash}\n * which provides the read-side primitive.\n *\n * @see specs/framework-mechanism.spec.md § 3 — Drift detection (T1.9).\n * @see specs/framework-mechanism.spec.md AM7 — drift warning surfaces\n * the extension name and the diff direction.\n */\nexport function detectSpaceContractDrift(\n spaceId: string,\n inputs: DetectSpaceContractDriftInputs,\n): SpaceContractDriftResult {\n if (inputs.pinnedHash === null) {\n return {\n kind: 'firstEmit',\n spaceId,\n descriptorHash: inputs.descriptorHash,\n pinnedHash: null,\n };\n }\n if (inputs.descriptorHash === inputs.pinnedHash) {\n return {\n kind: 'noDrift',\n spaceId,\n descriptorHash: inputs.descriptorHash,\n pinnedHash: inputs.pinnedHash,\n };\n }\n return {\n kind: 'drift',\n spaceId,\n descriptorHash: inputs.descriptorHash,\n pinnedHash: inputs.pinnedHash,\n };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { canonicalizeJson } from './canonicalize-json';\nimport { errorPinnedArtefactsAppSpace } from './errors';\nimport { APP_SPACE_ID, assertValidSpaceId } from './space-layout';\n\n/**\n * Pinned head reference for a contract space — `(hash, invariants)`.\n * Mirrors {@link import('./refs').RefEntry} but is redeclared locally so\n * callers can construct the input without depending on the refs module.\n */\nexport interface PinnedSpaceHeadRef {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\n/**\n * Inputs for {@link emitPinnedSpaceArtefacts}.\n *\n * - `contract` is the canonical contract value the framework just emitted\n * for the space; it is serialised through {@link canonicalizeJson}, so\n * it must be a JSON-compatible value (objects / arrays / primitives).\n * Typed as `unknown` rather than the SQL-family `Contract<SqlStorage>`\n * to keep `migration-tools` framework-neutral; SQL-family callers pass\n * their typed value through unchanged.\n *\n * - `contractDts` is the pre-rendered `.d.ts` text. Rendering happens in\n * the SQL family (which owns the codec / typemap input the renderer\n * needs), so this helper accepts the text verbatim and writes it out\n * without further transformation.\n *\n * - `headRef` is the pinned head reference for the space.\n * `invariants` are sorted alphabetically before serialisation so two\n * callers passing the same set in different orders produce\n * byte-identical `refs/head.json`.\n */\nexport interface PinnedSpaceArtefactInputs {\n readonly contract: unknown;\n readonly contractDts: string;\n readonly headRef: PinnedSpaceHeadRef;\n}\n\n/**\n * Emit the pinned per-space artefacts (`contract.json`, `contract.d.ts`,\n * `refs/head.json`) under `<projectMigrationsDir>/<spaceId>/`.\n *\n * Always-overwrite: the framework owns these files; running `migrate`\n * twice with the same inputs is a no-op observably (idempotent), but the\n * helper does not check pre-existing contents — re-emit always wins.\n *\n * Path layout matches the convention in\n * [`spaceMigrationDirectory`](./space-layout.ts), with two restrictions\n * specific to pinned artefacts:\n *\n * - Rejects the app space (`spaceId === APP_SPACE_ID`): the app space's\n * canonical `contract.json` lives at the project root, not under\n * `migrations/`. Callers that want to emit it use the app-space\n * contract emit pipeline.\n * - Validates `spaceId` against `[a-z][a-z0-9_-]{0,63}` via\n * {@link assertValidSpaceId} for the same filesystem-safety reasons.\n *\n * The migrations directory and space subdirectory are created if they\n * do not yet exist (`mkdir { recursive: true }`).\n *\n * @see specs/framework-mechanism.spec.md § 3 — Pinned artefact emission (T1.8).\n */\nexport async function emitPinnedSpaceArtefacts(\n projectMigrationsDir: string,\n spaceId: string,\n inputs: PinnedSpaceArtefactInputs,\n): Promise<void> {\n if (spaceId === APP_SPACE_ID) {\n throw errorPinnedArtefactsAppSpace();\n }\n assertValidSpaceId(spaceId);\n\n const dir = join(projectMigrationsDir, spaceId);\n await mkdir(join(dir, 'refs'), { recursive: true });\n\n await writeFile(join(dir, 'contract.json'), `${canonicalizeJson(inputs.contract)}\\n`);\n await writeFile(join(dir, 'contract.d.ts'), inputs.contractDts);\n\n const sortedInvariants = [...inputs.headRef.invariants].sort();\n const headJson = canonicalizeJson({\n hash: inputs.headRef.hash,\n invariants: sortedInvariants,\n });\n await writeFile(join(dir, 'refs', 'head.json'), `${headJson}\\n`);\n}\n","import { errorDuplicateSpaceId } from './errors';\n\n/**\n * Per-space input for {@link planAllSpaces}. One entry per loaded\n * contract space (the application's `'app'` plus each extension that\n * exposes a `contractSpace`).\n *\n * - `priorContract` is `null` for a space that has never been emitted\n * (no `migrations/<space-id>/contract.json` on disk yet); otherwise it\n * is the canonical contract value pinned for that space.\n * - `newContract` is the canonical contract value the planner is about\n * to emit for that space — for app-space, the just-emitted root\n * `contract.json`; for an extension space, the descriptor's\n * `contractSpace.contractJson`.\n *\n * @see specs/framework-mechanism.spec.md § 3.\n */\nexport interface SpacePlanInput<TContract> {\n readonly spaceId: string;\n readonly priorContract: TContract | null;\n readonly newContract: TContract;\n}\n\nexport interface SpacePlanOutput<TPackage> {\n readonly spaceId: string;\n readonly migrationPackages: readonly TPackage[];\n}\n\n/**\n * Iterate the per-space planner across a set of loaded contract spaces\n * and return a deterministic shape regardless of declaration order.\n *\n * Behaviour:\n *\n * - The output is sorted alphabetically by `spaceId` (AM3). Two callers\n * passing the same set of inputs in different orders observe\n * byte-identical outputs.\n * - The per-space planner (`planSpace`) is called exactly once per\n * input, in alphabetical-by-spaceId order. Its return value is\n * attached to the corresponding output entry verbatim.\n * - Duplicate `spaceId`s in the input array throw\n * `MIGRATION.DUPLICATE_SPACE_ID` before any `planSpace` call runs,\n * keeping the planner pure when the input is malformed.\n *\n * The signature is generic over `TContract` and `TPackage` because the\n * shape is framework-neutral (SQL family today, Mongo family\n * eventually). Callers wire in whatever contract value and migration\n * package shape their family already speaks.\n *\n * Synchronous: the underlying per-space planner (target's\n * `MigrationPlanner.plan(...)`) is synchronous; callers that need to\n * resolve async I/O (e.g. reading pinned `contract.json` from disk)\n * resolve it before calling `planAllSpaces` and pass the materialised\n * inputs through.\n *\n * @see specs/framework-mechanism.spec.md § 3 — Per-space planner (T1.3).\n */\nexport function planAllSpaces<TContract, TPackage>(\n inputs: readonly SpacePlanInput<TContract>[],\n planSpace: (input: SpacePlanInput<TContract>) => readonly TPackage[],\n): readonly SpacePlanOutput<TPackage>[] {\n const seen = new Set<string>();\n for (const input of inputs) {\n if (seen.has(input.spaceId)) {\n throw errorDuplicateSpaceId(input.spaceId);\n }\n seen.add(input.spaceId);\n }\n\n const sorted = [...inputs].sort((a, b) => {\n if (a.spaceId < b.spaceId) return -1;\n if (a.spaceId > b.spaceId) return 1;\n return 0;\n });\n\n return sorted.map((input) => ({\n spaceId: input.spaceId,\n migrationPackages: planSpace(input),\n }));\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { errorInvalidJson, errorInvalidRefFile, errorPinnedArtefactsAppSpace } from './errors';\nimport { APP_SPACE_ID, assertValidSpaceId } from './space-layout';\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\n/**\n * Read the pinned head hash for an extension space.\n *\n * Returns the `hash` field of `<projectMigrationsDir>/<spaceId>/refs/head.json`\n * — i.e. the canonical contract hash the framework wrote on the last\n * `migrate` for this space. Returns `null` when the file does not exist\n * (or the migrations directory is missing entirely), which is the\n * \"first emit\" signal {@link import('./detect-space-contract-drift').detectSpaceContractDrift}\n * uses to distinguish a brand-new extension from drift.\n *\n * Pure I/O (read + parse). The \"comparison hash\" is stored on disk by\n * {@link import('./emit-pinned-space-artefacts').emitPinnedSpaceArtefacts}\n * via the descriptor's `headRef.hash`, so reading it back here matches\n * the descriptor's hashing pipeline by construction — neither side\n * recomputes anything.\n *\n * Validation:\n *\n * - Rejects the app space — pinned head refs are an extension-space\n * concept; the app space's contract-of-record lives at the project\n * root, not under `migrations/`.\n * - Validates the space id against the same `[a-z][a-z0-9_-]{0,63}`\n * pattern as the rest of the per-space helpers.\n * - Surfaces `MIGRATION.INVALID_JSON` / `MIGRATION.INVALID_REF_FILE`\n * on a corrupt `refs/head.json` so callers can distinguish \"no\n * pinned file\" (returns `null`) from \"pinned file but unreadable\"\n * (throws).\n *\n * @see specs/framework-mechanism.spec.md § 3 — Drift detection (T1.9).\n */\nexport async function readPinnedContractHash(\n projectMigrationsDir: string,\n spaceId: string,\n): Promise<string | null> {\n if (spaceId === APP_SPACE_ID) {\n throw errorPinnedArtefactsAppSpace();\n }\n assertValidSpaceId(spaceId);\n\n const filePath = join(projectMigrationsDir, spaceId, 'refs', 'head.json');\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return null;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));\n }\n\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n typeof (parsed as { hash?: unknown }).hash !== 'string'\n ) {\n throw errorInvalidRefFile(filePath, 'expected an object with a string `hash` field');\n }\n\n return (parsed as { hash: string }).hash;\n}\n","import { readdir, stat } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { MANIFEST_FILE } from './io';\nimport { APP_SPACE_ID } from './space-layout';\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\n/**\n * List the per-space pinned subdirectories under\n * `<projectRoot>/migrations/`. Returns space-id directory names (sorted\n * alphabetically) — i.e. any non-dot-prefixed subdirectory whose root\n * does **not** contain a `migration.json` manifest. The manifest is the\n * structural marker of a user-authored migration directory (see\n * `readMigrationsDir` in `./io`); directory names themselves belong to\n * the user and are not part of the contract.\n *\n * Returns `[]` if the migrations directory does not exist (greenfield\n * project).\n *\n * Reads only the user's repo. **No descriptor import.** The caller\n * (verifier) feeds the result into {@link verifyContractSpaces} alongside\n * the loaded-space set and the marker rows.\n *\n * @see specs/framework-mechanism.spec.md § 4 — Verifier (steps 5–6).\n */\nexport async function listPinnedSpaceDirectories(\n projectMigrationsDir: string,\n): Promise<readonly string[]> {\n let entries: { readonly name: string; readonly isDirectory: boolean }[];\n try {\n const dirents = await readdir(projectMigrationsDir, { withFileTypes: true });\n entries = dirents.map((d) => ({ name: d.name, isDirectory: d.isDirectory() }));\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return [];\n }\n throw error;\n }\n\n const namedCandidates = entries\n .filter((e) => e.isDirectory)\n .map((e) => e.name)\n .filter((name) => !name.startsWith('.'))\n .sort();\n\n const manifestChecks = await Promise.all(\n namedCandidates.map(async (name) => {\n try {\n await stat(join(projectMigrationsDir, name, MANIFEST_FILE));\n return { name, isMigrationDir: true };\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return { name, isMigrationDir: false };\n }\n throw error;\n }\n }),\n );\n\n return manifestChecks.filter((c) => !c.isMigrationDir).map((c) => c.name);\n}\n\n/**\n * Pinned head value (`(hash, invariants)`) for one contract space.\n * The verifier compares this against the marker row for the same space\n * to detect drift between the user-emitted artefacts and the live DB\n * marker.\n */\nexport interface SpacePinnedHashRecord {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\n/**\n * Marker row read from `prisma_contract.marker` (one per `space`).\n * Caller resolves these via the family runtime's marker reader (T1.1)\n * before invoking {@link verifyContractSpaces}.\n */\nexport interface SpaceMarkerRecord {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\nexport interface VerifyContractSpacesInputs {\n /**\n * Set of contract spaces the project declares: `'app'` plus each\n * extension space in `extensionPacks`. The caller's discovery path\n * never reads the extension descriptor module — it walks the\n * `extensionPacks` configuration in `prisma-next.config.ts` for the\n * space ids.\n */\n readonly loadedSpaces: ReadonlySet<string>;\n\n /**\n * Pinned per-space subdirectories observed under\n * `<projectRoot>/migrations/`. Resolved via\n * {@link listPinnedSpaceDirectories}.\n */\n readonly pinnedDirsOnDisk: readonly string[];\n\n /**\n * Pinned head ref per space, keyed by space id. Caller reads\n * `<projectRoot>/migrations/<space-id>/contract.json` and\n * `refs/head.json` (or, for app-space if its pinned shape ever moves\n * under `migrations/`, the equivalent files) to construct this map.\n * Spaces with no pinned dir on disk simply omit a map entry.\n */\n readonly pinnedHashesBySpace: ReadonlyMap<string, SpacePinnedHashRecord>;\n\n /**\n * Marker rows keyed by `space`. Caller reads them from the\n * `prisma_contract.marker` table.\n */\n readonly markerRowsBySpace: ReadonlyMap<string, SpaceMarkerRecord>;\n}\n\nexport type SpaceVerifierViolation =\n | {\n readonly kind: 'declaredButUnmigrated';\n readonly spaceId: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'orphanMarker';\n readonly spaceId: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'orphanPinnedDir';\n readonly spaceId: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'hashMismatch';\n readonly spaceId: string;\n readonly pinnedHash: string;\n readonly markerHash: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'invariantsMismatch';\n readonly spaceId: string;\n readonly pinnedInvariants: readonly string[];\n readonly markerInvariants: readonly string[];\n readonly remediation: string;\n };\n\nexport type VerifyContractSpacesResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly violations: readonly SpaceVerifierViolation[] };\n\n/**\n * Pure structural verifier for the per-space mechanism. Aggregates the\n * three orphan / missing checks (FR6 cases a–c) plus per-space hash and\n * invariant comparison.\n *\n * Algorithm (sub-spec § 4):\n *\n * - For every extension space declared in `loadedSpaces` (`'app'`\n * excluded — its pinned `contract.json` lives at the project root):\n * - If no pinned dir on disk → `declaredButUnmigrated`.\n * - Else if `markerRowsBySpace` lacks an entry → no violation here;\n * the live-DB compare in step 8 (out of scope of this helper) is\n * where the absence shows up.\n * - Else compare marker hash / invariants vs. pinned hash /\n * invariants → `hashMismatch` / `invariantsMismatch` on drift.\n * - For every pinned dir on disk that is not in `loadedSpaces` →\n * `orphanPinnedDir`.\n * - For every marker row whose `space` is not in `loadedSpaces` →\n * `orphanMarker`. The app-space marker is always loaded (`'app'` is\n * in `loadedSpaces` by definition).\n *\n * Output is deterministic (NFR6): violations are sorted first by `kind`\n * (`declaredButUnmigrated` → `orphanMarker` → `orphanPinnedDir` →\n * `hashMismatch` → `invariantsMismatch`) then by `spaceId`. Two callers\n * passing equivalent inputs see byte-identical violation lists.\n *\n * Synchronous, pure, no I/O. **Does not import the extension descriptor**\n * (the inputs are pre-resolved by the caller). This is the property\n * AC-15 / AC-26 (\"verifier reads only the user repo, not\n * `node_modules`\") locks in.\n *\n * @see specs/framework-mechanism.spec.md § 4 — Verifier (T1.5).\n */\nexport function verifyContractSpaces(\n inputs: VerifyContractSpacesInputs,\n): VerifyContractSpacesResult {\n const violations: SpaceVerifierViolation[] = [];\n\n for (const spaceId of [...inputs.loadedSpaces].sort()) {\n if (spaceId === APP_SPACE_ID) continue;\n\n if (!inputs.pinnedDirsOnDisk.includes(spaceId)) {\n violations.push({\n kind: 'declaredButUnmigrated',\n spaceId,\n remediation: `Extension '${spaceId}' is declared in extensionPacks but has not been emitted; run \\`prisma-next migrate\\`.`,\n });\n continue;\n }\n\n const pinned = inputs.pinnedHashesBySpace.get(spaceId);\n const marker = inputs.markerRowsBySpace.get(spaceId);\n if (!pinned || !marker) {\n continue;\n }\n\n if (pinned.hash !== marker.hash) {\n violations.push({\n kind: 'hashMismatch',\n spaceId,\n pinnedHash: pinned.hash,\n markerHash: marker.hash,\n remediation: `Marker row for space '${spaceId}' is keyed at ${marker.hash}, but the pinned ${join('migrations', spaceId, 'contract.json')} resolves to ${pinned.hash}. Run \\`prisma-next db update\\` to advance the database, or \\`prisma-next migrate\\` if the descriptor was bumped without re-emitting.`,\n });\n continue;\n }\n\n const pinnedInvariants = [...pinned.invariants].sort();\n const markerInvariants = new Set(marker.invariants);\n const missing = pinnedInvariants.filter((id) => !markerInvariants.has(id));\n if (missing.length > 0) {\n violations.push({\n kind: 'invariantsMismatch',\n spaceId,\n pinnedInvariants,\n markerInvariants: [...marker.invariants].sort(),\n remediation: `Marker row for space '${spaceId}' is missing invariants [${missing.map((s) => JSON.stringify(s)).join(', ')}]. Run \\`prisma-next db update\\` to apply the corresponding data-transform migrations.`,\n });\n }\n }\n\n for (const dir of [...inputs.pinnedDirsOnDisk].sort()) {\n if (!inputs.loadedSpaces.has(dir)) {\n violations.push({\n kind: 'orphanPinnedDir',\n spaceId: dir,\n remediation: `Orphan pinned directory \\`${join('migrations', dir)}/\\` for an extension not in extensionPacks; remove the directory or re-add the extension.`,\n });\n }\n }\n\n for (const space of [...inputs.markerRowsBySpace.keys()].sort()) {\n if (!inputs.loadedSpaces.has(space)) {\n violations.push({\n kind: 'orphanMarker',\n spaceId: space,\n remediation: `Orphan marker row for space '${space}' (no longer in extensionPacks); remediation: manually delete the row from \\`prisma_contract.marker\\`.`,\n });\n }\n }\n\n if (violations.length === 0) {\n return { ok: true };\n }\n\n const kindOrder: Record<SpaceVerifierViolation['kind'], number> = {\n declaredButUnmigrated: 0,\n orphanMarker: 1,\n orphanPinnedDir: 2,\n hashMismatch: 3,\n invariantsMismatch: 4,\n };\n\n violations.sort((a, b) => {\n const k = kindOrder[a.kind] - kindOrder[b.kind];\n if (k !== 0) return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AAC;;AAIN,MAAK,MAAM,OAAO,CAAC,GAAG,OAAO,iBAAiB,CAAC,MAAM,CACnD,KAAI,CAAC,OAAO,aAAa,IAAI,IAAI,CAC/B,YAAW,KAAK;EACd,MAAM;EACN,SAAS;EACT,aAAa,6BAA6B,KAAK,cAAc,IAAI,CAAC;EACnE,CAAC;AAIN,MAAK,MAAM,SAAS,CAAC,GAAG,OAAO,kBAAkB,MAAM,CAAC,CAAC,MAAM,CAC7D,KAAI,CAAC,OAAO,aAAa,IAAI,MAAM,CACjC,YAAW,KAAK;EACd,MAAM;EACN,SAAS;EACT,aAAa,gCAAgC,MAAM;EACpD,CAAC;AAIN,KAAI,WAAW,WAAW,EACxB,QAAO,EAAE,IAAI,MAAM;CAGrB,MAAMC,YAA4D;EAChE,uBAAuB;EACvB,cAAc;EACd,iBAAiB;EACjB,cAAc;EACd,oBAAoB;EACrB;AAED,YAAW,MAAM,GAAG,MAAM;EACxB,MAAM,IAAI,UAAU,EAAE,QAAQ,UAAU,EAAE;AAC1C,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,EAAE,UAAU,EAAE,QAAS,QAAO;AAClC,MAAI,EAAE,UAAU,EAAE,QAAS,QAAO;AAClC,SAAO;GACP;AAEF,QAAO;EAAE,IAAI;EAAO;EAAY"}
1
+ {"version":3,"file":"spaces.mjs","names":[],"sources":["../../src/assert-descriptor-self-consistency.ts","../../src/compute-extension-space-apply-path.ts","../../src/emit-contract-space-artefacts.ts","../../src/gather-disk-contract-space-state.ts","../../src/plan-all-spaces.ts"],"sourcesContent":["import { computeStorageHash } from '@prisma-next/contract/hashing';\nimport { errorDescriptorHeadHashMismatch } from './errors';\n\n/**\n * Inputs the helper needs to recompute the descriptor's storage hash and\n * compare it to the published `headRef.hash`. Kept structural so the SQL\n * family (and any future target family) can compose the check without\n * coupling to its own descriptor types.\n */\nexport interface DescriptorSelfConsistencyInputs {\n readonly extensionId: string;\n readonly target: string;\n readonly targetFamily: string;\n /**\n * Family-specific storage object. Typed as `unknown` so callers can\n * pass their own narrow storage shape (e.g. `SqlStorage`) without an\n * inline cast — the helper canonicalises through `JSON.stringify`\n * inside {@link computeStorageHash} and only requires a plain\n * record-shaped value at runtime.\n */\n readonly storage: unknown;\n readonly headRefHash: string;\n}\n\n/**\n * Assert that an extension descriptor is self-consistent: the\n * `headRef.hash` it publishes must match the canonical hash recomputed\n * from its `contractSpace.contractJson`.\n *\n * Recomputes via {@link computeStorageHash} — the same canonical-JSON\n * pipeline the descriptor's own emit pipeline produced the hash with —\n * over `(target, targetFamily, storage)`. Mismatch indicates the\n * extension author bumped `contractJson` without rerunning emit, leaving\n * the descriptor's `headRef.hash` stale; the consumer-side helpers\n * (drift detection, on-disk artefact emission, runner marker writes) all\n * trust `headRef.hash` as the canonical identity, so a stale value would\n * silently corrupt every downstream boundary.\n *\n * Synchronous, pure, no I/O. Throws\n * `MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH` on failure with both the\n * recomputed and published hashes in `details` so callers can surface a\n * clear remediation hint without re-deriving them.\n */\nexport function assertDescriptorSelfConsistency(inputs: DescriptorSelfConsistencyInputs): void {\n // The published `storage.storageHash` is the *output* of the production\n // emit pipeline's `computeStorageHash` call, computed over a storage\n // object that did not yet carry `storageHash`. Recomputing against the\n // published storage as-is would feed the result back into its own input\n // and produce a different digest. Strip `storageHash` before\n // recomputing so the helper sees the same canonical shape the\n // descriptor's authoring pipeline saw.\n // The helper requires only a plain record-shaped storage value at\n // runtime; a single cast here keeps the public input type\n // family-agnostic (`unknown`) while still letting us strip the\n // descriptor-published `storageHash` before re-canonicalising.\n const storageRecord = inputs.storage as Record<string, unknown>;\n const { storageHash: _stripped, ...storageWithoutHash } = storageRecord;\n const recomputed = computeStorageHash({\n target: inputs.target,\n targetFamily: inputs.targetFamily,\n storage: storageWithoutHash,\n });\n if (recomputed !== inputs.headRefHash) {\n throw errorDescriptorHeadHashMismatch({\n extensionId: inputs.extensionId,\n recomputedHash: recomputed,\n headRefHash: inputs.headRefHash,\n });\n }\n}\n","import { EMPTY_CONTRACT_HASH } from './constants';\nimport { readMigrationsDir } from './io';\nimport { findPathWithDecision, reconstructGraph } from './migration-graph';\nimport type { MigrationOps } from './package';\nimport {\n type ContractSpaceHeadRef,\n readContractSpaceHeadRef,\n} from './read-contract-space-head-ref';\nimport { spaceMigrationDirectory } from './space-layout';\n\n/**\n * Outcome of {@link computeExtensionSpaceApplyPath} — a discriminated union\n * mirroring {@link import('./migration-graph').FindPathOutcome} so callers\n * can map structural / invariant failures to their preferred CLI envelope\n * without re-running pathfinding.\n */\nexport type ExtensionSpaceApplyPathOutcome =\n | {\n readonly kind: 'ok';\n readonly contractSpaceHeadRef: ContractSpaceHeadRef;\n /**\n * Sorted, deduplicated invariant ids covered by the walked path.\n * Mirrors the on-disk `providedInvariants` summed across edges and\n * canonicalised — what the runner stamps on the marker after apply.\n */\n readonly providedInvariants: readonly string[];\n /**\n * Path operations in apply order. Empty when the marker is already\n * at the recorded head (no-op).\n */\n readonly pathOps: MigrationOps;\n /**\n * Migration directory names walked, in order. Mirrors `pathOps`'s\n * structure but at the package granularity — useful for surfacing\n * \"applied N migration(s)\" messages.\n */\n readonly walkedMigrationDirs: readonly string[];\n }\n | { readonly kind: 'unreachable'; readonly contractSpaceHeadRef: ContractSpaceHeadRef }\n | {\n readonly kind: 'unsatisfiable';\n readonly contractSpaceHeadRef: ContractSpaceHeadRef;\n readonly missing: readonly string[];\n readonly structuralPath: readonly { readonly dirName: string; readonly to: string }[];\n }\n | { readonly kind: 'contractSpaceHeadRefMissing' };\n\n/**\n * Inputs to {@link computeExtensionSpaceApplyPath}. The helper is\n * deliberately framework-neutral and consumes only on-disk state:\n *\n * - `projectMigrationsDir` is the project's top-level `migrations/` dir.\n * - `spaceId` selects the per-space subdirectory under it.\n * - `currentMarkerHash` / `currentMarkerInvariants` come from the live\n * marker row keyed by `space = <spaceId>`. `null` hash = no marker yet\n * (the pathfinder treats this as the empty-contract sentinel per ADR\n * 208).\n */\nexport interface ComputeExtensionSpaceApplyPathInputs {\n readonly projectMigrationsDir: string;\n readonly spaceId: string;\n readonly currentMarkerHash: string | null;\n readonly currentMarkerInvariants: readonly string[];\n}\n\n/**\n * Compute the apply path for an extension contract space — the shortest\n * sequence of on-disk migration packages that walks the live marker\n * forward to the on-disk head ref hash, covering every required\n * invariant.\n *\n * Reads only on-disk artefacts (`migrations/<spaceId>/refs/head.json`\n * and the per-space migration packages). **Does not import any\n * extension descriptor module** — `db init` / `db update` must remain\n * runnable without the descriptor source on disk.\n *\n * Behaviour:\n * - Returns `{ kind: 'ok', pathOps: [], … }` when the marker is already\n * at the recorded head and no required invariants are missing.\n * - Returns `{ kind: 'unreachable' }` when the marker hash is not\n * structurally connected to the recorded head in the graph.\n * - Returns `{ kind: 'unsatisfiable', missing, … }` when the marker is\n * reachable but no path covers the required invariants.\n * - Returns `{ kind: 'contractSpaceHeadRefMissing' }` when the per-space\n * `refs/head.json` is absent — the precheck verifier should already\n * have rejected this case, but the helper is defensive so callers can\n * surface a coherent error rather than throw.\n */\nexport async function computeExtensionSpaceApplyPath(\n inputs: ComputeExtensionSpaceApplyPathInputs,\n): Promise<ExtensionSpaceApplyPathOutcome> {\n const { projectMigrationsDir, spaceId, currentMarkerHash, currentMarkerInvariants } = inputs;\n\n const contractSpaceHeadRef = await readContractSpaceHeadRef(projectMigrationsDir, spaceId);\n if (contractSpaceHeadRef === null) {\n return { kind: 'contractSpaceHeadRefMissing' };\n }\n\n const spaceDir = spaceMigrationDirectory(projectMigrationsDir, spaceId);\n const packages = await readMigrationsDir(spaceDir);\n const graph = reconstructGraph(packages);\n\n // Live-marker layer encodes \"no prior state\" as EMPTY_CONTRACT_HASH;\n // mirror the `migration apply` flow so a fresh-marker initial walk\n // hits the baseline migration whose `from` is EMPTY_CONTRACT_HASH.\n const fromHash = currentMarkerHash ?? EMPTY_CONTRACT_HASH;\n const required = new Set(\n contractSpaceHeadRef.invariants.filter((id) => !currentMarkerInvariants.includes(id)),\n );\n\n const outcome = findPathWithDecision(graph, fromHash, contractSpaceHeadRef.hash, { required });\n\n if (outcome.kind === 'unreachable') {\n return { kind: 'unreachable', contractSpaceHeadRef };\n }\n if (outcome.kind === 'unsatisfiable') {\n return {\n kind: 'unsatisfiable',\n contractSpaceHeadRef,\n missing: outcome.missing,\n structuralPath: outcome.structuralPath.map(({ dirName, to }) => ({ dirName, to })),\n };\n }\n\n const packagesByHash = new Map(packages.map((pkg) => [pkg.metadata.migrationHash, pkg]));\n\n const pathOps: MigrationOps[number][] = [];\n const walkedMigrationDirs: string[] = [];\n const providedInvariantsSet = new Set<string>();\n for (const edge of outcome.decision.selectedPath) {\n const pkg = packagesByHash.get(edge.migrationHash);\n if (!pkg) {\n // Path edges always come from the same `packages` array, so this\n // is only reachable when the graph is internally inconsistent —\n // surface it loudly rather than silently truncating the path.\n throw new Error(\n `Migration package missing for edge ${edge.migrationHash} in space \"${spaceId}\"`,\n );\n }\n walkedMigrationDirs.push(pkg.dirName);\n for (const op of pkg.ops) pathOps.push(op);\n for (const invariant of pkg.metadata.providedInvariants) providedInvariantsSet.add(invariant);\n }\n\n return {\n kind: 'ok',\n contractSpaceHeadRef,\n providedInvariants: [...providedInvariantsSet].sort(),\n pathOps,\n walkedMigrationDirs,\n };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { canonicalizeJson } from './canonicalize-json';\nimport type { ContractSpaceHeadRef } from './read-contract-space-head-ref';\nimport { assertValidSpaceId } from './space-layout';\n\n/**\n * Inputs for {@link emitContractSpaceArtefacts}.\n *\n * - `contract` is the canonical contract value the framework just emitted\n * for the space; it is serialised through {@link canonicalizeJson}, so\n * it must be a JSON-compatible value (objects / arrays / primitives).\n * Typed as `unknown` rather than the SQL-family `Contract<SqlStorage>`\n * to keep `migration-tools` framework-neutral; SQL-family callers pass\n * their typed value through unchanged.\n *\n * - `contractDts` is the pre-rendered `.d.ts` text. Rendering happens in\n * the SQL family (which owns the codec / typemap input the renderer\n * needs), so this helper accepts the text verbatim and writes it out\n * without further transformation.\n *\n * - `headRef` is the head reference for the space.\n * `invariants` are sorted alphabetically before serialisation so two\n * callers passing the same set in different orders produce\n * byte-identical `refs/head.json`.\n */\nexport interface ContractSpaceArtefactInputs {\n readonly contract: unknown;\n readonly contractDts: string;\n readonly headRef: ContractSpaceHeadRef;\n}\n\n/**\n * Emit the per-space artefacts (`contract.json`, `contract.d.ts`,\n * `refs/head.json`) under `<projectMigrationsDir>/<spaceId>/`.\n *\n * Always-overwrite: the framework owns these files; running `migrate`\n * twice with the same inputs is a no-op observably (idempotent), but the\n * helper does not check pre-existing contents — re-emit always wins.\n *\n * Path layout matches the convention in\n * [`spaceMigrationDirectory`](./space-layout.ts). The space id is\n * validated against `[a-z][a-z0-9_-]{0,63}` via\n * {@link assertValidSpaceId} for filesystem-safety reasons; the helper\n * accepts every space uniformly (including the app space, default\n * `'app'`).\n *\n * The migrations directory and space subdirectory are created if they\n * do not yet exist (`mkdir { recursive: true }`).\n */\nexport async function emitContractSpaceArtefacts(\n projectMigrationsDir: string,\n spaceId: string,\n inputs: ContractSpaceArtefactInputs,\n): Promise<void> {\n assertValidSpaceId(spaceId);\n\n const dir = join(projectMigrationsDir, spaceId);\n await mkdir(join(dir, 'refs'), { recursive: true });\n\n await writeFile(join(dir, 'contract.json'), `${canonicalizeJson(inputs.contract)}\\n`);\n await writeFile(join(dir, 'contract.d.ts'), inputs.contractDts);\n\n const sortedInvariants = [...inputs.headRef.invariants].sort();\n const headJson = canonicalizeJson({\n hash: inputs.headRef.hash,\n invariants: sortedInvariants,\n });\n await writeFile(join(dir, 'refs', 'head.json'), `${headJson}\\n`);\n}\n","import { readContractSpaceHeadRef } from './read-contract-space-head-ref';\nimport { APP_SPACE_ID } from './space-layout';\nimport {\n type ContractSpaceHeadRecord,\n listContractSpaceDirectories,\n} from './verify-contract-spaces';\n\n/**\n * Disk-side inputs to {@link import('./verify-contract-spaces').verifyContractSpaces}\n * — gathered without touching the live database. The caller composes\n * this with the marker rows it reads from the runtime to invoke the\n * verifier.\n */\nexport interface DiskContractSpaceState {\n /** Contract-space directory names observed under `<projectMigrationsDir>/`. */\n readonly spaceDirsOnDisk: readonly string[];\n /** Head-ref `(hash, invariants)` per extension space. */\n readonly headRefsBySpace: ReadonlyMap<string, ContractSpaceHeadRecord>;\n}\n\n/**\n * Read the on-disk state the per-space verifier needs:\n *\n * - The list of contract-space directories under\n * `<projectMigrationsDir>/` (via\n * {@link import('./verify-contract-spaces').listContractSpaceDirectories}).\n * - The on-disk head ref `(hash, invariants)` for each declared extension space\n * (via {@link readContractSpaceHeadRef}; missing on-disk artefacts are simply\n * omitted — the verifier reports them as `declaredButUnmigrated`).\n *\n * Synchronous in spirit but async due to filesystem reads. Reads only\n * the user's repo. **Does not import any extension descriptor module.**\n *\n * Composition convention: pure target-agnostic primitive in\n * `1-framework`; the SQL family (and any future target family) wires\n * it into its `dbInit` / `verify` flows alongside its own marker-row\n * read before invoking `verifyContractSpaces`.\n */\nexport async function gatherDiskContractSpaceState(args: {\n readonly projectMigrationsDir: string;\n /**\n * Set of space ids the project declares: `'app'` plus each entry in\n * `extensionPacks` whose descriptor exposes a `contractSpace`. The\n * helper reads on-disk head data only for the extension members.\n */\n readonly loadedSpaceIds: ReadonlySet<string>;\n}): Promise<DiskContractSpaceState> {\n const { projectMigrationsDir, loadedSpaceIds } = args;\n\n const spaceDirsOnDisk = await listContractSpaceDirectories(projectMigrationsDir);\n\n const headRefsBySpace = new Map<string, ContractSpaceHeadRecord>();\n for (const spaceId of loadedSpaceIds) {\n if (spaceId === APP_SPACE_ID) continue;\n const head = await readContractSpaceHeadRef(projectMigrationsDir, spaceId);\n if (head !== null) {\n headRefsBySpace.set(spaceId, head);\n }\n }\n\n return { spaceDirsOnDisk, headRefsBySpace };\n}\n","import { errorDuplicateSpaceId } from './errors';\n\n/**\n * Per-space input for {@link planAllSpaces}. One entry per loaded\n * contract space (the application's `'app'` plus each extension that\n * exposes a `contractSpace`).\n *\n * - `priorContract` is `null` for a space that has never been emitted\n * (no `migrations/<space-id>/contract.json` on disk yet); otherwise it\n * is the canonical contract value emitted for that space.\n * - `newContract` is the canonical contract value the planner is about\n * to emit for that space — for app-space, the just-emitted root\n * `contract.json`; for an extension space, the descriptor's\n * `contractSpace.contractJson`.\n */\nexport interface SpacePlanInput<TContract> {\n readonly spaceId: string;\n readonly priorContract: TContract | null;\n readonly newContract: TContract;\n}\n\nexport interface SpacePlanOutput<TPackage> {\n readonly spaceId: string;\n readonly migrationPackages: readonly TPackage[];\n}\n\n/**\n * Iterate the per-space planner across a set of loaded contract spaces\n * and return a deterministic shape regardless of declaration order.\n *\n * Behaviour:\n *\n * - The output is sorted alphabetically by `spaceId`. Two callers\n * passing the same set of inputs in different orders observe\n * byte-identical outputs.\n * - The per-space planner (`planSpace`) is called exactly once per\n * input, in alphabetical-by-spaceId order. Its return value is\n * attached to the corresponding output entry verbatim.\n * - Duplicate `spaceId`s in the input array throw\n * `MIGRATION.DUPLICATE_SPACE_ID` before any `planSpace` call runs,\n * keeping the planner pure when the input is malformed.\n *\n * The signature is generic over `TContract` and `TPackage` because the\n * shape is framework-neutral (SQL family today, Mongo family\n * eventually). Callers wire in whatever contract value and migration\n * package shape their family already speaks.\n *\n * Synchronous: the underlying per-space planner (target's\n * `MigrationPlanner.plan(...)`) is synchronous; callers that need to\n * resolve async I/O (e.g. reading on-disk `contract.json` from disk)\n * resolve it before calling `planAllSpaces` and pass the materialised\n * inputs through.\n */\nexport function planAllSpaces<TContract, TPackage>(\n inputs: readonly SpacePlanInput<TContract>[],\n planSpace: (input: SpacePlanInput<TContract>) => readonly TPackage[],\n): readonly SpacePlanOutput<TPackage>[] {\n const seen = new Set<string>();\n for (const input of inputs) {\n if (seen.has(input.spaceId)) {\n throw errorDuplicateSpaceId(input.spaceId);\n }\n seen.add(input.spaceId);\n }\n\n const sorted = [...inputs].sort((a, b) => {\n if (a.spaceId < b.spaceId) return -1;\n if (a.spaceId > b.spaceId) return 1;\n return 0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c;EAC9B,MAAM,OAAO,MAAM,yBAAyB,sBAAsB,QAAQ;EAC1E,IAAI,SAAS,MACX,gBAAgB,IAAI,SAAS,KAAK;;CAItC,OAAO;EAAE;EAAiB;EAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACP7C,SAAgB,cACd,QACA,WACsC;CACtC,MAAM,uBAAO,IAAI,KAAa;CAC9B,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,KAAK,IAAI,MAAM,QAAQ,EACzB,MAAM,sBAAsB,MAAM,QAAQ;EAE5C,KAAK,IAAI,MAAM,QAAQ;;CASzB,OANe,CAAC,GAAG,OAAO,CAAC,MAAM,GAAG,MAAM;EACxC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,OAAO;GAGI,CAAC,KAAK,WAAW;EAC5B,SAAS,MAAM;EACf,mBAAmB,UAAU,MAAM;EACpC,EAAE"}
@@ -25,4 +25,4 @@ interface MigrationGraph {
25
25
  }
26
26
  //#endregion
27
27
  export { MigrationGraph as n, MigrationEdge as t };
28
- //# sourceMappingURL=graph-Czaj8O2q.d.mts.map
28
+ //# sourceMappingURL=graph-HMWAldoR.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-HMWAldoR.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;EAAA,SACA,MAAA;EAMA;;;AAGX;;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"}
@@ -1,5 +1,4 @@
1
1
  import { createHash } from "node:crypto";
2
-
3
2
  //#region src/canonicalize-json.ts
4
3
  function sortKeys(value) {
5
4
  if (value === null || typeof value !== "object") return value;
@@ -11,7 +10,6 @@ function sortKeys(value) {
11
10
  function canonicalizeJson(value) {
12
11
  return JSON.stringify(sortKeys(value));
13
12
  }
14
-
15
13
  //#endregion
16
14
  //#region src/hash.ts
17
15
  function sha256Hex(input) {
@@ -70,7 +68,7 @@ function verifyMigrationHash(pkg) {
70
68
  computedHash: computed
71
69
  };
72
70
  }
73
-
74
71
  //#endregion
75
72
  export { verifyMigrationHash as n, canonicalizeJson as r, computeMigrationHash as t };
76
- //# sourceMappingURL=hash-G0bAfIGh.mjs.map
73
+
74
+ //# sourceMappingURL=hash-By50zM_E.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash-By50zM_E.mjs","names":[],"sources":["../src/canonicalize-json.ts","../src/hash.ts"],"sourcesContent":["function sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(sortKeys);\n }\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return sorted;\n}\n\nexport function canonicalizeJson(value: unknown): string {\n return JSON.stringify(sortKeys(value));\n}\n","import { createHash } from 'node:crypto';\nimport { canonicalizeJson } from './canonicalize-json';\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 sans\n * contracts/hints/signature, ops). See ADR 199 — Storage-only migration\n * identity for the rationale: contracts are anchored separately by the\n * storage-hash bookends inside the envelope; planner hints are advisory\n * and must not affect identity.\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 {\n migrationHash: _migrationHash,\n signature: _signature,\n fromContract: _fromContract,\n toContract: _toContract,\n hints: _hints,\n ...strippedMeta\n } = 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":";;AAAA,SAAS,SAAS,OAAyB;CACzC,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAET,IAAI,MAAM,QAAQ,MAAM,EACtB,OAAO,MAAM,IAAI,SAAS;CAE5B,MAAM,SAAkC,EAAE;CAC1C,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,MAAM,EACzC,OAAO,OAAO,SAAU,MAAkC,KAAK;CAEjE,OAAO;;AAGT,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,KAAK,UAAU,SAAS,MAAM,CAAC;;;;ACHxC,SAAS,UAAU,OAAuB;CACxC,OAAO,WAAW,SAAS,CAAC,OAAO,MAAM,CAAC,OAAO,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BzD,SAAgB,qBACd,UACA,KACQ;CACR,MAAM,EACJ,eAAe,gBACf,WAAW,YACX,cAAc,eACd,YAAY,aACZ,OAAO,QACP,GAAG,iBACD;CAQJ,OAAO,UAFM,UAAU,iBADJ,CAHO,iBAAiB,aAGN,EAFhB,iBAAiB,IAEa,CAAC,CAAC,IAAI,UACP,CAAC,CAE9B;;;;;;;;;;;AAYvB,SAAgB,oBAAoB,KAA2C;CAC7E,MAAM,WAAW,qBAAqB,IAAI,UAAU,IAAI,IAAI;CAE5D,IAAI,IAAI,SAAS,kBAAkB,UACjC,OAAO;EACL,IAAI;EACJ,YAAY,IAAI,SAAS;EACzB,cAAc;EACf;CAGH,OAAO;EACL,IAAI;EACJ,QAAQ;EACR,YAAY,IAAI,SAAS;EACzB,cAAc;EACf"}
@@ -1,5 +1,4 @@
1
- import { c as errorInvalidInvariantId, i as errorDuplicateInvariantInEdge } from "./errors-DQsXvidG.mjs";
2
-
1
+ import { a as errorDuplicateInvariantInEdge, l as errorInvalidInvariantId } from "./errors-EPL_9p9f.mjs";
3
2
  //#region src/invariants.ts
4
3
  /**
5
4
  * Hygiene check for `invariantId`. Rejects empty values plus any
@@ -14,8 +13,19 @@ function validateInvariantId(invariantId) {
14
13
  /**
15
14
  * Walk a migration's operations and produce its `providedInvariants`
16
15
  * aggregate: the sorted, deduplicated list of `invariantId`s declared
17
- * by data-transform ops. Ops without `operationClass === 'data'` are
18
- * skipped; data ops without an `invariantId` are skipped.
16
+ * by ops in the migration. Ops without an `invariantId` are skipped.
17
+ *
18
+ * Both `data`-class ops (data-transforms, e.g. backfills) and
19
+ * `additive`-class opaque DDL (e.g. cipherstash's vendored EQL bundle
20
+ * via `installEqlBundleOp`) may declare invariantIds: the
21
+ * `operationClass` axis classifies *policy gating* (which kinds of ops
22
+ * a `db init` / `db update` policy permits), while `invariantId`
23
+ * classifies *marker bookkeeping* (which named bundles of work a
24
+ * future regeneration knows to skip). The two concerns are
25
+ * intentionally orthogonal — an extension can ship additive
26
+ * non-IR-derivable DDL (the only way the planner can know the bundle
27
+ * is already applied is via the invariantId on the marker) without
28
+ * needing to mis-classify it as `data`-class.
19
29
  *
20
30
  * Throws `MIGRATION.INVALID_INVARIANT_ID` on a malformed id and
21
31
  * `MIGRATION.DUPLICATE_INVARIANT_IN_EDGE` on duplicates.
@@ -32,11 +42,11 @@ function deriveProvidedInvariants(ops) {
32
42
  return [...seen].sort();
33
43
  }
34
44
  function readInvariantId(op) {
35
- if (op.operationClass !== "data") return void 0;
45
+ if (!Object.hasOwn(op, "invariantId")) return void 0;
36
46
  const candidate = op.invariantId;
37
47
  return typeof candidate === "string" ? candidate : void 0;
38
48
  }
39
-
40
49
  //#endregion
41
50
  export { validateInvariantId as n, deriveProvidedInvariants as t };
42
- //# sourceMappingURL=invariants-4Avb_Yhy.mjs.map
51
+
52
+ //# sourceMappingURL=invariants-Duc8f9NM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariants-Duc8f9NM.mjs","names":[],"sources":["../src/invariants.ts"],"sourcesContent":["import type { MigrationPlanOperation } from '@prisma-next/framework-components/control';\nimport { errorDuplicateInvariantInEdge, errorInvalidInvariantId } from './errors';\nimport type { MigrationOps } from './package';\n\n/**\n * Hygiene check for `invariantId`. Rejects empty values plus any\n * whitespace or control character (including Unicode whitespace like\n * NBSP and em space, which are visually identical to ASCII space and\n * routinely sneak in via paste).\n */\nexport function validateInvariantId(invariantId: string): boolean {\n if (invariantId.length === 0) return false;\n return !/[\\p{Cc}\\p{White_Space}]/u.test(invariantId);\n}\n\n/**\n * Walk a migration's operations and produce its `providedInvariants`\n * aggregate: the sorted, deduplicated list of `invariantId`s declared\n * by ops in the migration. Ops without an `invariantId` are skipped.\n *\n * Both `data`-class ops (data-transforms, e.g. backfills) and\n * `additive`-class opaque DDL (e.g. cipherstash's vendored EQL bundle\n * via `installEqlBundleOp`) may declare invariantIds: the\n * `operationClass` axis classifies *policy gating* (which kinds of ops\n * a `db init` / `db update` policy permits), while `invariantId`\n * classifies *marker bookkeeping* (which named bundles of work a\n * future regeneration knows to skip). The two concerns are\n * intentionally orthogonal — an extension can ship additive\n * non-IR-derivable DDL (the only way the planner can know the bundle\n * is already applied is via the invariantId on the marker) without\n * needing to mis-classify it as `data`-class.\n *\n * Throws `MIGRATION.INVALID_INVARIANT_ID` on a malformed id and\n * `MIGRATION.DUPLICATE_INVARIANT_IN_EDGE` on duplicates.\n */\nexport function deriveProvidedInvariants(ops: MigrationOps): readonly string[] {\n const seen = new Set<string>();\n for (const op of ops) {\n const invariantId = readInvariantId(op);\n if (invariantId === undefined) continue;\n if (!validateInvariantId(invariantId)) {\n throw errorInvalidInvariantId(invariantId);\n }\n if (seen.has(invariantId)) {\n throw errorDuplicateInvariantInEdge(invariantId);\n }\n seen.add(invariantId);\n }\n return [...seen].sort();\n}\n\nfunction readInvariantId(op: MigrationPlanOperation): string | undefined {\n if (!Object.hasOwn(op, 'invariantId')) return undefined;\n const candidate = (op as { invariantId?: unknown }).invariantId;\n return typeof candidate === 'string' ? candidate : undefined;\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,oBAAoB,aAA8B;CAChE,IAAI,YAAY,WAAW,GAAG,OAAO;CACrC,OAAO,CAAC,2BAA2B,KAAK,YAAY;;;;;;;;;;;;;;;;;;;;;;AAuBtD,SAAgB,yBAAyB,KAAsC;CAC7E,MAAM,uBAAO,IAAI,KAAa;CAC9B,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,cAAc,gBAAgB,GAAG;EACvC,IAAI,gBAAgB,KAAA,GAAW;EAC/B,IAAI,CAAC,oBAAoB,YAAY,EACnC,MAAM,wBAAwB,YAAY;EAE5C,IAAI,KAAK,IAAI,YAAY,EACvB,MAAM,8BAA8B,YAAY;EAElD,KAAK,IAAI,YAAY;;CAEvB,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM;;AAGzB,SAAS,gBAAgB,IAAgD;CACvE,IAAI,CAAC,OAAO,OAAO,IAAI,cAAc,EAAE,OAAO,KAAA;CAC9C,MAAM,YAAa,GAAiC;CACpD,OAAO,OAAO,cAAc,WAAW,YAAY,KAAA"}
@@ -1,11 +1,10 @@
1
- import { C as errorProvidedInvariantsMismatch, _ as errorMigrationHashMismatch, h as errorInvalidSlug, l as errorInvalidJson, r as errorDirectoryExists, s as errorInvalidDestName, u as errorInvalidManifest, v as errorMissingFile } from "./errors-DQsXvidG.mjs";
2
- import { n as verifyMigrationHash, r as canonicalizeJson } from "./hash-G0bAfIGh.mjs";
3
- import { t as deriveProvidedInvariants } from "./invariants-4Avb_Yhy.mjs";
4
- import { n as MigrationOpsSchema } from "./op-schema-BiF1ZYqH.mjs";
1
+ import { C as errorProvidedInvariantsMismatch, c as errorInvalidDestName, d as errorInvalidManifest, g as errorInvalidSlug, i as errorDirectoryExists, u as errorInvalidJson, v as errorMigrationHashMismatch, y as errorMissingFile } from "./errors-EPL_9p9f.mjs";
2
+ import { n as verifyMigrationHash, r as canonicalizeJson } from "./hash-By50zM_E.mjs";
3
+ import { t as deriveProvidedInvariants } from "./invariants-Duc8f9NM.mjs";
4
+ import { n as MigrationOpsSchema } from "./op-schema-D5qkXfEf.mjs";
5
5
  import { basename, dirname, join, resolve } from "pathe";
6
6
  import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
7
7
  import { type } from "arktype";
8
-
9
8
  //#region src/io.ts
10
9
  const MANIFEST_FILE = "migration.json";
11
10
  const OPS_FILE = "ops.json";
@@ -13,11 +12,6 @@ const MAX_SLUG_LENGTH = 64;
13
12
  function hasErrnoCode(error, code) {
14
13
  return error instanceof Error && error.code === code;
15
14
  }
16
- const MigrationHintsSchema = type({
17
- used: "string[]",
18
- applied: "string[]",
19
- plannerVersion: "string"
20
- });
21
15
  const MigrationMetadataSchema = type({
22
16
  "+": "reject",
23
17
  from: "string > 0 | null",
@@ -25,7 +19,11 @@ const MigrationMetadataSchema = type({
25
19
  migrationHash: "string",
26
20
  fromContract: "object | null",
27
21
  toContract: "object",
28
- hints: MigrationHintsSchema,
22
+ hints: type({
23
+ used: "string[]",
24
+ applied: "string[]",
25
+ plannerVersion: "string"
26
+ }),
29
27
  labels: "string[]",
30
28
  providedInvariants: "string[]",
31
29
  "authorship?": type({
@@ -93,6 +91,40 @@ async function materialiseMigrationPackage(targetDir, pkg) {
93
91
  await writeFile(join(dir, "contract.json"), `${canonicalizeJson(pkg.metadata.toContract)}\n`, { flag: "wx" });
94
92
  }
95
93
  /**
94
+ * Idempotent variant of {@link materialiseMigrationPackage}: writes the
95
+ * package only if `<targetDir>/<pkg.dirName>/` does not already exist on
96
+ * disk as a directory; returns `{ written: false }` when the package
97
+ * directory is present (no rewrite, no comparison — by-existence skip).
98
+ *
99
+ * Concretely:
100
+ * - existing directory → skip silently, return `{ written: false }`.
101
+ * - missing path → write three files via {@link materialiseMigrationPackage},
102
+ * return `{ written: true }`.
103
+ * - path exists but is not a directory (file/symlink) → treated as
104
+ * missing; {@link materialiseMigrationPackage} will attempt creation
105
+ * and fail with an appropriate OS error.
106
+ * - any other I/O error from `stat` → propagated unchanged.
107
+ *
108
+ * Used by the CLI's `runContractSpaceExtensionMigrationsPass` to
109
+ * materialise extension migration packages into a project's
110
+ * `migrations/<spaceId>/` directory, and by extension-package tests
111
+ * that mirror the same idempotent-rematerialise property locally
112
+ * without taking a CLI dependency.
113
+ */
114
+ async function materialiseExtensionMigrationPackageIfMissing(targetDir, pkg) {
115
+ if (await directoryExists(join(targetDir, pkg.dirName))) return { written: false };
116
+ await materialiseMigrationPackage(targetDir, pkg);
117
+ return { written: true };
118
+ }
119
+ async function directoryExists(p) {
120
+ try {
121
+ return (await stat(p)).isDirectory();
122
+ } catch (error) {
123
+ if (hasErrnoCode(error, "ENOENT")) return false;
124
+ throw error;
125
+ }
126
+ }
127
+ /**
96
128
  * Copy a list of files into `destDir`, optionally renaming each one.
97
129
  *
98
130
  * The destination directory is created (with `recursive: true`) if it
@@ -201,7 +233,7 @@ function formatMigrationDirName(timestamp, slug) {
201
233
  const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);
202
234
  return `${timestamp.getUTCFullYear()}${String(timestamp.getUTCMonth() + 1).padStart(2, "0")}${String(timestamp.getUTCDate()).padStart(2, "0")}T${String(timestamp.getUTCHours()).padStart(2, "0")}${String(timestamp.getUTCMinutes()).padStart(2, "0")}_${truncated}`;
203
235
  }
204
-
205
236
  //#endregion
206
- export { readMigrationPackage as a, writeMigrationOps as c, materialiseMigrationPackage as i, writeMigrationPackage as l, copyFilesWithRename as n, readMigrationsDir as o, formatMigrationDirName as r, writeMigrationMetadata as s, MANIFEST_FILE as t };
207
- //# sourceMappingURL=io-CDJaWGbt.mjs.map
237
+ 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 };
238
+
239
+ //# sourceMappingURL=io-D13dLvUh.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io-D13dLvUh.mjs","names":[],"sources":["../src/io.ts"],"sourcesContent":["import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';\nimport type {\n MigrationMetadata,\n MigrationPackage,\n} from '@prisma-next/framework-components/control';\nimport { type } from 'arktype';\nimport { basename, dirname, join, resolve } from 'pathe';\nimport { canonicalizeJson } from './canonicalize-json';\nimport {\n errorDirectoryExists,\n errorInvalidDestName,\n errorInvalidJson,\n errorInvalidManifest,\n errorInvalidSlug,\n errorMigrationHashMismatch,\n errorMissingFile,\n errorProvidedInvariantsMismatch,\n} from './errors';\nimport { verifyMigrationHash } from './hash';\nimport { deriveProvidedInvariants } from './invariants';\nimport { MigrationOpsSchema } from './op-schema';\nimport type { MigrationOps, OnDiskMigrationPackage } from './package';\n\nexport const MANIFEST_FILE = 'migration.json';\nconst OPS_FILE = 'ops.json';\nconst MAX_SLUG_LENGTH = 64;\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\nconst MigrationHintsSchema = type({\n used: 'string[]',\n applied: 'string[]',\n plannerVersion: 'string',\n});\n\nconst MigrationMetadataSchema = type({\n '+': 'reject',\n from: 'string > 0 | null',\n to: 'string',\n migrationHash: 'string',\n fromContract: 'object | null',\n toContract: 'object',\n hints: MigrationHintsSchema,\n labels: 'string[]',\n providedInvariants: 'string[]',\n 'authorship?': type({\n 'author?': 'string',\n 'email?': 'string',\n }),\n 'signature?': type({\n keyId: 'string',\n value: 'string',\n }).or('null'),\n createdAt: 'string',\n});\n\nexport async function writeMigrationPackage(\n dir: string,\n metadata: MigrationMetadata,\n ops: MigrationOps,\n): Promise<void> {\n await mkdir(dirname(dir), { recursive: true });\n\n try {\n await mkdir(dir);\n } catch (error) {\n if (hasErrnoCode(error, 'EEXIST')) {\n throw errorDirectoryExists(dir);\n }\n throw error;\n }\n\n await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(metadata, null, 2), {\n flag: 'wx',\n });\n await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: 'wx' });\n}\n\n/**\n * Materialise an in-memory {@link MigrationPackage} to a per-space\n * directory on disk.\n *\n * Writes three files under `<targetDir>/<pkg.dirName>/`:\n *\n * - `migration.json` — the manifest (pretty-printed, matches\n * {@link writeMigrationPackage}'s output for byte-for-byte parity with\n * app-space migrations).\n * - `ops.json` — the operation list (pretty-printed).\n * - `contract.json` — the canonical-JSON serialisation of\n * `metadata.toContract`. This is the per-package post-state contract\n * snapshot; the canonicalisation pass guarantees byte-determinism so\n * re-emitting the same package across machines / runs produces an\n * identical file.\n *\n * Distinct verb from the lower-level {@link writeMigrationPackage}\n * (which takes constituent `(metadata, ops)`): callers reading\n * `materialise…` know they are persisting a struct-typed package\n * including its contract-snapshot side car.\n *\n * Overwrite-idempotent: the per-package directory is cleared before\n * each emit, so re-running against the same `targetDir` produces\n * byte-identical contents and never leaves stale files behind. The\n * spec's \"re-emitting the same package across runs / machines produces\n * byte-identical files\" guarantee (§ 3) covers both same-dir and\n * fresh-dir re-emits. The lower-level {@link writeMigrationPackage}\n * stays strict because the CLI authoring path (`migration plan` /\n * `migration new`) deliberately refuses to clobber an existing\n * authored migration; this helper is the re-emit path that is\n * supposed to converge on a single canonical on-disk shape.\n *\n * @see specs/framework-mechanism.spec.md § 3 — Emission helper (T1.7).\n */\nexport async function materialiseMigrationPackage(\n targetDir: string,\n pkg: MigrationPackage,\n): Promise<void> {\n const dir = join(targetDir, pkg.dirName);\n await rm(dir, { recursive: true, force: true });\n await writeMigrationPackage(dir, pkg.metadata, pkg.ops);\n await writeFile(join(dir, 'contract.json'), `${canonicalizeJson(pkg.metadata.toContract)}\\n`, {\n flag: 'wx',\n });\n}\n\n/**\n * Idempotent variant of {@link materialiseMigrationPackage}: writes the\n * package only if `<targetDir>/<pkg.dirName>/` does not already exist on\n * disk as a directory; returns `{ written: false }` when the package\n * directory is present (no rewrite, no comparison — by-existence skip).\n *\n * Concretely:\n * - existing directory → skip silently, return `{ written: false }`.\n * - missing path → write three files via {@link materialiseMigrationPackage},\n * return `{ written: true }`.\n * - path exists but is not a directory (file/symlink) → treated as\n * missing; {@link materialiseMigrationPackage} will attempt creation\n * and fail with an appropriate OS error.\n * - any other I/O error from `stat` → propagated unchanged.\n *\n * Used by the CLI's `runContractSpaceExtensionMigrationsPass` to\n * materialise extension migration packages into a project's\n * `migrations/<spaceId>/` directory, and by extension-package tests\n * that mirror the same idempotent-rematerialise property locally\n * without taking a CLI dependency.\n */\nexport async function materialiseExtensionMigrationPackageIfMissing(\n targetDir: string,\n pkg: MigrationPackage,\n): Promise<{ readonly written: boolean }> {\n const pkgDir = join(targetDir, pkg.dirName);\n if (await directoryExists(pkgDir)) {\n return { written: false };\n }\n await materialiseMigrationPackage(targetDir, pkg);\n return { written: true };\n}\n\nasync function directoryExists(p: string): Promise<boolean> {\n try {\n return (await stat(p)).isDirectory();\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) return false;\n throw error;\n }\n}\n\n/**\n * Copy a list of files into `destDir`, optionally renaming each one.\n *\n * The destination directory is created (with `recursive: true`) if it\n * does not already exist. Each source path is copied byte-for-byte into\n * `destDir/<destName>`; missing sources throw `ENOENT`. The helper is\n * intentionally generic: callers own the list of files (e.g. a contract\n * emitter's emitted output) and the naming convention (e.g. renaming\n * the destination contract to `end-contract.*` and the source contract\n * to `start-contract.*`).\n */\nexport async function copyFilesWithRename(\n destDir: string,\n files: readonly { readonly sourcePath: string; readonly destName: string }[],\n): Promise<void> {\n await mkdir(destDir, { recursive: true });\n for (const file of files) {\n if (basename(file.destName) !== file.destName) {\n throw errorInvalidDestName(file.destName);\n }\n await copyFile(file.sourcePath, join(destDir, file.destName));\n }\n}\n\nexport async function writeMigrationMetadata(\n dir: string,\n metadata: MigrationMetadata,\n): Promise<void> {\n await writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(metadata, null, 2)}\\n`);\n}\n\nexport async function writeMigrationOps(dir: string, ops: MigrationOps): Promise<void> {\n await writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\\n`);\n}\n\nexport async function readMigrationPackage(dir: string): Promise<OnDiskMigrationPackage> {\n const absoluteDir = resolve(dir);\n const manifestPath = join(absoluteDir, MANIFEST_FILE);\n const opsPath = join(absoluteDir, OPS_FILE);\n\n let manifestRaw: string;\n try {\n manifestRaw = await readFile(manifestPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile(MANIFEST_FILE, absoluteDir);\n }\n throw error;\n }\n\n let opsRaw: string;\n try {\n opsRaw = await readFile(opsPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile(OPS_FILE, absoluteDir);\n }\n throw error;\n }\n\n let metadata: MigrationMetadata;\n try {\n metadata = JSON.parse(manifestRaw);\n } catch (e) {\n throw errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));\n }\n\n let ops: MigrationOps;\n try {\n ops = JSON.parse(opsRaw);\n } catch (e) {\n throw errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));\n }\n\n validateMetadata(metadata, manifestPath);\n validateOps(ops, opsPath);\n\n // Re-derive before the hash check so format/duplicate diagnostics\n // fire with their dedicated codes rather than as a generic hash mismatch.\n const derivedInvariants = deriveProvidedInvariants(ops);\n if (!arraysEqual(metadata.providedInvariants, derivedInvariants)) {\n throw errorProvidedInvariantsMismatch(\n manifestPath,\n metadata.providedInvariants,\n derivedInvariants,\n );\n }\n\n const pkg: OnDiskMigrationPackage = {\n dirName: basename(absoluteDir),\n dirPath: absoluteDir,\n metadata,\n ops,\n };\n\n const verification = verifyMigrationHash(pkg);\n if (!verification.ok) {\n throw errorMigrationHashMismatch(\n absoluteDir,\n verification.storedHash,\n verification.computedHash,\n );\n }\n\n return pkg;\n}\n\nfunction arraysEqual(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction validateMetadata(\n metadata: unknown,\n filePath: string,\n): asserts metadata is MigrationMetadata {\n const result = MigrationMetadataSchema(metadata);\n if (result instanceof type.errors) {\n throw errorInvalidManifest(filePath, result.summary);\n }\n}\n\nfunction validateOps(ops: unknown, filePath: string): asserts ops is MigrationOps {\n const result = MigrationOpsSchema(ops);\n if (result instanceof type.errors) {\n throw errorInvalidManifest(filePath, result.summary);\n }\n}\n\nexport async function readMigrationsDir(\n migrationsRoot: string,\n): Promise<readonly OnDiskMigrationPackage[]> {\n let entries: string[];\n try {\n entries = await readdir(migrationsRoot);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return [];\n }\n throw error;\n }\n\n const packages: OnDiskMigrationPackage[] = [];\n\n for (const entry of entries.sort()) {\n const entryPath = join(migrationsRoot, entry);\n const entryStat = await stat(entryPath);\n if (!entryStat.isDirectory()) continue;\n\n const manifestPath = join(entryPath, MANIFEST_FILE);\n try {\n await stat(manifestPath);\n } catch {\n continue; // skip non-migration directories\n }\n\n packages.push(await readMigrationPackage(entryPath));\n }\n\n return packages;\n}\n\nexport function formatMigrationDirName(timestamp: Date, slug: string): string {\n const sanitized = slug\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '_')\n .replace(/_+/g, '_')\n .replace(/^_|_$/g, '');\n\n if (sanitized.length === 0) {\n throw errorInvalidSlug(slug);\n }\n\n const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);\n\n const y = timestamp.getUTCFullYear();\n const mo = String(timestamp.getUTCMonth() + 1).padStart(2, '0');\n const d = String(timestamp.getUTCDate()).padStart(2, '0');\n const h = String(timestamp.getUTCHours()).padStart(2, '0');\n const mi = String(timestamp.getUTCMinutes()).padStart(2, '0');\n\n return `${y}${mo}${d}T${h}${mi}_${truncated}`;\n}\n"],"mappings":";;;;;;;;AAuBA,MAAa,gBAAgB;AAC7B,MAAM,WAAW;AACjB,MAAM,kBAAkB;AAExB,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;;AASzE,MAAM,0BAA0B,KAAK;CACnC,KA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