🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@prisma-next/migration-tools

Package Overview
Dependencies
Maintainers
4
Versions
610
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@prisma-next/migration-tools - npm Package Compare versions

Comparing version
0.16.0-dev.4
to
0.16.0-dev.5
+118
dist/contract-snapshot-store-DCFUkXwL.mjs
import { a as errorContractSnapshotHashMismatch, m as errorInvalidJson, o as errorContractSnapshotMissing } from "./errors-DldT38lZ.mjs";
import { join, relative } from "pathe";
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import { randomBytes } from "node:crypto";
import { CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex } from "@prisma-next/framework-components/control";
import { canonicalizeJson } from "@prisma-next/framework-components/utils";
import { blindCast } from "@prisma-next/utils/casts";
//#region src/contract-snapshot-store.ts
const CONTRACT_JSON_FILE = "contract.json";
const CONTRACT_DTS_FILE = "contract.d.ts";
function hasErrnoCode(error, code) {
return error instanceof Error && blindCast(error).code === code;
}
async function directoryExists(p) {
try {
return (await stat(p)).isDirectory();
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return false;
throw error;
}
}
function contractSnapshotDir(migrationsDir, storageHash) {
return join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex(storageHash));
}
async function writeContractSnapshot(migrationsDir, storageHash, input) {
const dir = contractSnapshotDir(migrationsDir, storageHash);
const actualStorageHash = blindCast(input.contractJson).storage?.storageHash;
if (actualStorageHash !== storageHash) throw errorContractSnapshotHashMismatch(storageHash, typeof actualStorageHash === "string" ? actualStorageHash : String(actualStorageHash), dir);
if (await directoryExists(dir)) return {
written: false,
dir
};
const tmpDir = join(join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME), `.tmp-${storageHashHex(storageHash)}-${Date.now()}-${randomBytes(4).toString("hex")}`);
await mkdir(tmpDir, { recursive: true });
const jsonContent = `${canonicalizeJson(input.contractJson)}\n`;
const dtsContent = input.contractDts.endsWith("\n") ? input.contractDts : `${input.contractDts}\n`;
try {
await writeFile(join(tmpDir, CONTRACT_JSON_FILE), jsonContent);
await writeFile(join(tmpDir, CONTRACT_DTS_FILE), dtsContent);
await rename(tmpDir, dir);
} catch (error) {
await rm(tmpDir, {
recursive: true,
force: true
});
if (hasErrnoCode(error, "EEXIST") || hasErrnoCode(error, "ENOTEMPTY")) return {
written: false,
dir
};
throw error;
}
return {
written: true,
dir
};
}
async function readContractSnapshotJson(migrationsDir, storageHash) {
const jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);
let raw;
try {
raw = await readFile(jsonPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorContractSnapshotMissing(storageHash, jsonPath);
throw error;
}
try {
return JSON.parse(raw);
} catch (e) {
throw errorInvalidJson(jsonPath, e instanceof Error ? e.message : String(e));
}
}
/**
* Tolerant read: a missing store entry (ENOENT), an unparseable
* `contract.json`, the JSON literal `null`, or a `storageHash` that isn't a
* well-formed `sha256:<64hex>` value all resolve to `undefined` rather than
* throwing — parity with the catch-all tolerance of the pre-store
* `readEndContractJson` (`io.ts`), which never validated the hash it was
* keyed by either. Any other fs error (e.g. `EACCES` on a present-but-
* unreadable file) propagates rather than silently loading a contract-less
* package.
*/
async function readContractSnapshotJsonTolerant(migrationsDir, storageHash) {
let jsonPath;
try {
jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);
} catch {
return;
}
let raw;
try {
raw = await readFile(jsonPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return;
throw error;
}
try {
const parsed = JSON.parse(raw);
return parsed === null ? void 0 : parsed;
} catch {
return;
}
}
async function readContractSnapshotDts(migrationsDir, storageHash) {
const dtsPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_DTS_FILE);
try {
return await readFile(dtsPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorContractSnapshotMissing(storageHash, dtsPath);
throw error;
}
}
function snapshotsImportPathFrom(packageDir, migrationsDir) {
return relative(packageDir, join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME)).split("\\").join("/");
}
//#endregion
export { snapshotsImportPathFrom as a, readContractSnapshotJsonTolerant as i, readContractSnapshotDts as n, writeContractSnapshot as o, readContractSnapshotJson as r, contractSnapshotDir as t };
//# sourceMappingURL=contract-snapshot-store-DCFUkXwL.mjs.map
{"version":3,"file":"contract-snapshot-store-DCFUkXwL.mjs","names":[],"sources":["../src/contract-snapshot-store.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport {\n CONTRACT_SNAPSHOTS_DIRNAME,\n storageHashHex,\n} from '@prisma-next/framework-components/control';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { blindCast } from '@prisma-next/utils/casts';\nimport { join, relative } from 'pathe';\nimport {\n errorContractSnapshotHashMismatch,\n errorContractSnapshotMissing,\n errorInvalidJson,\n} from './errors';\n\nconst CONTRACT_JSON_FILE = 'contract.json';\nconst CONTRACT_DTS_FILE = 'contract.d.ts';\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return (\n error instanceof Error &&\n blindCast<\n { code?: string },\n 'Node fs errors carry an errno string `code` absent from the Error type'\n >(error).code === code\n );\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\nexport function contractSnapshotDir(migrationsDir: string, storageHash: string): string {\n return join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex(storageHash));\n}\n\nexport interface ContractSnapshotInput {\n readonly contractJson: unknown;\n readonly contractDts: string;\n}\n\nexport async function writeContractSnapshot(\n migrationsDir: string,\n storageHash: string,\n input: ContractSnapshotInput,\n): Promise<{ readonly written: boolean; readonly dir: string }> {\n const dir = contractSnapshotDir(migrationsDir, storageHash);\n\n // contractJson is unknown JSON; only storage.storageHash is read, to check\n // it against the hash the snapshot is being written under.\n const contractStorage = blindCast<\n { storage?: { storageHash?: unknown } },\n 'contractJson is unknown JSON; only the storage.storageHash field is read here'\n >(input.contractJson);\n const actualStorageHash = contractStorage.storage?.storageHash;\n if (actualStorageHash !== storageHash) {\n throw errorContractSnapshotHashMismatch(\n storageHash,\n typeof actualStorageHash === 'string' ? actualStorageHash : String(actualStorageHash),\n dir,\n );\n }\n\n if (await directoryExists(dir)) {\n return { written: false, dir };\n }\n\n const snapshotsDir = join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME);\n const tmpDir = join(\n snapshotsDir,\n `.tmp-${storageHashHex(storageHash)}-${Date.now()}-${randomBytes(4).toString('hex')}`,\n );\n await mkdir(tmpDir, { recursive: true });\n\n const jsonContent = `${canonicalizeJson(input.contractJson)}\\n`;\n const dtsContent = input.contractDts.endsWith('\\n')\n ? input.contractDts\n : `${input.contractDts}\\n`;\n\n try {\n await writeFile(join(tmpDir, CONTRACT_JSON_FILE), jsonContent);\n await writeFile(join(tmpDir, CONTRACT_DTS_FILE), dtsContent);\n await rename(tmpDir, dir);\n } catch (error) {\n await rm(tmpDir, { recursive: true, force: true });\n if (hasErrnoCode(error, 'EEXIST') || hasErrnoCode(error, 'ENOTEMPTY')) {\n return { written: false, dir };\n }\n throw error;\n }\n\n return { written: true, dir };\n}\n\nexport async function readContractSnapshotJson(\n migrationsDir: string,\n storageHash: string,\n): Promise<unknown> {\n const jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorContractSnapshotMissing(storageHash, jsonPath);\n }\n throw error;\n }\n\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw errorInvalidJson(jsonPath, e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Tolerant read: a missing store entry (ENOENT), an unparseable\n * `contract.json`, the JSON literal `null`, or a `storageHash` that isn't a\n * well-formed `sha256:<64hex>` value all resolve to `undefined` rather than\n * throwing — parity with the catch-all tolerance of the pre-store\n * `readEndContractJson` (`io.ts`), which never validated the hash it was\n * keyed by either. Any other fs error (e.g. `EACCES` on a present-but-\n * unreadable file) propagates rather than silently loading a contract-less\n * package.\n */\nexport async function readContractSnapshotJsonTolerant(\n migrationsDir: string,\n storageHash: string,\n): Promise<unknown | undefined> {\n let jsonPath: string;\n try {\n jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);\n } catch {\n return undefined;\n }\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return undefined;\n }\n throw error;\n }\n\n try {\n const parsed: unknown = JSON.parse(raw);\n return parsed === null ? undefined : parsed;\n } catch {\n return undefined;\n }\n}\n\nexport async function readContractSnapshotDts(\n migrationsDir: string,\n storageHash: string,\n): Promise<string> {\n const dtsPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_DTS_FILE);\n\n try {\n return await readFile(dtsPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorContractSnapshotMissing(storageHash, dtsPath);\n }\n throw error;\n }\n}\n\nexport function snapshotsImportPathFrom(packageDir: string, migrationsDir: string): string {\n const storeDir = join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME);\n return relative(packageDir, storeDir).split('\\\\').join('/');\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAE1B,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OACE,iBAAiB,SACjB,UAGE,KAAK,CAAC,CAAC,SAAS;AAEtB;AAEA,eAAe,gBAAgB,GAA6B;CAC1D,IAAI;EACF,QAAQ,MAAM,KAAK,CAAC,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aACkB;CAClB,MAAM,WAAW,KAAK,oBAAoB,eAAe,WAAW,GAAG,kBAAkB;CAEzF,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,SAAS,UAAU,OAAO;CACxC,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAC9B,MAAM,6BAA6B,aAAa,QAAQ;EAE1D,MAAM;CACR;CAEA,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,SAAS,GAAG;EACV,MAAM,iBAAiB,UAAU,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;CAC7E;AACF;;;;;;;;;;;AAYA,eAAsB,iCACpB,eACA,aAC8B;CAC9B,IAAI;CACJ,IAAI;EACF,WAAW,KAAK,oBAAoB,eAAe,WAAW,GAAG,kBAAkB;CACrF,QAAQ;EACN;CACF;CAEA,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,SAAS,UAAU,OAAO;CACxC,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAC9B;EAEF,MAAM;CACR;CAEA,IAAI;EACF,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,OAAO,WAAW,OAAO,KAAA,IAAY;CACvC,QAAQ;EACN;CACF;AACF;AAEA,eAAsB,wBACpB,eACA,aACiB;CACjB,MAAM,UAAU,KAAK,oBAAoB,eAAe,WAAW,GAAG,iBAAiB;CAEvF,IAAI;EACF,OAAO,MAAM,SAAS,SAAS,OAAO;CACxC,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAC9B,MAAM,6BAA6B,aAAa,OAAO;EAEzD,MAAM;CACR;AACF;AAEA,SAAgB,wBAAwB,YAAoB,eAA+B;CAEzF,OAAO,SAAS,YADC,KAAK,eAAe,0BACF,CAAC,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,KAAK,GAAG;AAC5D"}
import { ifDefined } from "@prisma-next/utils/defined";
import { dirname, relative } from "pathe";
//#region src/errors.ts
/**
* Build the canonical "re-emit this package" remediation hint.
*
* Every on-disk migration package ships its own `migration.ts` author-time
* file. Running it regenerates `migration.json` and `ops.json` with the
* correct hash + metadata, so it is the right primitive whenever a single
* package's on-disk artifacts are missing, malformed, or otherwise corrupt.
* Pointing users at `migration plan` would emit a *new* package rather than
* heal the broken one.
*/
function reemitHint(dir, fallback) {
const reemit = `Re-emit the package by running \`node "${relative(process.cwd(), dir)}/migration.ts"\``;
return fallback ? `${reemit}, ${fallback}` : `${reemit}.`;
}
/**
* Structured error for migration tooling operations.
*
* Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under
* the MIGRATION namespace. These are tooling-time errors (file I/O, hash
* verification, migration history reconstruction), distinct from the runtime
* MIGRATION.* codes for apply-time failures (PRECHECK_FAILED, POSTCHECK_FAILED,
* etc.).
*
* Fields:
* - code: Stable machine-readable code (MIGRATION.SUBCODE)
* - category: Always 'MIGRATION'
* - why: Explains the cause in plain language
* - fix: Actionable remediation step
* - details: Machine-readable structured data for agents
*/
var MigrationToolsError = class extends Error {
code;
category = "MIGRATION";
why;
fix;
details;
constructor(code, summary, options) {
super(summary);
this.name = "MigrationToolsError";
this.code = code;
this.why = options.why;
this.fix = options.fix;
this.details = options.details;
}
static is(error) {
if (!(error instanceof Error)) return false;
const candidate = error;
return candidate.name === "MigrationToolsError" && typeof candidate.code === "string";
}
};
function errorDirectoryExists(dir) {
return new MigrationToolsError("MIGRATION.DIR_EXISTS", "Migration directory already exists", {
why: `The directory "${dir}" already exists. Each migration must have a unique directory.`,
fix: "Use --name to pick a different name, or delete the existing directory and re-run.",
details: { dir }
});
}
function errorMissingFile(file, dir) {
return new MigrationToolsError("MIGRATION.FILE_MISSING", `Missing ${file}`, {
why: `Expected "${file}" in "${dir}" but the file does not exist.`,
fix: reemitHint(dir, "or delete the directory if the migration is unwanted and the source TypeScript is gone."),
details: {
file,
dir
}
});
}
function errorInvalidJson(filePath, parseError) {
return new MigrationToolsError("MIGRATION.INVALID_JSON", "Invalid JSON in migration file", {
why: `Failed to parse "${filePath}": ${parseError}`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
parseError
}
});
}
function errorInvalidManifest(filePath, reason) {
return new MigrationToolsError("MIGRATION.INVALID_MANIFEST", "Invalid migration manifest", {
why: `Migration manifest at "${filePath}" is invalid: ${reason}`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
reason
}
});
}
function errorInvalidOperationEntry(index, reason) {
return new MigrationToolsError("MIGRATION.INVALID_OPERATION_ENTRY", "Migration operation entry is malformed", {
why: `Operation at index ${index} returned by the migration class failed schema validation: ${reason}.`,
fix: "Update the migration class so each entry of `operations` carries `id` (string), `label` (string), and `operationClass` (one of 'additive' | 'widening' | 'destructive' | 'data').",
details: {
index,
reason
}
});
}
function errorInvalidSlug(slug) {
return new MigrationToolsError("MIGRATION.INVALID_NAME", "Invalid migration name", {
why: `The slug "${slug}" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,
fix: "Provide a name with at least one alphanumeric character, e.g. --name add_users.",
details: { slug }
});
}
function errorInvalidDestName(destName) {
return new MigrationToolsError("MIGRATION.INVALID_DEST_NAME", "Invalid copy destination name", {
why: `The destination name "${destName}" must be a single path segment (no ".." or directory separators).`,
fix: "Use a simple file name such as \"contract.json\" for each destination in the copy list.",
details: { destName }
});
}
function errorInvalidSpaceId(spaceId) {
return new MigrationToolsError("MIGRATION.INVALID_SPACE_ID", "Invalid contract space identifier", {
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.`,
fix: "Pick a lowercase identifier that begins with a letter and contains only lowercase letters, digits, hyphens, or underscores; max 64 characters total.",
details: { spaceId }
});
}
function errorDescriptorHeadHashMismatch(args) {
const { extensionId, recomputedHash, headRefHash } = args;
return new MigrationToolsError("MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH", "Extension descriptor's headRef.hash does not match its contractJson", {
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.`,
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).",
details: {
extensionId,
recomputedHash,
headRefHash
}
});
}
function errorDuplicateSpaceId(spaceId) {
return new MigrationToolsError("MIGRATION.DUPLICATE_SPACE_ID", "Duplicate contract space identifier", {
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).`,
fix: "Deduplicate the inputs before passing them to `planAllSpaces` — typically by checking your `extensionPacks` declaration for repeated entries.",
details: { spaceId }
});
}
function errorAmbiguousTarget(branchTips, context) {
const divergenceInfo = context ? `\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")}` : "";
return new MigrationToolsError("MIGRATION.AMBIGUOUS_TARGET", "Ambiguous migration target", {
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}`,
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.",
details: {
branchTips,
...context ? {
divergencePoint: context.divergencePoint,
branches: context.branches
} : {}
}
});
}
function errorNoInitialMigration(nodes) {
return new MigrationToolsError("MIGRATION.NO_INITIAL_MIGRATION", "No initial migration found", {
why: `No migration starts from the empty contract state (known hashes: ${nodes.join(", ")}). At least one migration must originate from the empty state.`,
fix: "Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.",
details: { nodes }
});
}
function errorInvalidRefFile(filePath, reason) {
return new MigrationToolsError("MIGRATION.INVALID_REF_FILE", "Invalid ref file", {
why: `Ref file at "${filePath}" is invalid: ${reason}`,
fix: "Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.",
details: {
path: filePath,
reason
}
});
}
function errorInvalidRefName(refName) {
return new MigrationToolsError("MIGRATION.INVALID_REF_NAME", "Invalid ref name", {
why: `Ref name "${refName}" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no "." or ".." segments).`,
fix: `Use a valid ref name (e.g., "staging", "envs/production").`,
details: { refName }
});
}
function errorNoTarget(reachableHashes) {
return new MigrationToolsError("MIGRATION.NO_TARGET", "No migration target could be resolved", {
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).`,
fix: "Use --from <hash> to specify the planning origin explicitly.",
details: { reachableHashes }
});
}
function errorInvalidRefValue(value) {
return new MigrationToolsError("MIGRATION.INVALID_REF_VALUE", "Invalid ref value", {
why: `Ref value "${value}" is not a valid contract hash. Values must be in the format "sha256:<64 hex chars>" or "sha256:empty".`,
fix: "Use a valid storage hash from `prisma-next contract emit` output or an existing migration.",
details: { value }
});
}
function errorInvalidInvariantId(invariantId) {
return new MigrationToolsError("MIGRATION.INVALID_INVARIANT_ID", "Invalid invariantId", {
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.`,
fix: "Pick an invariantId without spaces, tabs, newlines, or control characters — e.g. \"backfill-user-phone\", \"users/backfill-phone\", or \"BackfillUserPhone\".",
details: { invariantId }
});
}
function errorDuplicateInvariantInEdge(invariantId) {
return new MigrationToolsError("MIGRATION.DUPLICATE_INVARIANT_IN_EDGE", "Duplicate invariantId on a single migration", {
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.`,
fix: "Rename one of the conflicting dataTransform invariantIds, or drop invariantId on the op that does not need to be routing-visible.",
details: { invariantId }
});
}
function errorProvidedInvariantsMismatch(filePath, stored, derived) {
const storedSet = new Set(stored);
const derivedSet = new Set(derived);
const missing = [...derivedSet].filter((id) => !storedSet.has(id));
const extra = [...storedSet].filter((id) => !derivedSet.has(id));
return new MigrationToolsError("MIGRATION.PROVIDED_INVARIANTS_MISMATCH", "providedInvariants on migration.json disagrees with ops.json", {
why: missing.length === 0 && extra.length === 0 ? `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.` : `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.`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
stored,
derived,
difference: {
missing,
extra
}
}
});
}
function errorNoInvariantPath(args) {
const { refName, required, missing, structuralPath } = args;
const refClause = refName ? `Ref "${refName}"` : "Target";
const missingList = missing.map((id) => JSON.stringify(id)).join(", ");
return new MigrationToolsError("MIGRATION.NO_INVARIANT_PATH", "No path covers the required invariants", {
why: `${refClause} requires invariants the reachable path doesn't cover. required=[${required.map((id) => JSON.stringify(id)).join(", ")}], missing=[${missingList}].`,
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.",
details: {
required,
missing,
structuralPath,
...ifDefined("refName", refName)
}
});
}
function errorUnknownInvariant(args) {
const { refName, unknown, declared } = args;
return new MigrationToolsError("MIGRATION.UNKNOWN_INVARIANT", "Ref declares invariants no migration in the graph provides", {
why: `${refName ? `Ref "${refName}" declares` : "Declares"} invariants no migration in the graph provides. unknown=[${unknown.map((id) => JSON.stringify(id)).join(", ")}].`,
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.",
details: {
unknown,
declared,
...ifDefined("refName", refName)
}
});
}
function errorMigrationHashMismatch(dir, storedHash, computedHash) {
return new MigrationToolsError("MIGRATION.HASH_MISMATCH", "Migration package is corrupt", {
why: `Stored migrationHash "${storedHash}" does not match the recomputed hash "${computedHash}" for "${relative(process.cwd(), dir)}". The migration.json or ops.json has been edited or partially written since emit.`,
fix: reemitHint(dir, "or restore the directory from version control."),
details: {
dir,
storedHash,
computedHash
}
});
}
function errorSnapshotMissing(refName) {
return new MigrationToolsError("MIGRATION.SNAPSHOT_MISSING", `Ref "${refName}" has no paired contract snapshot`, {
why: `Ref "${refName}" exists but its paired snapshot files are missing.`,
fix: `Run "prisma-next db update --advance-ref ${refName}" to repopulate the snapshot, or "prisma-next ref delete ${refName}" to clear the orphan pointer.`,
details: {
refName,
identifier: refName,
viaRef: true
}
});
}
function errorBundleNotFoundForGraphNode(hash, explicitLabel) {
return new MigrationToolsError("MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE", explicitLabel ? `No migration bundle found for reference "${explicitLabel}" (resolved hash: ${hash})` : `No migration bundle found for graph node ${hash}`, {
why: `The hash ${hash} is a graph node but no on-disk migration package has a destination (\`to\`) hash matching it.`,
fix: "Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.",
details: {
hash,
...explicitLabel ? { explicitLabel } : {}
}
});
}
function errorContractDeserializationFailed(filePath, message) {
return new MigrationToolsError("MIGRATION.CONTRACT_DESERIALIZATION_FAILED", "Contract failed to deserialize", {
why: `Contract at "${filePath}" failed to deserialize: ${message}`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
message
}
});
}
function errorHashNotInGraph(hash, graph) {
const reachableHashes = [...graph.nodes].sort();
const reachableList = reachableHashes.length > 0 ? reachableHashes.join(", ") : "(none)";
return new MigrationToolsError("MIGRATION.HASH_NOT_IN_GRAPH", `Hash "${hash}" is not a node in the migration graph`, {
why: `The migration graph contains nodes ${reachableList}; "${hash}" isn't one of them.`,
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.`,
details: {
hash,
reachableHashes
}
});
}
function errorContractSnapshotMissing(storageHash, expectedPath) {
return new MigrationToolsError("MIGRATION.CONTRACT_SNAPSHOT_MISSING", "Contract snapshot is missing", {
why: `Expected a contract snapshot for ${storageHash} at "${expectedPath}" but the file does not exist.`,
fix: "Re-emit the contract snapshot by re-running the command that authored the migration referencing this hash (`prisma-next migration plan` for app-space migrations; the extension's contract-space build for extension spaces), or restore migrations/snapshots/ from version control.",
details: {
storageHash,
expectedPath
}
});
}
function errorContractSnapshotHashMismatch(storageHash, actualHash, dir) {
return new MigrationToolsError("MIGRATION.CONTRACT_SNAPSHOT_HASH_MISMATCH", "Contract snapshot hash mismatch", {
why: `The contract JSON's inner storage.storageHash ("${actualHash}") does not match the requested storage hash ("${storageHash}") for snapshot directory "${dir}".`,
fix: "Pass a contractJson whose storage.storageHash equals the storageHash argument passed to writeContractSnapshot — the two must agree by construction.",
details: {
storageHash,
actualHash,
dir
}
});
}
function errorMigrationContractViewMissing(className, accessor, jsonField) {
return new MigrationToolsError("MIGRATION.CONTRACT_VIEW_MISSING", `${className}.${accessor} requires ${jsonField}`, {
why: `${className}.${accessor} was read, but this instance has no ${jsonField} to build the view from.`,
fix: `Set ${jsonField} to the migration's committed contract JSON, or avoid reading ${accessor} on a migration that overrides describe() and carries no contract.`,
details: {
className,
accessor,
jsonField
}
});
}
//#endregion
export { errorUnknownInvariant as A, errorMigrationHashMismatch as C, errorNoTarget as D, errorNoInvariantPath as E, errorProvidedInvariantsMismatch as O, errorMigrationContractViewMissing as S, errorNoInitialMigration as T, errorInvalidRefFile as _, errorContractSnapshotHashMismatch as a, errorInvalidSlug as b, errorDirectoryExists as c, errorHashNotInGraph as d, errorInvalidDestName as f, errorInvalidOperationEntry as g, errorInvalidManifest as h, errorContractDeserializationFailed as i, errorSnapshotMissing as k, errorDuplicateInvariantInEdge as l, errorInvalidJson as m, errorAmbiguousTarget as n, errorContractSnapshotMissing as o, errorInvalidInvariantId as p, errorBundleNotFoundForGraphNode as r, errorDescriptorHeadHashMismatch as s, MigrationToolsError as t, errorDuplicateSpaceId as u, errorInvalidRefName as v, errorMissingFile as w, errorInvalidSpaceId as x, errorInvalidRefValue as y };
//# sourceMappingURL=errors-DldT38lZ.mjs.map
{"version":3,"file":"errors-DldT38lZ.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 errorSnapshotMissing(refName: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.SNAPSHOT_MISSING',\n `Ref \"${refName}\" has no paired contract snapshot`,\n {\n why: `Ref \"${refName}\" exists but its paired snapshot files are missing.`,\n fix: `Run \"prisma-next db update --advance-ref ${refName}\" to repopulate the snapshot, or \"prisma-next ref delete ${refName}\" to clear the orphan pointer.`,\n details: { refName, identifier: refName, viaRef: true },\n },\n );\n}\n\nexport function errorBundleNotFoundForGraphNode(\n hash: string,\n explicitLabel?: string,\n): MigrationToolsError {\n const summary = explicitLabel\n ? `No migration bundle found for reference \"${explicitLabel}\" (resolved hash: ${hash})`\n : `No migration bundle found for graph node ${hash}`;\n return new MigrationToolsError('MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE', summary, {\n why: `The hash ${hash} is a graph node but no on-disk migration package has a destination (\\`to\\`) hash matching it.`,\n fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',\n details: { hash, ...(explicitLabel ? { explicitLabel } : {}) },\n });\n}\n\nexport function errorContractDeserializationFailed(\n filePath: string,\n message: string,\n): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.CONTRACT_DESERIALIZATION_FAILED',\n 'Contract failed to deserialize',\n {\n why: `Contract at \"${filePath}\" failed to deserialize: ${message}`,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, message },\n },\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\nexport function errorContractSnapshotMissing(\n storageHash: string,\n expectedPath: string,\n): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.CONTRACT_SNAPSHOT_MISSING',\n 'Contract snapshot is missing',\n {\n why: `Expected a contract snapshot for ${storageHash} at \"${expectedPath}\" but the file does not exist.`,\n fix: \"Re-emit the contract snapshot by re-running the command that authored the migration referencing this hash (`prisma-next migration plan` for app-space migrations; the extension's contract-space build for extension spaces), or restore migrations/snapshots/ from version control.\",\n details: { storageHash, expectedPath },\n },\n );\n}\n\nexport function errorContractSnapshotHashMismatch(\n storageHash: string,\n actualHash: string,\n dir: string,\n): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.CONTRACT_SNAPSHOT_HASH_MISMATCH',\n 'Contract snapshot hash mismatch',\n {\n why: `The contract JSON's inner storage.storageHash (\"${actualHash}\") does not match the requested storage hash (\"${storageHash}\") for snapshot directory \"${dir}\".`,\n fix: 'Pass a contractJson whose storage.storageHash equals the storageHash argument passed to writeContractSnapshot — the two must agree by construction.',\n details: { storageHash, actualHash, dir },\n },\n );\n}\n\nexport function errorMigrationContractViewMissing(\n className: string,\n accessor: 'endContract' | 'startContract',\n jsonField: 'endContractJson' | 'startContractJson',\n): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.CONTRACT_VIEW_MISSING',\n `${className}.${accessor} requires ${jsonField}`,\n {\n why: `${className}.${accessor} was read, but this instance has no ${jsonField} to build the view from.`,\n fix: `Set ${jsonField} to the migration's committed contract JSON, or avoid reading ${accessor} on a migration that overrides describe() and carries no contract.`,\n details: { className, accessor, jsonField },\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;CAC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gB,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;AAEA,SAAgB,6BACd,aACA,cACqB;CACrB,OAAO,IAAI,oBACT,uCACA,gCACA;EACE,KAAK,oCAAoC,YAAY,OAAO,aAAa;EACzE,KAAK;EACL,SAAS;GAAE;GAAa;EAAa;CACvC,CACF;AACF;AAEA,SAAgB,kCACd,aACA,YACA,KACqB;CACrB,OAAO,IAAI,oBACT,6CACA,mCACA;EACE,KAAK,mDAAmD,WAAW,iDAAiD,YAAY,6BAA6B,IAAI;EACjK,KAAK;EACL,SAAS;GAAE;GAAa;GAAY;EAAI;CAC1C,CACF;AACF;AAEA,SAAgB,kCACd,WACA,UACA,WACqB;CACrB,OAAO,IAAI,oBACT,mCACA,GAAG,UAAU,GAAG,SAAS,YAAY,aACrC;EACE,KAAK,GAAG,UAAU,GAAG,SAAS,sCAAsC,UAAU;EAC9E,KAAK,OAAO,UAAU,gEAAgE,SAAS;EAC/F,SAAS;GAAE;GAAW;GAAU;EAAU;CAC5C,CACF;AACF"}
//#region src/contract-snapshot-store.d.ts
declare function contractSnapshotDir(migrationsDir: string, storageHash: string): string;
interface ContractSnapshotInput {
readonly contractJson: unknown;
readonly contractDts: string;
}
declare function writeContractSnapshot(migrationsDir: string, storageHash: string, input: ContractSnapshotInput): Promise<{
readonly written: boolean;
readonly dir: string;
}>;
declare function readContractSnapshotJson(migrationsDir: string, storageHash: string): Promise<unknown>;
/**
* Tolerant read: a missing store entry (ENOENT), an unparseable
* `contract.json`, the JSON literal `null`, or a `storageHash` that isn't a
* well-formed `sha256:<64hex>` value all resolve to `undefined` rather than
* throwing — parity with the catch-all tolerance of the pre-store
* `readEndContractJson` (`io.ts`), which never validated the hash it was
* keyed by either. Any other fs error (e.g. `EACCES` on a present-but-
* unreadable file) propagates rather than silently loading a contract-less
* package.
*/
declare function readContractSnapshotJsonTolerant(migrationsDir: string, storageHash: string): Promise<unknown | undefined>;
declare function readContractSnapshotDts(migrationsDir: string, storageHash: string): Promise<string>;
declare function snapshotsImportPathFrom(packageDir: string, migrationsDir: string): string;
//#endregion
export { type ContractSnapshotInput, contractSnapshotDir, readContractSnapshotDts, readContractSnapshotJson, readContractSnapshotJsonTolerant, snapshotsImportPathFrom, writeContractSnapshot };
//# sourceMappingURL=contract-snapshot-store.d.mts.map
{"version":3,"file":"contract-snapshot-store.d.mts","names":[],"sources":["../../src/contract-snapshot-store.ts"],"mappings":";iBAqCgB,oBAAoB,uBAAuB;UAI1C;WACN;WACA;;iBAGW,sBACpB,uBACA,qBACA,OAAO,wBACN;WAAmB;WAA2B;;iBAiD3B,yBACpB,uBACA,sBACC;;;;;;;;;;;iBA8BmB,iCACpB,uBACA,sBACC;iBA0BmB,wBACpB,uBACA,sBACC;iBAaa,wBAAwB,oBAAoB"}
import { a as snapshotsImportPathFrom, i as readContractSnapshotJsonTolerant, n as readContractSnapshotDts, o as writeContractSnapshot, r as readContractSnapshotJson, t as contractSnapshotDir } from "../contract-snapshot-store-DCFUkXwL.mjs";
export { contractSnapshotDir, readContractSnapshotDts, readContractSnapshotJson, readContractSnapshotJsonTolerant, snapshotsImportPathFrom, writeContractSnapshot };
import { d as errorHashNotInGraph } from "./errors-DldT38lZ.mjs";
import "./constants-YnG8_EGO.mjs";
//#region src/graph-membership.ts
function isGraphNode(hash, graph) {
if (hash === "sha256:empty") return true;
return graph.nodes.has(hash);
}
function assertHashIsGraphNode(hash, graph) {
if (isGraphNode(hash, graph)) return;
throw errorHashNotInGraph(hash, graph);
}
//#endregion
export { isGraphNode as n, assertHashIsGraphNode as t };
//# sourceMappingURL=graph-membership-DDYdPRwc.mjs.map
{"version":3,"file":"graph-membership-DDYdPRwc.mjs","names":[],"sources":["../src/graph-membership.ts"],"sourcesContent":["import { EMPTY_CONTRACT_HASH } from './constants';\nimport { errorHashNotInGraph } from './errors';\nimport type { MigrationGraph } from './graph';\n\nexport function isGraphNode(hash: string, graph: MigrationGraph): boolean {\n if (hash === EMPTY_CONTRACT_HASH) {\n return true;\n }\n return graph.nodes.has(hash);\n}\n\nexport function assertHashIsGraphNode(hash: string, graph: MigrationGraph): asserts hash is string {\n if (isGraphNode(hash, graph)) {\n return;\n }\n throw errorHashNotInGraph(hash, graph);\n}\n"],"mappings":";;;AAIA,SAAgB,YAAY,MAAc,OAAgC;CACxE,IAAI,SAAA,gBACF,OAAO;CAET,OAAO,MAAM,MAAM,IAAI,IAAI;AAC7B;AAEA,SAAgB,sBAAsB,MAAc,OAA+C;CACjG,IAAI,YAAY,MAAM,KAAK,GACzB;CAEF,MAAM,oBAAoB,MAAM,KAAK;AACvC"}
import { l as errorDuplicateInvariantInEdge, p as errorInvalidInvariantId } from "./errors-DldT38lZ.mjs";
//#region src/invariants.ts
/**
* Hygiene check for `invariantId`. Rejects empty values plus any
* whitespace or control character (including Unicode whitespace like
* NBSP and em space, which are visually identical to ASCII space and
* routinely sneak in via paste).
*/
function validateInvariantId(invariantId) {
if (invariantId.length === 0) return false;
return !/[\p{Cc}\p{White_Space}]/u.test(invariantId);
}
/**
* Walk a migration's operations and produce its `providedInvariants`
* aggregate: the sorted, deduplicated list of `invariantId`s declared
* by ops in the migration. Ops without an `invariantId` are skipped.
*
* Both `data`-class ops (data-transforms, e.g. backfills) and
* `additive`-class opaque DDL (e.g. cipherstash's vendored EQL bundle
* via `installEqlBundleOp`) may declare invariantIds: the
* `operationClass` axis classifies *policy gating* (which kinds of ops
* a `db init` / `db update` policy permits), while `invariantId`
* classifies *marker bookkeeping* (which named bundles of work a
* future regeneration knows to skip). The two concerns are
* intentionally orthogonal — an extension can ship additive
* non-IR-derivable DDL (the only way the planner can know the bundle
* is already applied is via the invariantId on the marker) without
* needing to mis-classify it as `data`-class.
*
* Throws `MIGRATION.INVALID_INVARIANT_ID` on a malformed id and
* `MIGRATION.DUPLICATE_INVARIANT_IN_EDGE` on duplicates.
*
* @see docs/architecture docs/adrs/ADR 212 - Contract spaces.md
* — extension migrations carry `invariantId`s on additive ops; e.g.
* cipherstash's `installEqlBundle` and structural `create-*` ops are
* additive-class but carry `cipherstash:*` invariantIds.
*/
function deriveProvidedInvariants(ops) {
const seen = /* @__PURE__ */ new Set();
for (const op of ops) {
const invariantId = readInvariantId(op);
if (invariantId === void 0) continue;
if (!validateInvariantId(invariantId)) throw errorInvalidInvariantId(invariantId);
if (seen.has(invariantId)) throw errorDuplicateInvariantInEdge(invariantId);
seen.add(invariantId);
}
return [...seen].sort();
}
function readInvariantId(op) {
if (!Object.hasOwn(op, "invariantId")) return void 0;
const candidate = op.invariantId;
return typeof candidate === "string" ? candidate : void 0;
}
//#endregion
export { validateInvariantId as n, deriveProvidedInvariants as t };
//# sourceMappingURL=invariants-BcT9Izto.mjs.map
{"version":3,"file":"invariants-BcT9Izto.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 *\n * @see docs/architecture docs/adrs/ADR 212 - Contract spaces.md\n * — extension migrations carry `invariantId`s on additive ops; e.g.\n * cipherstash's `installEqlBundle` and structural `create-*` ops are\n * additive-class but carry `cipherstash:*` invariantIds.\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,WAAW;AACrD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,yBAAyB,KAAsC;CAC7E,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,cAAc,gBAAgB,EAAE;EACtC,IAAI,gBAAgB,KAAA,GAAW;EAC/B,IAAI,CAAC,oBAAoB,WAAW,GAClC,MAAM,wBAAwB,WAAW;EAE3C,IAAI,KAAK,IAAI,WAAW,GACtB,MAAM,8BAA8B,WAAW;EAEjD,KAAK,IAAI,WAAW;CACtB;CACA,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;AACxB;AAEA,SAAS,gBAAgB,IAAgD;CACvE,IAAI,CAAC,OAAO,OAAO,IAAI,aAAa,GAAG,OAAO,KAAA;CAC9C,MAAM,YAAa,GAAiC;CACpD,OAAO,OAAO,cAAc,WAAW,YAAY,KAAA;AACrD"}
import { n as OnDiskMigrationPackage, t as MigrationOps } from "./package-CCIHXr9Z.mjs";
import { MigrationMetadata, MigrationPackage } from "@prisma-next/framework-components/control";
//#region src/io.d.ts
interface ReadMigrationPackageOptions {
readonly migrationsDir: string;
}
declare function writeMigrationPackage(dir: string, metadata: MigrationMetadata, ops: MigrationOps): Promise<void>;
/**
* Materialise an in-memory {@link MigrationPackage} to a per-space
* directory on disk.
*
* Writes two files under `<targetDir>/<pkg.dirName>/`:
*
* - `migration.json` — the manifest (pretty-printed, matches
* {@link writeMigrationPackage}'s output for byte-for-byte parity with
* app-space migrations).
* - `ops.json` — the operation list (pretty-printed).
*
* Distinct verb from the lower-level {@link writeMigrationPackage}
* (which takes constituent `(metadata, ops)`): callers reading
* `materialise…` know they are persisting a struct-typed package.
*
* Overwrite-idempotent: the per-package directory is cleared before
* each emit, so re-running against the same `targetDir` produces
* byte-identical contents and never leaves stale files behind. The
* lower-level {@link writeMigrationPackage} stays strict because the
* CLI authoring path (`migration plan` / `migration new`) deliberately
* refuses to clobber an existing authored migration; this helper is
* the re-emit path that is supposed to converge on a single canonical
* on-disk shape.
*
* The per-space head contract resolves through
* `<projectMigrationsDir>/snapshots/<hex>/` (written by
* {@link import('./emit-contract-space-artifacts').emitContractSpaceArtifacts}),
* not inside the per-package directory. The runner reads only
* `migration.json` + `ops.json` from each package.
*/
declare function materialiseMigrationPackage(targetDir: string, pkg: MigrationPackage): Promise<void>;
/**
* Idempotent variant of {@link materialiseMigrationPackage}: writes the
* package only if `<targetDir>/<pkg.dirName>/` does not already exist on
* disk as a directory; returns `{ written: false }` when the package
* directory is present (no rewrite, no comparison — by-existence skip).
*
* Concretely:
* - existing directory → skip silently, return `{ written: false }`.
* - missing path → write three files via {@link materialiseMigrationPackage},
* return `{ written: true }`.
* - path exists but is not a directory (file/symlink) → treated as
* missing; {@link materialiseMigrationPackage} will attempt creation
* and fail with an appropriate OS error.
* - any other I/O error from `stat` → propagated unchanged.
*
* Used by the CLI's `runContractSpaceExtensionMigrationsPass` to
* materialise extension migration packages into a project's
* `migrations/<spaceId>/` directory, and by extension-package tests
* that mirror the same idempotent-rematerialise property locally
* without taking a CLI dependency.
*/
declare function materialiseExtensionMigrationPackageIfMissing(targetDir: string, pkg: MigrationPackage): Promise<{
readonly written: boolean;
}>;
/**
* Copy a list of files into `destDir`, optionally renaming each one.
*
* The destination directory is created (with `recursive: true`) if it
* does not already exist. Each source path is copied byte-for-byte into
* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is
* intentionally generic: callers own the list of files and the naming
* convention for the copies.
*/
declare function copyFilesWithRename(destDir: string, files: readonly {
readonly sourcePath: string;
readonly destName: string;
}[]): Promise<void>;
declare function writeMigrationMetadata(dir: string, metadata: MigrationMetadata): Promise<void>;
declare function writeMigrationOps(dir: string, ops: MigrationOps): Promise<void>;
declare function readMigrationPackage(dir: string, options: ReadMigrationPackageOptions): Promise<OnDiskMigrationPackage>;
/**
* A per-package load-time problem returned by {@link readMigrationsDir}.
*
* Three variants, matching the relocated throws from the load path:
*
* - `hashMismatch` — stored `migrationHash` differs from the recomputed value.
* The package is **retained** in the returned `packages` array.
* - `providedInvariantsMismatch` — `migration.json` declares different
* `providedInvariants` than `ops.json` implies. The package is **retained**.
* - `packageUnloadable` — the manifest is missing, unparseable, or schema-
* invalid. The package is **omitted** from `packages`.
*
* Callers that need the `spaceId` context (e.g. the aggregate loader) attach
* it when converting to {@link import('./integrity-violation').IntegrityViolation}.
*/
type PackageLoadProblem = {
readonly kind: 'hashMismatch';
readonly dirName: string;
readonly stored: string;
readonly computed: string;
} | {
readonly kind: 'providedInvariantsMismatch';
readonly dirName: string;
} | {
readonly kind: 'packageUnloadable';
readonly dirName: string;
readonly detail: string;
};
/**
* Result returned by {@link readMigrationsDir}.
*
* - `packages` — every package that could be read; hash-mismatched and
* invariants-mismatched packages are included here (the problem is
* represented rather than fatal).
* - `problems` — one entry per package that had a load-time issue.
* `packageUnloadable` entries are **not** in `packages`.
*/
interface ReadMigrationsDirResult {
readonly packages: readonly OnDiskMigrationPackage[];
readonly problems: readonly PackageLoadProblem[];
}
declare function readMigrationsDir(migrationsRoot: string, options: ReadMigrationPackageOptions): Promise<ReadMigrationsDirResult>;
declare function formatMigrationDirName(timestamp: Date, slug: string): string;
//#endregion
export { materialiseExtensionMigrationPackageIfMissing as a, readMigrationsDir as c, writeMigrationPackage as d, formatMigrationDirName as i, writeMigrationMetadata as l, ReadMigrationsDirResult as n, materialiseMigrationPackage as o, copyFilesWithRename as r, readMigrationPackage as s, PackageLoadProblem as t, writeMigrationOps as u };
//# sourceMappingURL=io-Bbn6RnRd.d.mts.map
{"version":3,"file":"io-Bbn6RnRd.d.mts","names":[],"sources":["../src/io.ts"],"mappings":";;;UA6BiB;WACN;;iBAgBW,sBACpB,aACA,UAAU,mBACV,KAAK,eACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDmB,4BACpB,mBACA,KAAK,mBACJ;;;;;;;;;;;;;;;;;;;;;;iBA2BmB,8CACpB,mBACA,KAAK,mBACJ;WAAmB;;;;;;;;;;;iBA2BA,oBACpB,iBACA;WAA2B;WAA6B;MACvD;iBAUmB,uBACpB,aACA,UAAU,oBACT;iBAImB,kBAAkB,aAAa,KAAK,eAAe;iBAInD,qBACpB,aACA,SAAS,8BACR,QAAQ;;;;;;;;;;;;;;;;KA8KC;WAEG;WACA;WACA;WACA;;WAEA;WAA6C;;WAC7C;WAAoC;WAA0B;;;;;;;;;;;UAW5D;WACN,mBAAmB;WACnB,mBAAmB;;iBASR,kBACpB,wBACA,SAAS,8BACR,QAAQ;iBAkEK,uBAAuB,WAAW,MAAM"}
import { C as errorMigrationHashMismatch, O as errorProvidedInvariantsMismatch, b as errorInvalidSlug, c as errorDirectoryExists, f as errorInvalidDestName, h as errorInvalidManifest, m as errorInvalidJson, t as MigrationToolsError, w as errorMissingFile } from "./errors-DldT38lZ.mjs";
import { i as readContractSnapshotJsonTolerant } from "./contract-snapshot-store-DCFUkXwL.mjs";
import { n as verifyMigrationHash } from "./hash-BNCgfhir.mjs";
import { t as deriveProvidedInvariants } from "./invariants-BcT9Izto.mjs";
import { n as MigrationOpsSchema } from "./op-schema-BSVHzEQN.mjs";
import { ifDefined } from "@prisma-next/utils/defined";
import { basename, dirname, join, resolve } from "pathe";
import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { type } from "arktype";
//#region src/io.ts
const MANIFEST_FILE = "migration.json";
const OPS_FILE = "ops.json";
const MAX_SLUG_LENGTH = 64;
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
const MigrationMetadataSchema = type({
"+": "reject",
from: "string > 0 | null",
to: "string",
migrationHash: "string",
providedInvariants: "string[]",
createdAt: "string"
});
async function writeMigrationPackage(dir, metadata, ops) {
await mkdir(dirname(dir), { recursive: true });
try {
await mkdir(dir);
} catch (error) {
if (hasErrnoCode(error, "EEXIST")) throw errorDirectoryExists(dir);
throw error;
}
await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(metadata, null, 2), { flag: "wx" });
await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: "wx" });
}
/**
* Materialise an in-memory {@link MigrationPackage} to a per-space
* directory on disk.
*
* Writes two files under `<targetDir>/<pkg.dirName>/`:
*
* - `migration.json` — the manifest (pretty-printed, matches
* {@link writeMigrationPackage}'s output for byte-for-byte parity with
* app-space migrations).
* - `ops.json` — the operation list (pretty-printed).
*
* Distinct verb from the lower-level {@link writeMigrationPackage}
* (which takes constituent `(metadata, ops)`): callers reading
* `materialise…` know they are persisting a struct-typed package.
*
* Overwrite-idempotent: the per-package directory is cleared before
* each emit, so re-running against the same `targetDir` produces
* byte-identical contents and never leaves stale files behind. The
* lower-level {@link writeMigrationPackage} stays strict because the
* CLI authoring path (`migration plan` / `migration new`) deliberately
* refuses to clobber an existing authored migration; this helper is
* the re-emit path that is supposed to converge on a single canonical
* on-disk shape.
*
* The per-space head contract resolves through
* `<projectMigrationsDir>/snapshots/<hex>/` (written by
* {@link import('./emit-contract-space-artifacts').emitContractSpaceArtifacts}),
* not inside the per-package directory. The runner reads only
* `migration.json` + `ops.json` from each package.
*/
async function materialiseMigrationPackage(targetDir, pkg) {
const dir = join(targetDir, pkg.dirName);
await rm(dir, {
recursive: true,
force: true
});
await writeMigrationPackage(dir, pkg.metadata, pkg.ops);
}
/**
* Idempotent variant of {@link materialiseMigrationPackage}: writes the
* package only if `<targetDir>/<pkg.dirName>/` does not already exist on
* disk as a directory; returns `{ written: false }` when the package
* directory is present (no rewrite, no comparison — by-existence skip).
*
* Concretely:
* - existing directory → skip silently, return `{ written: false }`.
* - missing path → write three files via {@link materialiseMigrationPackage},
* return `{ written: true }`.
* - path exists but is not a directory (file/symlink) → treated as
* missing; {@link materialiseMigrationPackage} will attempt creation
* and fail with an appropriate OS error.
* - any other I/O error from `stat` → propagated unchanged.
*
* Used by the CLI's `runContractSpaceExtensionMigrationsPass` to
* materialise extension migration packages into a project's
* `migrations/<spaceId>/` directory, and by extension-package tests
* that mirror the same idempotent-rematerialise property locally
* without taking a CLI dependency.
*/
async function materialiseExtensionMigrationPackageIfMissing(targetDir, pkg) {
if (await directoryExists(join(targetDir, pkg.dirName))) return { written: false };
await materialiseMigrationPackage(targetDir, pkg);
return { written: true };
}
async function directoryExists(p) {
try {
return (await stat(p)).isDirectory();
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return false;
throw error;
}
}
/**
* Copy a list of files into `destDir`, optionally renaming each one.
*
* The destination directory is created (with `recursive: true`) if it
* does not already exist. Each source path is copied byte-for-byte into
* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is
* intentionally generic: callers own the list of files and the naming
* convention for the copies.
*/
async function copyFilesWithRename(destDir, files) {
await mkdir(destDir, { recursive: true });
for (const file of files) {
if (basename(file.destName) !== file.destName) throw errorInvalidDestName(file.destName);
await copyFile(file.sourcePath, join(destDir, file.destName));
}
}
async function writeMigrationMetadata(dir, metadata) {
await writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(metadata, null, 2)}\n`);
}
async function writeMigrationOps(dir, ops) {
await writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\n`);
}
async function readMigrationPackage(dir, options) {
const absoluteDir = resolve(dir);
const manifestPath = join(absoluteDir, MANIFEST_FILE);
const opsPath = join(absoluteDir, OPS_FILE);
let manifestRaw;
try {
manifestRaw = await readFile(manifestPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile(MANIFEST_FILE, absoluteDir);
throw error;
}
let opsRaw;
try {
opsRaw = await readFile(opsPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile(OPS_FILE, absoluteDir);
throw error;
}
let metadata;
try {
metadata = JSON.parse(manifestRaw);
} catch (e) {
throw errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));
}
let ops;
try {
ops = JSON.parse(opsRaw);
} catch (e) {
throw errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));
}
validateMetadata(metadata, manifestPath);
validateOps(ops, opsPath);
const derivedInvariants = deriveProvidedInvariants(ops);
if (!arraysEqual(metadata.providedInvariants, derivedInvariants)) throw errorProvidedInvariantsMismatch(manifestPath, metadata.providedInvariants, derivedInvariants);
const endContractJson = await readContractSnapshotJsonTolerant(options.migrationsDir, metadata.to);
const pkg = {
dirName: basename(absoluteDir),
dirPath: absoluteDir,
metadata,
ops,
...ifDefined("endContractJson", endContractJson)
};
const verification = verifyMigrationHash(pkg);
if (!verification.ok) throw errorMigrationHashMismatch(absoluteDir, verification.storedHash, verification.computedHash);
return pkg;
}
/**
* Reads a migration package's manifest and ops without running hash or
* invariants verification. Returns `null` when the files cannot be read or
* parsed (i.e. when the package is genuinely unloadable).
*
* Used by {@link readMigrationsDir} to retain a package whose hash or
* invariants diverge from what is stored on disk — the raw content is still
* useful for display / querying; only integrity is in question.
*/
async function readMigrationPackageRaw(dir) {
const absoluteDir = resolve(dir);
const manifestPath = join(absoluteDir, MANIFEST_FILE);
const opsPath = join(absoluteDir, OPS_FILE);
let manifestRaw;
try {
manifestRaw = await readFile(manifestPath, "utf-8");
} catch {
return null;
}
let opsRaw;
try {
opsRaw = await readFile(opsPath, "utf-8");
} catch {
return null;
}
let metadata;
try {
metadata = JSON.parse(manifestRaw);
} catch {
return null;
}
let ops;
try {
ops = JSON.parse(opsRaw);
} catch {
return null;
}
if (MigrationMetadataSchema(metadata) instanceof type.errors) return null;
if (MigrationOpsSchema(ops) instanceof type.errors) return null;
return {
dirName: basename(absoluteDir),
dirPath: absoluteDir,
metadata,
ops
};
}
function arraysEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
function validateMetadata(metadata, filePath) {
const result = MigrationMetadataSchema(metadata);
if (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);
}
function validateOps(ops, filePath) {
const result = MigrationOpsSchema(ops);
if (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);
}
function packageLoadProblemDetailFromError(error) {
if (MigrationToolsError.is(error)) return error.why;
if (error instanceof Error) return error.message;
return String(error);
}
async function readMigrationsDir(migrationsRoot, options) {
let entries;
try {
entries = await readdir(migrationsRoot);
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return {
packages: [],
problems: []
};
throw error;
}
const packages = [];
const problems = [];
for (const entry of entries.sort()) {
const entryPath = join(migrationsRoot, entry);
if (!(await stat(entryPath)).isDirectory()) continue;
const manifestPath = join(entryPath, MANIFEST_FILE);
try {
await stat(manifestPath);
} catch {
continue;
}
let pkg;
try {
pkg = await readMigrationPackage(entryPath, options);
} catch (error) {
const dirName = entry;
if (MigrationToolsError.is(error)) {
if (error.code === "MIGRATION.HASH_MISMATCH") {
const details = error.details;
const rawPkg = await readMigrationPackageRaw(entryPath);
if (rawPkg !== null) packages.push(rawPkg);
problems.push({
kind: "hashMismatch",
dirName,
stored: typeof details?.["storedHash"] === "string" ? details["storedHash"] : "",
computed: typeof details?.["computedHash"] === "string" ? details["computedHash"] : ""
});
continue;
}
if (error.code === "MIGRATION.PROVIDED_INVARIANTS_MISMATCH") {
const rawPkg = await readMigrationPackageRaw(entryPath);
if (rawPkg !== null) packages.push(rawPkg);
problems.push({
kind: "providedInvariantsMismatch",
dirName
});
continue;
}
}
problems.push({
kind: "packageUnloadable",
dirName,
detail: packageLoadProblemDetailFromError(error)
});
continue;
}
packages.push(pkg);
}
return {
packages,
problems
};
}
function formatMigrationDirName(timestamp, slug) {
const sanitized = slug.toLowerCase().replace(/[^a-z0-9]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
if (sanitized.length === 0) throw errorInvalidSlug(slug);
const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);
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}`;
}
//#endregion
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 };
//# sourceMappingURL=io-H4a-OJHL.mjs.map
{"version":3,"file":"io-H4a-OJHL.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 { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\nimport { basename, dirname, join, resolve } from 'pathe';\nimport { readContractSnapshotJsonTolerant } from './contract-snapshot-store';\nimport {\n errorDirectoryExists,\n errorInvalidDestName,\n errorInvalidJson,\n errorInvalidManifest,\n errorInvalidSlug,\n errorMigrationHashMismatch,\n errorMissingFile,\n errorProvidedInvariantsMismatch,\n MigrationToolsError,\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\nexport interface ReadMigrationPackageOptions {\n readonly migrationsDir: string;\n}\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\nconst MigrationMetadataSchema = type({\n '+': 'reject',\n from: 'string > 0 | null',\n to: 'string',\n migrationHash: 'string',\n providedInvariants: 'string[]',\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 two 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 *\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 *\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 * lower-level {@link writeMigrationPackage} stays strict because the\n * CLI authoring path (`migration plan` / `migration new`) deliberately\n * refuses to clobber an existing authored migration; this helper is\n * the re-emit path that is supposed to converge on a single canonical\n * on-disk shape.\n *\n * The per-space head contract resolves through\n * `<projectMigrationsDir>/snapshots/<hex>/` (written by\n * {@link import('./emit-contract-space-artifacts').emitContractSpaceArtifacts}),\n * not inside the per-package directory. The runner reads only\n * `migration.json` + `ops.json` from each package.\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}\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 and the naming\n * convention for the copies.\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(\n dir: string,\n options: ReadMigrationPackageOptions,\n): 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 endContractJson = await readContractSnapshotJsonTolerant(\n options.migrationsDir,\n metadata.to,\n );\n const pkg: OnDiskMigrationPackage = {\n dirName: basename(absoluteDir),\n dirPath: absoluteDir,\n metadata,\n ops,\n ...ifDefined('endContractJson', endContractJson),\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\n/**\n * Reads a migration package's manifest and ops without running hash or\n * invariants verification. Returns `null` when the files cannot be read or\n * parsed (i.e. when the package is genuinely unloadable).\n *\n * Used by {@link readMigrationsDir} to retain a package whose hash or\n * invariants diverge from what is stored on disk — the raw content is still\n * useful for display / querying; only integrity is in question.\n */\nasync function readMigrationPackageRaw(dir: string): Promise<OnDiskMigrationPackage | null> {\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 {\n return null;\n }\n let opsRaw: string;\n try {\n opsRaw = await readFile(opsPath, 'utf-8');\n } catch {\n return null;\n }\n\n let metadata: MigrationMetadata;\n try {\n metadata = JSON.parse(manifestRaw);\n } catch {\n return null;\n }\n let ops: MigrationOps;\n try {\n ops = JSON.parse(opsRaw);\n } catch {\n return null;\n }\n\n const result = MigrationMetadataSchema(metadata);\n if (result instanceof type.errors) return null;\n\n const opsResult = MigrationOpsSchema(ops);\n if (opsResult instanceof type.errors) return null;\n\n // Deliberately no `endContractJson`: this loader only runs for packages\n // that failed hash / invariants verification, and a snapshot from an\n // unverifiable package must never reach the ledger's contract store.\n return {\n dirName: basename(absoluteDir),\n dirPath: absoluteDir,\n metadata,\n ops,\n };\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\n/**\n * A per-package load-time problem returned by {@link readMigrationsDir}.\n *\n * Three variants, matching the relocated throws from the load path:\n *\n * - `hashMismatch` — stored `migrationHash` differs from the recomputed value.\n * The package is **retained** in the returned `packages` array.\n * - `providedInvariantsMismatch` — `migration.json` declares different\n * `providedInvariants` than `ops.json` implies. The package is **retained**.\n * - `packageUnloadable` — the manifest is missing, unparseable, or schema-\n * invalid. The package is **omitted** from `packages`.\n *\n * Callers that need the `spaceId` context (e.g. the aggregate loader) attach\n * it when converting to {@link import('./integrity-violation').IntegrityViolation}.\n */\nexport type PackageLoadProblem =\n | {\n readonly kind: 'hashMismatch';\n readonly dirName: string;\n readonly stored: string;\n readonly computed: string;\n }\n | { readonly kind: 'providedInvariantsMismatch'; readonly dirName: string }\n | { readonly kind: 'packageUnloadable'; readonly dirName: string; readonly detail: string };\n\n/**\n * Result returned by {@link readMigrationsDir}.\n *\n * - `packages` — every package that could be read; hash-mismatched and\n * invariants-mismatched packages are included here (the problem is\n * represented rather than fatal).\n * - `problems` — one entry per package that had a load-time issue.\n * `packageUnloadable` entries are **not** in `packages`.\n */\nexport interface ReadMigrationsDirResult {\n readonly packages: readonly OnDiskMigrationPackage[];\n readonly problems: readonly PackageLoadProblem[];\n}\n\nfunction packageLoadProblemDetailFromError(error: unknown): string {\n if (MigrationToolsError.is(error)) return error.why;\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nexport async function readMigrationsDir(\n migrationsRoot: string,\n options: ReadMigrationPackageOptions,\n): Promise<ReadMigrationsDirResult> {\n let entries: string[];\n try {\n entries = await readdir(migrationsRoot);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return { packages: [], problems: [] };\n }\n throw error;\n }\n\n const packages: OnDiskMigrationPackage[] = [];\n const problems: PackageLoadProblem[] = [];\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 let pkg: OnDiskMigrationPackage;\n try {\n pkg = await readMigrationPackage(entryPath, options);\n } catch (error) {\n const dirName = entry;\n if (MigrationToolsError.is(error)) {\n if (error.code === 'MIGRATION.HASH_MISMATCH') {\n const details = error.details;\n const rawPkg = await readMigrationPackageRaw(entryPath);\n if (rawPkg !== null) packages.push(rawPkg);\n problems.push({\n kind: 'hashMismatch',\n dirName,\n stored: typeof details?.['storedHash'] === 'string' ? details['storedHash'] : '',\n computed: typeof details?.['computedHash'] === 'string' ? details['computedHash'] : '',\n });\n continue;\n }\n if (error.code === 'MIGRATION.PROVIDED_INVARIANTS_MISMATCH') {\n const rawPkg = await readMigrationPackageRaw(entryPath);\n if (rawPkg !== null) packages.push(rawPkg);\n problems.push({ kind: 'providedInvariantsMismatch', dirName });\n continue;\n }\n }\n // Any other error (missing file, invalid JSON, invalid manifest schema) →\n // package unloadable; omit from packages.\n problems.push({\n kind: 'packageUnloadable',\n dirName,\n detail: packageLoadProblemDetailFromError(error),\n });\n continue;\n }\n packages.push(pkg);\n }\n\n return { packages, problems };\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":";;;;;;;;;;AAyBA,MAAa,gBAAgB;AAC7B,MAAM,WAAW;AACjB,MAAM,kBAAkB;AAMxB,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;AAEA,MAAM,0BAA0B,KAAK;CACnC,KAAK;CACL,MAAM;CACN,IAAI;CACJ,eAAe;CACf,oBAAoB;CACpB,WAAW;AACb,CAAC;AAED,eAAsB,sBACpB,KACA,UACA,KACe;CACf,MAAM,MAAM,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAE7C,IAAI;EACF,MAAM,MAAM,GAAG;CACjB,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAC9B,MAAM,qBAAqB,GAAG;EAEhC,MAAM;CACR;CAEA,MAAM,UAAU,KAAK,KAAK,aAAa,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,GAAG,EAC3E,MAAM,KACR,CAAC;CACD,MAAM,UAAU,KAAK,KAAK,QA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O;EAAE;EAAU;CAAS;AAC9B;AAEA,SAAgB,uBAAuB,WAAiB,MAAsB;CAC5E,MAAM,YAAY,KACf,YAAY,CAAC,CACb,QAAQ,cAAc,GAAG,CAAC,CAC1B,QAAQ,OAAO,GAAG,CAAC,CACnB,QAAQ,UAAU,EAAE;CAEvB,IAAI,UAAU,WAAW,GACvB,MAAM,iBAAiB,IAAI;CAG7B,MAAM,YAAY,UAAU,MAAM,GAAG,eAAe;CAQpD,OAAO,GANG,UAAU,eAMV,IALC,OAAO,UAAU,YAAY,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAK5C,IAJL,OAAO,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG,GAIlC,EAAE,GAHX,OAAO,UAAU,YAAY,CAAC,CAAC,CAAC,SAAS,GAAG,GAG9B,IAFb,OAAO,UAAU,cAAc,CAAC,CAAC,CAAC,SAAS,GAAG,GAE5B,EAAE,GAAG;AACpC"}
import { D as errorNoTarget, T as errorNoInitialMigration, n as errorAmbiguousTarget } from "./errors-DldT38lZ.mjs";
import { t as EMPTY_CONTRACT_HASH } from "./constants-YnG8_EGO.mjs";
import { ifDefined } from "@prisma-next/utils/defined";
//#region src/queue.ts
/**
* FIFO queue with amortised O(1) push and shift.
*
* Uses a head-index cursor over a backing array rather than
* `Array.prototype.shift()`, which is O(n) on V8. Intended for BFS-shaped
* traversals where the queue is drained in a single pass — it does not
* reclaim memory for already-shifted items, so it is not suitable for
* long-lived queues with many push/shift cycles.
*/
var Queue = class {
items;
head = 0;
constructor(initial = []) {
this.items = [...initial];
}
push(item) {
this.items.push(item);
}
/**
* Remove and return the next item. Caller must check `isEmpty` first —
* shifting an empty queue throws.
*/
shift() {
if (this.head >= this.items.length) throw new Error("Queue.shift called on empty queue");
return this.items[this.head++];
}
get isEmpty() {
return this.head >= this.items.length;
}
};
//#endregion
//#region src/graph-ops.ts
function* bfs(starts, neighbours, key = (state) => state) {
const visited = /* @__PURE__ */ new Set();
const parentMap = /* @__PURE__ */ new Map();
const queue = new Queue();
for (const start of starts) {
const k = key(start);
if (!visited.has(k)) {
visited.add(k);
queue.push({
state: start,
key: k
});
}
}
while (!queue.isEmpty) {
const { state: current, key: curKey } = queue.shift();
const parentInfo = parentMap.get(curKey);
yield {
state: current,
parent: parentInfo?.parent ?? null,
incomingEdge: parentInfo?.edge ?? null
};
for (const { next, edge } of neighbours(current)) {
const k = key(next);
if (!visited.has(k)) {
visited.add(k);
parentMap.set(k, {
parent: current,
edge
});
queue.push({
state: next,
key: k
});
}
}
}
}
//#endregion
//#region src/migration-graph.ts
/** Forward-edge neighbours: edge `e` from `n` visits `e.to` next. */
function forwardNeighbours(graph, node) {
return (graph.forwardChain.get(node) ?? []).map((edge) => ({
next: edge.to,
edge
}));
}
/**
* Forward-edge neighbours, sorted by the deterministic tie-break.
* Used by path-finding so the resulting shortest path is stable across runs.
*/
function sortedForwardNeighbours(graph, node) {
return [...graph.forwardChain.get(node) ?? []].sort(compareTieBreak).map((edge) => ({
next: edge.to,
edge
}));
}
/** Reverse-edge neighbours: edge `e` from `n` visits `e.from` next. */
function reverseNeighbours(graph, node) {
return (graph.reverseChain.get(node) ?? []).map((edge) => ({
next: edge.from,
edge
}));
}
function appendEdge(map, key, entry) {
const bucket = map.get(key);
if (bucket) bucket.push(entry);
else map.set(key, [entry]);
}
function reconstructGraph(packages) {
const nodes = /* @__PURE__ */ new Set();
const forwardChain = /* @__PURE__ */ new Map();
const reverseChain = /* @__PURE__ */ new Map();
const migrationByHash = /* @__PURE__ */ new Map();
for (const pkg of packages) {
const from = pkg.metadata.from ?? "sha256:empty";
const { to } = pkg.metadata;
nodes.add(from);
nodes.add(to);
const migration = {
from,
to,
migrationHash: pkg.metadata.migrationHash,
dirName: pkg.dirName,
createdAt: pkg.metadata.createdAt,
invariants: pkg.metadata.providedInvariants
};
if (!migrationByHash.has(migration.migrationHash)) migrationByHash.set(migration.migrationHash, migration);
appendEdge(forwardChain, from, migration);
appendEdge(reverseChain, to, migration);
}
return {
nodes,
forwardChain,
reverseChain,
migrationByHash
};
}
function compareTieBreak(a, b) {
const ca = a.createdAt.localeCompare(b.createdAt);
if (ca !== 0) return ca;
const tc = a.to.localeCompare(b.to);
if (tc !== 0) return tc;
return a.migrationHash.localeCompare(b.migrationHash);
}
function sortedNeighbors(edges) {
return [...edges].sort(compareTieBreak);
}
/**
* Find the shortest path from `fromHash` to `toHash` using BFS over the
* contract-hash graph. Returns the ordered list of edges, or null if no path
* exists. Returns an empty array when `fromHash === toHash` (no-op).
*
* Neighbor ordering is deterministic via the tie-break sort key:
* createdAt → to → migrationHash.
*/
function findPath(graph, fromHash, toHash) {
if (fromHash === toHash) return [];
const parents = /* @__PURE__ */ new Map();
for (const step of bfs([fromHash], (n) => sortedForwardNeighbours(graph, n))) {
if (step.parent !== null && step.incomingEdge !== null) parents.set(step.state, {
parent: step.parent,
edge: step.incomingEdge
});
if (step.state === toHash) {
const path = [];
let cur = toHash;
let p = parents.get(cur);
while (p) {
path.push(p.edge);
cur = p.parent;
p = parents.get(cur);
}
path.reverse();
return path;
}
}
return null;
}
/**
* Find the shortest path from `fromHash` to `toHash` whose edges collectively
* cover every invariant in `required`. Returns `null` when no such path exists
* (either `fromHash`→`toHash` is structurally unreachable, or every reachable
* path leaves at least one required invariant uncovered). When `required` is
* empty, delegates to `findPath` so the result is byte-identical for that case.
*
* Algorithm: BFS over `(node, coveredSubset)` states with state-level dedup.
* The covered subset is a `Set<string>` of invariant ids; the state's dedup
* key is `${node}\0${[...covered].sort().join('\0')}`. State keys distinguish
* distinct `(node, covered)` tuples regardless of node-name length because
* `\0` cannot appear in any invariant id (validation rejects whitespace and
* control chars at authoring time).
*
* Neighbour ordering when `required ≠ ∅`: edges covering ≥1 still-needed
* invariant come first, with `createdAt → to → migrationHash` as the
* secondary key. The heuristic steers BFS toward the satisfying path;
* correctness (shortest, deterministic) does not depend on it.
*/
function findPathWithInvariants(graph, fromHash, toHash, required) {
if (required.size === 0) return findPath(graph, fromHash, toHash);
const stateKey = (s) => {
if (s.covered.size === 0) return `${s.node}\0`;
return `${s.node}\0${[...s.covered].sort().join("\0")}`;
};
const neighbours = (s) => {
const outgoing = graph.forwardChain.get(s.node) ?? [];
if (outgoing.length === 0) return [];
return [...outgoing].map((edge) => {
let useful = false;
let next = null;
for (const inv of edge.invariants) if (required.has(inv) && !s.covered.has(inv)) {
if (next === null) next = new Set(s.covered);
next.add(inv);
useful = true;
}
return {
edge,
useful,
nextCovered: next ?? s.covered
};
}).sort((a, b) => {
if (a.useful !== b.useful) return a.useful ? -1 : 1;
return compareTieBreak(a.edge, b.edge);
}).map(({ edge, nextCovered }) => ({
next: {
node: edge.to,
covered: nextCovered
},
edge
}));
};
const parents = /* @__PURE__ */ new Map();
for (const step of bfs([{
node: fromHash,
covered: /* @__PURE__ */ new Set()
}], neighbours, stateKey)) {
const curKey = stateKey(step.state);
if (step.parent !== null && step.incomingEdge !== null) parents.set(curKey, {
parentKey: stateKey(step.parent),
edge: step.incomingEdge
});
if (step.state.node === toHash && step.state.covered.size === required.size) {
const path = [];
let cur = curKey;
while (cur !== void 0) {
const p = parents.get(cur);
if (!p) break;
path.push(p.edge);
cur = p.parentKey;
}
path.reverse();
return path;
}
}
return null;
}
/**
* Reverse-BFS from `toHash` over `reverseChain` to collect every node from
* which `toHash` is reachable (inclusive of `toHash` itself).
*/
function collectNodesReachingTarget(graph, toHash) {
const reached = /* @__PURE__ */ new Set();
for (const step of bfs([toHash], (n) => reverseNeighbours(graph, n))) reached.add(step.state);
return reached;
}
/**
* Find the shortest path from `fromHash` to `toHash` and return structured
* path-decision metadata for machine-readable output. When `required` is
* non-empty, the returned path is the shortest one whose edges collectively
* cover every required invariant.
*
* The discriminated return type tells the caller *why* a path could not be
* found, so the CLI can pick the right structured error without re-running
* a structural BFS.
*/
function findPathWithDecision(graph, fromHash, toHash, options = {}) {
const { refName, required = /* @__PURE__ */ new Set() } = options;
const requiredInvariants = [...required].sort();
if (fromHash === toHash && required.size === 0) return {
kind: "ok",
decision: {
selectedPath: [],
fromHash,
toHash,
alternativeCount: 0,
tieBreakReasons: [],
requiredInvariants,
satisfiedInvariants: [],
...ifDefined("refName", refName)
}
};
const path = findPathWithInvariants(graph, fromHash, toHash, required);
if (!path) {
if (required.size === 0) return { kind: "unreachable" };
const structural = findPath(graph, fromHash, toHash);
if (structural === null) return { kind: "unreachable" };
const coveredByStructural = /* @__PURE__ */ new Set();
for (const edge of structural) for (const inv of edge.invariants) if (required.has(inv)) coveredByStructural.add(inv);
return {
kind: "unsatisfiable",
structuralPath: structural,
missing: requiredInvariants.filter((id) => !coveredByStructural.has(id))
};
}
const satisfiedInvariants = computeSatisfiedInvariants(required, path);
const reachesTarget = collectNodesReachingTarget(graph, toHash);
const coveragePrefixes = requiredCoveragePrefixes(required, path);
const tieBreakReasons = [];
let alternativeCount = 0;
for (const [i, edge] of path.entries()) {
const outgoing = graph.forwardChain.get(edge.from);
if (!outgoing || outgoing.length <= 1) continue;
const reachable = outgoing.filter((e) => reachesTarget.has(e.to));
if (reachable.length <= 1) continue;
let comparisonPool = reachable;
if (required.size > 0) {
const prefixSet = coveragePrefixes[i];
if (prefixSet === void 0) continue;
comparisonPool = invariantViableAlternativesAtStep(required, prefixSet, reachable);
}
alternativeCount += reachable.length - 1;
if (sortedNeighbors(reachable)[0]?.migrationHash !== edge.migrationHash) continue;
if (!reachable.some((e) => e.migrationHash !== edge.migrationHash)) continue;
const sortedViable = sortedNeighbors(comparisonPool);
if (sortedViable.length > 1 && sortedViable[0]?.migrationHash === edge.migrationHash && sortedViable.some((e) => e.migrationHash !== edge.migrationHash)) tieBreakReasons.push(`at ${edge.from}: ${comparisonPool.length} candidates, selected by tie-break`);
}
return {
kind: "ok",
decision: {
selectedPath: path,
fromHash,
toHash,
alternativeCount,
tieBreakReasons,
requiredInvariants,
satisfiedInvariants,
...ifDefined("refName", refName)
}
};
}
function computeSatisfiedInvariants(required, path) {
if (required.size === 0) return [];
const covered = /* @__PURE__ */ new Set();
for (const edge of path) for (const inv of edge.invariants) if (required.has(inv)) covered.add(inv);
return [...covered].sort();
}
/**
* For each edge on path, invariant coverage accumulated from earlier edges only —
* `(required ∩ ∪_{j<i} path[j].invariants)` represented as cumulative set along `required`,
* keyed as "full set of required ids satisfied before taking path[i]".
*/
function requiredCoveragePrefixes(required, path) {
const prefixes = [];
const acc = /* @__PURE__ */ new Set();
for (const edge of path) {
prefixes.push(new Set(acc));
for (const inv of edge.invariants) if (required.has(inv)) acc.add(inv);
}
return prefixes;
}
function invariantViableAlternativesAtStep(required, coverageBeforeTakingEdge, outgoing) {
if (required.size === 0) return [...outgoing];
return outgoing.filter((e) => [...required].every((id) => coverageBeforeTakingEdge.has(id) || e.invariants.includes(id)));
}
/**
* Walk ancestors of each branch tip back to find the last node
* that appears on all paths. Returns `fromHash` if no shared ancestor is found.
*/
function findDivergencePoint(graph, fromHash, leaves) {
const ancestorSets = leaves.map((leaf) => {
const ancestors = /* @__PURE__ */ new Set();
for (const step of bfs([leaf], (n) => reverseNeighbours(graph, n))) ancestors.add(step.state);
return ancestors;
});
const commonAncestors = [...ancestorSets[0] ?? []].filter((node) => ancestorSets.every((s) => s.has(node)));
let deepest = fromHash;
let deepestDepth = -1;
for (const ancestor of commonAncestors) {
const path = findPath(graph, fromHash, ancestor);
const depth = path ? path.length : 0;
if (depth > deepestDepth) {
deepestDepth = depth;
deepest = ancestor;
}
}
return deepest;
}
/**
* Find all branch tips (nodes with no outgoing edges) reachable from
* `fromHash` via forward edges.
*/
function findReachableLeaves(graph, fromHash) {
const leaves = [];
for (const step of bfs([fromHash], (n) => forwardNeighbours(graph, n))) if (!graph.forwardChain.get(step.state)?.length) leaves.push(step.state);
return leaves;
}
/**
* Find the target contract hash of the migration graph reachable from
* EMPTY_CONTRACT_HASH. Returns `null` for a graph that has no target
* state (either empty, or containing only the root with no outgoing
* edges). Throws NO_INITIAL_MIGRATION if the graph has nodes but none
* originate from the empty hash, and AMBIGUOUS_TARGET if multiple
* branch tips exist.
*/
function findLeaf(graph) {
if (graph.nodes.size === 0) return null;
if (!graph.nodes.has("sha256:empty")) throw errorNoInitialMigration([...graph.nodes]);
const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);
if (leaves.length === 0) {
const reachable = [...graph.nodes].filter((n) => n !== EMPTY_CONTRACT_HASH);
if (reachable.length > 0) throw errorNoTarget(reachable);
return null;
}
if (leaves.length > 1) {
const divergencePoint = findDivergencePoint(graph, EMPTY_CONTRACT_HASH, leaves);
throw errorAmbiguousTarget(leaves, {
divergencePoint,
branches: leaves.map((tip) => {
return {
tip,
edges: (findPath(graph, divergencePoint, tip) ?? []).map((e) => ({
dirName: e.dirName,
from: e.from,
to: e.to
}))
};
})
});
}
return leaves[0];
}
/**
* Find the latest migration entry by traversing from EMPTY_CONTRACT_HASH
* to the single target. Returns null for an empty graph.
* Throws AMBIGUOUS_TARGET if the graph has multiple branch tips.
*/
function findLatestMigration(graph) {
const leafHash = findLeaf(graph);
if (leafHash === null) return null;
return findPath(graph, "sha256:empty", leafHash)?.at(-1) ?? null;
}
function detectCycles(graph) {
const WHITE = 0;
const GRAY = 1;
const BLACK = 2;
const color = /* @__PURE__ */ new Map();
const parentMap = /* @__PURE__ */ new Map();
const cycles = [];
for (const node of graph.nodes) color.set(node, WHITE);
const stack = [];
function pushFrame(u) {
color.set(u, GRAY);
stack.push({
node: u,
outgoing: graph.forwardChain.get(u) ?? [],
index: 0
});
}
for (const root of graph.nodes) {
if (color.get(root) !== WHITE) continue;
parentMap.set(root, null);
pushFrame(root);
while (stack.length > 0) {
const frame = stack[stack.length - 1];
if (frame.index >= frame.outgoing.length) {
color.set(frame.node, BLACK);
stack.pop();
continue;
}
const v = frame.outgoing[frame.index++].to;
const vColor = color.get(v);
if (vColor === GRAY) {
const cycle = [v];
let cur = frame.node;
while (cur !== v) {
cycle.push(cur);
cur = parentMap.get(cur) ?? v;
}
cycle.reverse();
cycles.push(cycle);
} else if (vColor === WHITE) {
parentMap.set(v, frame.node);
pushFrame(v);
}
}
}
return cycles;
}
function detectOrphans(graph) {
if (graph.nodes.size === 0) return [];
const reachable = /* @__PURE__ */ new Set();
const startNodes = [];
if (graph.forwardChain.has("sha256:empty")) startNodes.push(EMPTY_CONTRACT_HASH);
else {
const allTargets = /* @__PURE__ */ new Set();
for (const edges of graph.forwardChain.values()) for (const edge of edges) allTargets.add(edge.to);
for (const node of graph.nodes) if (!allTargets.has(node)) startNodes.push(node);
}
for (const step of bfs(startNodes, (n) => forwardNeighbours(graph, n))) reachable.add(step.state);
const orphans = [];
for (const [from, migrations] of graph.forwardChain) if (!reachable.has(from)) orphans.push(...migrations);
return orphans;
}
//#endregion
export { findPath as a, findReachableLeaves as c, findLeaf as i, reconstructGraph as l, detectOrphans as n, findPathWithDecision as o, findLatestMigration as r, findPathWithInvariants as s, detectCycles as t };
//# sourceMappingURL=migration-graph-k8O6g9j2.mjs.map
{"version":3,"file":"migration-graph-k8O6g9j2.mjs","names":[],"sources":["../src/queue.ts","../src/graph-ops.ts","../src/migration-graph.ts"],"sourcesContent":["/**\n * FIFO queue with amortised O(1) push and shift.\n *\n * Uses a head-index cursor over a backing array rather than\n * `Array.prototype.shift()`, which is O(n) on V8. Intended for BFS-shaped\n * traversals where the queue is drained in a single pass — it does not\n * reclaim memory for already-shifted items, so it is not suitable for\n * long-lived queues with many push/shift cycles.\n */\nexport class Queue<T> {\n private readonly items: T[];\n private head = 0;\n\n constructor(initial: Iterable<T> = []) {\n this.items = [...initial];\n }\n\n push(item: T): void {\n this.items.push(item);\n }\n\n /**\n * Remove and return the next item. Caller must check `isEmpty` first —\n * shifting an empty queue throws.\n */\n shift(): T {\n if (this.head >= this.items.length) {\n throw new Error('Queue.shift called on empty queue');\n }\n // biome-ignore lint/style/noNonNullAssertion: bounds-checked on the line above\n return this.items[this.head++]!;\n }\n\n get isEmpty(): boolean {\n return this.head >= this.items.length;\n }\n}\n","import { Queue } from './queue';\n\n/**\n * One step of a BFS traversal.\n *\n * `parent` and `incomingEdge` are `null` for start states — they were not\n * reached via any edge. For every other state they record the predecessor\n * state and the edge by which this state was first reached.\n *\n * `state` is the BFS state, most often a string (graph node identifier) but\n * can be a composite object. The string overload keeps the common case\n * ergonomic; the generic overload accepts a caller-supplied `key` function\n * that produces a stable equality key for dedup.\n */\nexport interface BfsStep<S, E> {\n readonly state: S;\n readonly parent: S | null;\n readonly incomingEdge: E | null;\n}\n\n/**\n * Generic breadth-first traversal.\n *\n * Direction (forward/reverse) is expressed by the caller's `neighbours`\n * closure: return `{ next, edge }` pairs where `next` is the state to visit\n * next and `edge` is the edge that connects them. Callers that don't need\n * path reconstruction can ignore the `parent`/`incomingEdge` fields of each\n * yielded step.\n *\n * Ordering — when the result needs to be deterministic (path-finding) the\n * caller is responsible for sorting inside `neighbours`; this generator\n * does not impose an ordering hook of its own. State-dependent orderings\n * have full access to the source state inside the closure.\n *\n * Stops are intrinsic — callers `break` out of the `for..of` loop when\n * they've found what they're looking for.\n */\nexport function bfs<E>(\n starts: Iterable<string>,\n neighbours: (state: string) => Iterable<{ next: string; edge: E }>,\n): Generator<BfsStep<string, E>>;\nexport function bfs<S, E>(\n starts: Iterable<S>,\n neighbours: (state: S) => Iterable<{ next: S; edge: E }>,\n key: (state: S) => string,\n): Generator<BfsStep<S, E>>;\nexport function* bfs<S, E>(\n starts: Iterable<S>,\n neighbours: (state: S) => Iterable<{ next: S; edge: E }>,\n // Identity default for the string overload. TypeScript can't express\n // \"default applies only when S = string\", so this cast bridges the\n // generic implementation signature to the public overloads — which\n // guarantee `key` is omitted only when S = string at the call site.\n key: (state: S) => string = (state) => state as unknown as string,\n): Generator<BfsStep<S, E>> {\n // Queue entries carry the state alongside its key so we don't recompute\n // key() twice per visit (once on dedup, once on parent lookup). Composite\n // keys can be non-trivial to compute; string-overload callers pay nothing\n // since key() is identity there.\n interface Entry {\n readonly state: S;\n readonly key: string;\n }\n const visited = new Set<string>();\n const parentMap = new Map<string, { parent: S; edge: E }>();\n const queue = new Queue<Entry>();\n for (const start of starts) {\n const k = key(start);\n if (!visited.has(k)) {\n visited.add(k);\n queue.push({ state: start, key: k });\n }\n }\n while (!queue.isEmpty) {\n const { state: current, key: curKey } = queue.shift();\n const parentInfo = parentMap.get(curKey);\n yield {\n state: current,\n parent: parentInfo?.parent ?? null,\n incomingEdge: parentInfo?.edge ?? null,\n };\n\n for (const { next, edge } of neighbours(current)) {\n const k = key(next);\n if (!visited.has(k)) {\n visited.add(k);\n parentMap.set(k, { parent: current, edge });\n queue.push({ state: next, key: k });\n }\n }\n }\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\nimport { EMPTY_CONTRACT_HASH } from './constants';\nimport { errorAmbiguousTarget, errorNoInitialMigration, errorNoTarget } from './errors';\nimport type { MigrationEdge, MigrationGraph } from './graph';\nimport { bfs } from './graph-ops';\nimport type { OnDiskMigrationPackage } from './package';\n\n/** Forward-edge neighbours: edge `e` from `n` visits `e.to` next. */\nfunction forwardNeighbours(graph: MigrationGraph, node: string) {\n return (graph.forwardChain.get(node) ?? []).map((edge) => ({ next: edge.to, edge }));\n}\n\n/**\n * Forward-edge neighbours, sorted by the deterministic tie-break.\n * Used by path-finding so the resulting shortest path is stable across runs.\n */\nfunction sortedForwardNeighbours(graph: MigrationGraph, node: string) {\n const edges = graph.forwardChain.get(node) ?? [];\n return [...edges].sort(compareTieBreak).map((edge) => ({ next: edge.to, edge }));\n}\n\n/** Reverse-edge neighbours: edge `e` from `n` visits `e.from` next. */\nfunction reverseNeighbours(graph: MigrationGraph, node: string) {\n return (graph.reverseChain.get(node) ?? []).map((edge) => ({ next: edge.from, edge }));\n}\n\nfunction appendEdge(map: Map<string, MigrationEdge[]>, key: string, entry: MigrationEdge): void {\n const bucket = map.get(key);\n if (bucket) bucket.push(entry);\n else map.set(key, [entry]);\n}\n\nexport function reconstructGraph(packages: readonly OnDiskMigrationPackage[]): MigrationGraph {\n const nodes = new Set<string>();\n const forwardChain = new Map<string, MigrationEdge[]>();\n const reverseChain = new Map<string, MigrationEdge[]>();\n const migrationByHash = new Map<string, MigrationEdge>();\n\n for (const pkg of packages) {\n // Manifest `from` is `string | null` (null = baseline). The graph layer\n // is the marker/path layer where \"no prior state\" is encoded as the\n // EMPTY_CONTRACT_HASH sentinel; bridge here so pathfinding stays string-\n // keyed.\n const from = pkg.metadata.from ?? EMPTY_CONTRACT_HASH;\n const { to } = pkg.metadata;\n\n nodes.add(from);\n nodes.add(to);\n\n const migration: MigrationEdge = {\n from,\n to,\n migrationHash: pkg.metadata.migrationHash,\n dirName: pkg.dirName,\n createdAt: pkg.metadata.createdAt,\n invariants: pkg.metadata.providedInvariants,\n };\n\n if (!migrationByHash.has(migration.migrationHash)) {\n migrationByHash.set(migration.migrationHash, migration);\n }\n\n appendEdge(forwardChain, from, migration);\n appendEdge(reverseChain, to, migration);\n }\n\n return { nodes, forwardChain, reverseChain, migrationByHash };\n}\n\n// ---------------------------------------------------------------------------\n// Deterministic tie-breaking for BFS neighbour order.\n// Used by path-finders only; not a general-purpose utility.\n// Ordering: createdAt → to → migrationHash.\n// ---------------------------------------------------------------------------\n\nfunction compareTieBreak(a: MigrationEdge, b: MigrationEdge): number {\n const ca = a.createdAt.localeCompare(b.createdAt);\n if (ca !== 0) return ca;\n const tc = a.to.localeCompare(b.to);\n if (tc !== 0) return tc;\n return a.migrationHash.localeCompare(b.migrationHash);\n}\n\nfunction sortedNeighbors(edges: readonly MigrationEdge[]): readonly MigrationEdge[] {\n return [...edges].sort(compareTieBreak);\n}\n\n/**\n * Find the shortest path from `fromHash` to `toHash` using BFS over the\n * contract-hash graph. Returns the ordered list of edges, or null if no path\n * exists. Returns an empty array when `fromHash === toHash` (no-op).\n *\n * Neighbor ordering is deterministic via the tie-break sort key:\n * createdAt → to → migrationHash.\n */\nexport function findPath(\n graph: MigrationGraph,\n fromHash: string,\n toHash: string,\n): readonly MigrationEdge[] | null {\n if (fromHash === toHash) return [];\n\n const parents = new Map<string, { parent: string; edge: MigrationEdge }>();\n for (const step of bfs([fromHash], (n) => sortedForwardNeighbours(graph, n))) {\n if (step.parent !== null && step.incomingEdge !== null) {\n parents.set(step.state, { parent: step.parent, edge: step.incomingEdge });\n }\n if (step.state === toHash) {\n const path: MigrationEdge[] = [];\n let cur = toHash;\n let p = parents.get(cur);\n while (p) {\n path.push(p.edge);\n cur = p.parent;\n p = parents.get(cur);\n }\n path.reverse();\n return path;\n }\n }\n\n return null;\n}\n\n/**\n * Find the shortest path from `fromHash` to `toHash` whose edges collectively\n * cover every invariant in `required`. Returns `null` when no such path exists\n * (either `fromHash`→`toHash` is structurally unreachable, or every reachable\n * path leaves at least one required invariant uncovered). When `required` is\n * empty, delegates to `findPath` so the result is byte-identical for that case.\n *\n * Algorithm: BFS over `(node, coveredSubset)` states with state-level dedup.\n * The covered subset is a `Set<string>` of invariant ids; the state's dedup\n * key is `${node}\\0${[...covered].sort().join('\\0')}`. State keys distinguish\n * distinct `(node, covered)` tuples regardless of node-name length because\n * `\\0` cannot appear in any invariant id (validation rejects whitespace and\n * control chars at authoring time).\n *\n * Neighbour ordering when `required ≠ ∅`: edges covering ≥1 still-needed\n * invariant come first, with `createdAt → to → migrationHash` as the\n * secondary key. The heuristic steers BFS toward the satisfying path;\n * correctness (shortest, deterministic) does not depend on it.\n */\nexport function findPathWithInvariants(\n graph: MigrationGraph,\n fromHash: string,\n toHash: string,\n required: ReadonlySet<string>,\n): readonly MigrationEdge[] | null {\n if (required.size === 0) {\n return findPath(graph, fromHash, toHash);\n }\n\n interface InvState {\n readonly node: string;\n readonly covered: ReadonlySet<string>;\n }\n // `\\0` is a safe segment separator: `validateInvariantId` rejects any id\n // containing whitespace or control characters (NUL is U+0000), and node\n // hashes are hex strings. Distinct `(node, covered)` tuples therefore\n // map to distinct strings. If `validateInvariantId` is ever relaxed,\n // re-confirm dedup correctness here.\n const stateKey = (s: InvState): string => {\n if (s.covered.size === 0) return `${s.node}\\0`;\n return `${s.node}\\0${[...s.covered].sort().join('\\0')}`;\n };\n\n const neighbours = (s: InvState): Iterable<{ next: InvState; edge: MigrationEdge }> => {\n const outgoing = graph.forwardChain.get(s.node) ?? [];\n if (outgoing.length === 0) return [];\n return [...outgoing]\n .map((edge) => {\n let useful = false;\n let next: Set<string> | null = null;\n for (const inv of edge.invariants) {\n if (required.has(inv) && !s.covered.has(inv)) {\n if (next === null) next = new Set(s.covered);\n next.add(inv);\n useful = true;\n }\n }\n return { edge, useful, nextCovered: next ?? s.covered };\n })\n .sort((a, b) => {\n if (a.useful !== b.useful) return a.useful ? -1 : 1;\n return compareTieBreak(a.edge, b.edge);\n })\n .map(({ edge, nextCovered }) => ({\n next: { node: edge.to, covered: nextCovered },\n edge,\n }));\n };\n\n // Path reconstruction is consumer-side, keyed on stateKey, same shape as\n // findPath's parents map.\n const parents = new Map<string, { parentKey: string; edge: MigrationEdge }>();\n for (const step of bfs<InvState, MigrationEdge>(\n [{ node: fromHash, covered: new Set() }],\n neighbours,\n stateKey,\n )) {\n const curKey = stateKey(step.state);\n if (step.parent !== null && step.incomingEdge !== null) {\n parents.set(curKey, { parentKey: stateKey(step.parent), edge: step.incomingEdge });\n }\n if (step.state.node === toHash && step.state.covered.size === required.size) {\n const path: MigrationEdge[] = [];\n let cur: string | undefined = curKey;\n while (cur !== undefined) {\n const p = parents.get(cur);\n if (!p) break;\n path.push(p.edge);\n cur = p.parentKey;\n }\n path.reverse();\n return path;\n }\n }\n\n return null;\n}\n\n/**\n * Reverse-BFS from `toHash` over `reverseChain` to collect every node from\n * which `toHash` is reachable (inclusive of `toHash` itself).\n */\nfunction collectNodesReachingTarget(graph: MigrationGraph, toHash: string): Set<string> {\n const reached = new Set<string>();\n for (const step of bfs([toHash], (n) => reverseNeighbours(graph, n))) {\n reached.add(step.state);\n }\n return reached;\n}\n\nexport interface PathDecision {\n readonly selectedPath: readonly MigrationEdge[];\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n /** The caller-supplied required invariant set, sorted ascending. */\n readonly requiredInvariants: readonly string[];\n /**\n * The subset of `requiredInvariants` actually covered by edges on\n * `selectedPath`. Always a subset of `requiredInvariants` (when the path\n * is satisfying, equal to it); always derived from `selectedPath`.\n */\n readonly satisfiedInvariants: readonly string[];\n}\n\n/**\n * Outcome of {@link findPathWithDecision}. The pathfinder distinguishes\n * three cases up front so callers don't re-derive structural reachability:\n *\n * - `ok` — a path covering `required` exists; `decision` carries the\n * selection metadata and per-edge invariants.\n * - `unreachable` — `from`→`to` has no structural path. Mapped by callers\n * to the existing no-path / `NO_TARGET` diagnostic.\n * - `unsatisfiable` — `from`→`to` is structurally reachable but no path\n * covers every required invariant. `structuralPath` is the\n * `findPath(graph, from, to)` result, included so callers don't have to\n * recompute it when raising `MIGRATION.NO_INVARIANT_PATH`. `missing` is\n * the subset of `required` that the structural path does *not* cover —\n * correctly accounts for partial coverage when some required invariants\n * are met by the fallback path. Only emitted when `required` is\n * non-empty.\n */\nexport type FindPathOutcome =\n | { readonly kind: 'ok'; readonly decision: PathDecision }\n | { readonly kind: 'unreachable' }\n | {\n readonly kind: 'unsatisfiable';\n readonly structuralPath: readonly MigrationEdge[];\n readonly missing: readonly string[];\n };\n\n/**\n * Routing context for {@link findPathWithDecision}. Both fields are optional;\n * `refName` is only used to decorate the resulting `PathDecision` for the\n * JSON envelope, and `required` defaults to an empty set (purely structural\n * routing). They are passed via a single options object so the call sites\n * cannot silently swap two adjacent string parameters.\n */\nexport interface FindPathWithDecisionOptions {\n readonly refName?: string;\n readonly required?: ReadonlySet<string>;\n}\n\n/**\n * Find the shortest path from `fromHash` to `toHash` and return structured\n * path-decision metadata for machine-readable output. When `required` is\n * non-empty, the returned path is the shortest one whose edges collectively\n * cover every required invariant.\n *\n * The discriminated return type tells the caller *why* a path could not be\n * found, so the CLI can pick the right structured error without re-running\n * a structural BFS.\n */\nexport function findPathWithDecision(\n graph: MigrationGraph,\n fromHash: string,\n toHash: string,\n options: FindPathWithDecisionOptions = {},\n): FindPathOutcome {\n const { refName, required = new Set<string>() } = options;\n const requiredInvariants = [...required].sort();\n\n if (fromHash === toHash && required.size === 0) {\n return {\n kind: 'ok',\n decision: {\n selectedPath: [],\n fromHash,\n toHash,\n alternativeCount: 0,\n tieBreakReasons: [],\n requiredInvariants,\n satisfiedInvariants: [],\n ...ifDefined('refName', refName),\n },\n };\n }\n\n const path = findPathWithInvariants(graph, fromHash, toHash, required);\n if (!path) {\n if (required.size === 0) {\n return { kind: 'unreachable' };\n }\n const structural = findPath(graph, fromHash, toHash);\n if (structural === null) {\n return { kind: 'unreachable' };\n }\n const coveredByStructural = new Set<string>();\n for (const edge of structural) {\n for (const inv of edge.invariants) {\n if (required.has(inv)) coveredByStructural.add(inv);\n }\n }\n const missing = requiredInvariants.filter((id) => !coveredByStructural.has(id));\n return { kind: 'unsatisfiable', structuralPath: structural, missing };\n }\n\n const satisfiedInvariants = computeSatisfiedInvariants(required, path);\n\n // Single reverse BFS marks every node from which `toHash` is reachable.\n // Replaces a per-edge `findPath(e.to, toHash)` call inside the loop below,\n // which made the whole function O(|path| · (V + E)) instead of O(V + E).\n const reachesTarget = collectNodesReachingTarget(graph, toHash);\n const coveragePrefixes = requiredCoveragePrefixes(required, path);\n\n const tieBreakReasons: string[] = [];\n let alternativeCount = 0;\n\n for (const [i, edge] of path.entries()) {\n const outgoing = graph.forwardChain.get(edge.from);\n if (!outgoing || outgoing.length <= 1) continue;\n const reachable = outgoing.filter((e) => reachesTarget.has(e.to));\n if (reachable.length <= 1) continue;\n\n let comparisonPool: readonly MigrationEdge[] = reachable;\n if (required.size > 0) {\n // coveragePrefixes is built one-per-edge from path, so the index is\n // always in range here; the explicit guard keeps the type narrowed\n // without a non-null assertion.\n const prefixSet = coveragePrefixes[i];\n if (prefixSet === undefined) continue;\n comparisonPool = invariantViableAlternativesAtStep(required, prefixSet, reachable);\n }\n\n alternativeCount += reachable.length - 1;\n const sorted = sortedNeighbors(reachable);\n if (sorted[0]?.migrationHash !== edge.migrationHash) continue;\n if (!reachable.some((e) => e.migrationHash !== edge.migrationHash)) continue;\n\n const sortedViable = sortedNeighbors(comparisonPool);\n if (\n sortedViable.length > 1 &&\n sortedViable[0]?.migrationHash === edge.migrationHash &&\n sortedViable.some((e) => e.migrationHash !== edge.migrationHash)\n ) {\n tieBreakReasons.push(\n `at ${edge.from}: ${comparisonPool.length} candidates, selected by tie-break`,\n );\n }\n }\n\n return {\n kind: 'ok',\n decision: {\n selectedPath: path,\n fromHash,\n toHash,\n alternativeCount,\n tieBreakReasons,\n requiredInvariants,\n satisfiedInvariants,\n ...ifDefined('refName', refName),\n },\n };\n}\n\nfunction computeSatisfiedInvariants(\n required: ReadonlySet<string>,\n path: readonly MigrationEdge[],\n): readonly string[] {\n if (required.size === 0) return [];\n const covered = new Set<string>();\n for (const edge of path) {\n for (const inv of edge.invariants) {\n if (required.has(inv)) covered.add(inv);\n }\n }\n return [...covered].sort();\n}\n\n/**\n * For each edge on path, invariant coverage accumulated from earlier edges only —\n * `(required ∩ ∪_{j<i} path[j].invariants)` represented as cumulative set along `required`,\n * keyed as \"full set of required ids satisfied before taking path[i]\".\n */\nfunction requiredCoveragePrefixes(\n required: ReadonlySet<string>,\n path: readonly MigrationEdge[],\n): readonly ReadonlySet<string>[] {\n const prefixes: ReadonlySet<string>[] = [];\n const acc = new Set<string>();\n for (const edge of path) {\n prefixes.push(new Set(acc));\n for (const inv of edge.invariants) {\n if (required.has(inv)) acc.add(inv);\n }\n }\n return prefixes;\n}\n\nfunction invariantViableAlternativesAtStep(\n required: ReadonlySet<string>,\n coverageBeforeTakingEdge: ReadonlySet<string>,\n outgoing: readonly MigrationEdge[],\n): readonly MigrationEdge[] {\n if (required.size === 0) return [...outgoing];\n return outgoing.filter((e) =>\n [...required].every((id) => coverageBeforeTakingEdge.has(id) || e.invariants.includes(id)),\n );\n}\n\n/**\n * Walk ancestors of each branch tip back to find the last node\n * that appears on all paths. Returns `fromHash` if no shared ancestor is found.\n */\nfunction findDivergencePoint(\n graph: MigrationGraph,\n fromHash: string,\n leaves: readonly string[],\n): string {\n const ancestorSets = leaves.map((leaf) => {\n const ancestors = new Set<string>();\n for (const step of bfs([leaf], (n) => reverseNeighbours(graph, n))) {\n ancestors.add(step.state);\n }\n return ancestors;\n });\n\n const commonAncestors = [...(ancestorSets[0] ?? [])].filter((node) =>\n ancestorSets.every((s) => s.has(node)),\n );\n\n let deepest = fromHash;\n let deepestDepth = -1;\n for (const ancestor of commonAncestors) {\n const path = findPath(graph, fromHash, ancestor);\n const depth = path ? path.length : 0;\n if (depth > deepestDepth) {\n deepestDepth = depth;\n deepest = ancestor;\n }\n }\n return deepest;\n}\n\n/**\n * Find all branch tips (nodes with no outgoing edges) reachable from\n * `fromHash` via forward edges.\n */\nexport function findReachableLeaves(graph: MigrationGraph, fromHash: string): readonly string[] {\n const leaves: string[] = [];\n for (const step of bfs([fromHash], (n) => forwardNeighbours(graph, n))) {\n if (!graph.forwardChain.get(step.state)?.length) {\n leaves.push(step.state);\n }\n }\n return leaves;\n}\n\n/**\n * Find the target contract hash of the migration graph reachable from\n * EMPTY_CONTRACT_HASH. Returns `null` for a graph that has no target\n * state (either empty, or containing only the root with no outgoing\n * edges). Throws NO_INITIAL_MIGRATION if the graph has nodes but none\n * originate from the empty hash, and AMBIGUOUS_TARGET if multiple\n * branch tips exist.\n */\nexport function findLeaf(graph: MigrationGraph): string | null {\n if (graph.nodes.size === 0) {\n return null;\n }\n\n if (!graph.nodes.has(EMPTY_CONTRACT_HASH)) {\n throw errorNoInitialMigration([...graph.nodes]);\n }\n\n const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);\n\n if (leaves.length === 0) {\n const reachable = [...graph.nodes].filter((n) => n !== EMPTY_CONTRACT_HASH);\n if (reachable.length > 0) {\n throw errorNoTarget(reachable);\n }\n return null;\n }\n\n if (leaves.length > 1) {\n const divergencePoint = findDivergencePoint(graph, EMPTY_CONTRACT_HASH, leaves);\n const branches = leaves.map((tip) => {\n const path = findPath(graph, divergencePoint, tip);\n return {\n tip,\n edges: (path ?? []).map((e) => ({ dirName: e.dirName, from: e.from, to: e.to })),\n };\n });\n throw errorAmbiguousTarget(leaves, { divergencePoint, branches });\n }\n\n // biome-ignore lint/style/noNonNullAssertion: leaves.length is neither 0 nor >1 per the branches above, so exactly one leaf remains\n return leaves[0]!;\n}\n\n/**\n * Find the latest migration entry by traversing from EMPTY_CONTRACT_HASH\n * to the single target. Returns null for an empty graph.\n * Throws AMBIGUOUS_TARGET if the graph has multiple branch tips.\n */\nexport function findLatestMigration(graph: MigrationGraph): MigrationEdge | null {\n const leafHash = findLeaf(graph);\n if (leafHash === null) return null;\n\n const path = findPath(graph, EMPTY_CONTRACT_HASH, leafHash);\n return path?.at(-1) ?? null;\n}\n\nexport function detectCycles(graph: MigrationGraph): readonly string[][] {\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n\n const color = new Map<string, number>();\n const parentMap = new Map<string, string | null>();\n const cycles: string[][] = [];\n\n for (const node of graph.nodes) {\n color.set(node, WHITE);\n }\n\n // Iterative three-color DFS. A frame is (node, outgoing edges, next-index).\n interface Frame {\n node: string;\n outgoing: readonly MigrationEdge[];\n index: number;\n }\n const stack: Frame[] = [];\n\n function pushFrame(u: string): void {\n color.set(u, GRAY);\n stack.push({ node: u, outgoing: graph.forwardChain.get(u) ?? [], index: 0 });\n }\n\n for (const root of graph.nodes) {\n if (color.get(root) !== WHITE) continue;\n parentMap.set(root, null);\n pushFrame(root);\n\n while (stack.length > 0) {\n // biome-ignore lint/style/noNonNullAssertion: stack.length > 0 should guarantee that this cannot be undefined\n const frame = stack[stack.length - 1]!;\n if (frame.index >= frame.outgoing.length) {\n color.set(frame.node, BLACK);\n stack.pop();\n continue;\n }\n // biome-ignore lint/style/noNonNullAssertion: the early-continue above guarantees frame.index < frame.outgoing.length here, so this is defined\n const edge = frame.outgoing[frame.index++]!;\n const v = edge.to;\n const vColor = color.get(v);\n if (vColor === GRAY) {\n const cycle: string[] = [v];\n let cur = frame.node;\n while (cur !== v) {\n cycle.push(cur);\n cur = parentMap.get(cur) ?? v;\n }\n cycle.reverse();\n cycles.push(cycle);\n } else if (vColor === WHITE) {\n parentMap.set(v, frame.node);\n pushFrame(v);\n }\n }\n }\n\n return cycles;\n}\n\nexport function detectOrphans(graph: MigrationGraph): readonly MigrationEdge[] {\n if (graph.nodes.size === 0) return [];\n\n const reachable = new Set<string>();\n const startNodes: string[] = [];\n\n if (graph.forwardChain.has(EMPTY_CONTRACT_HASH)) {\n startNodes.push(EMPTY_CONTRACT_HASH);\n } else {\n const allTargets = new Set<string>();\n for (const edges of graph.forwardChain.values()) {\n for (const edge of edges) {\n allTargets.add(edge.to);\n }\n }\n for (const node of graph.nodes) {\n if (!allTargets.has(node)) {\n startNodes.push(node);\n }\n }\n }\n\n for (const step of bfs(startNodes, (n) => forwardNeighbours(graph, n))) {\n reachable.add(step.state);\n }\n\n const orphans: MigrationEdge[] = [];\n for (const [from, migrations] of graph.forwardChain) {\n if (!reachable.has(from)) {\n orphans.push(...migrations);\n }\n }\n\n return orphans;\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAa,QAAb,MAAsB;CACpB;CACA,OAAe;CAEf,YAAY,UAAuB,CAAC,GAAG;EACrC,KAAK,QAAQ,CAAC,GAAG,OAAO;CAC1B;CAEA,KAAK,MAAe;EAClB,KAAK,MAAM,KAAK,IAAI;CACtB;;;;;CAMA,QAAW;EACT,IAAI,KAAK,QAAQ,KAAK,MAAM,QAC1B,MAAM,IAAI,MAAM,mCAAmC;EAGrD,OAAO,KAAK,MAAM,KAAK;CACzB;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,QAAQ,KAAK,MAAM;CACjC;AACF;;;ACUA,UAAiB,IACf,QACA,YAKA,OAA6B,UAAU,OACb;CAS1B,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,4BAAY,IAAI,IAAoC;CAC1D,MAAM,QAAQ,IAAI,MAAa;CAC/B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,IAAI,IA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I9B,OAAO;AACT"}
import { _ as errorInvalidRefFile, t as MigrationToolsError, v as errorInvalidRefName, y as errorInvalidRefValue } from "./errors-DldT38lZ.mjs";
import { dirname, join, relative } from "pathe";
import { mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from "node:fs/promises";
import { type } from "arktype";
//#region src/refs.ts
/**
* The system head ref lives at `refs/head.json`. It is read (and its
* corruption judged) through `readContractSpaceHeadRef`, not as a
* user-authored ref, so {@link readRefsTolerant} excludes it.
*/
const HEAD_REF_NAME = "head";
const REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
const REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;
function validateRefName(name) {
if (name.length === 0) return false;
if (name.includes("..")) return false;
if (name.includes("//")) return false;
if (name.startsWith(".")) return false;
return REF_NAME_PATTERN.test(name);
}
function validateRefValue(value) {
return REF_VALUE_PATTERN.test(value);
}
const RefEntrySchema = type({
hash: "string",
invariants: "string[]"
}).narrow((entry, ctx) => {
if (!validateRefValue(entry.hash)) return ctx.mustBe(`a valid contract hash (got "${entry.hash}")`);
return true;
});
function refFilePath(refsDir, name) {
return join(refsDir, `${name}.json`);
}
function refNameFromPath(refsDir, filePath) {
return relative(refsDir, filePath).replace(/\.json$/, "");
}
async function readRef(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const filePath = refFilePath(refsDir, name);
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
why: `No ref file found at "${filePath}".`,
fix: `Create the ref with: prisma-next ref set ${name} <hash>`,
details: {
refName: name,
filePath
}
});
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
}
const result = RefEntrySchema(parsed);
if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
return result;
}
async function readRefs(refsDir) {
let entries;
try {
entries = await readdir(refsDir, {
recursive: true,
encoding: "utf-8"
});
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") return {};
throw error;
}
const jsonFiles = entries.filter((entry) => entry.endsWith(".json") && !entry.endsWith(".contract.json"));
const refs = {};
for (const jsonFile of jsonFiles) {
const filePath = join(refsDir, jsonFile);
const name = refNameFromPath(refsDir, filePath);
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
const code = error instanceof Error ? error.code : void 0;
if (code === "ENOENT" || code === "EISDIR") continue;
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
}
const result = RefEntrySchema(parsed);
if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
refs[name] = result;
}
return refs;
}
/**
* Read a space's user-authored refs without ever throwing on disk
* content. A ref whose JSON is unparseable or whose shape fails
* {@link RefEntrySchema} is omitted from `refs` and reported as a
* {@link RefLoadProblem}; the remaining well-formed refs are still
* returned. A missing `refs/` directory yields no refs and no problems.
*
* `refs/head.json` is deliberately skipped here: the system head ref is
* read through `readContractSpaceHeadRef` (which validates head-ref
* shape, distinct from the strict user-ref hash grammar), so it is judged
* there and never doubles as a user ref. Genuine I/O faults (EACCES, EIO,
* …) still propagate — only parse / schema problems are made tolerant.
*/
async function readRefsTolerant(refsDir) {
let entries;
try {
entries = await readdir(refsDir, {
recursive: true,
encoding: "utf-8"
});
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") return {
refs: {},
problems: []
};
throw error;
}
const jsonFiles = entries.filter((entry) => entry.endsWith(".json") && !entry.endsWith(".contract.json") && entry !== `head.json`);
const refs = {};
const problems = [];
for (const jsonFile of jsonFiles) {
const filePath = join(refsDir, jsonFile);
const name = refNameFromPath(refsDir, filePath);
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
const code = error instanceof Error ? error.code : void 0;
if (code === "ENOENT" || code === "EISDIR") continue;
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (e) {
problems.push({
refName: name,
detail: e instanceof Error ? e.message : String(e)
});
continue;
}
const result = RefEntrySchema(parsed);
if (result instanceof type.errors) {
problems.push({
refName: name,
detail: result.summary
});
continue;
}
refs[name] = result;
}
return {
refs,
problems
};
}
async function writeRef(refsDir, name, entry) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
if (!validateRefValue(entry.hash)) throw errorInvalidRefValue(entry.hash);
const filePath = refFilePath(refsDir, name);
const dir = dirname(filePath);
await mkdir(dir, { recursive: true });
const tmpPath = join(dir, `.${name.split("/").pop()}.json.${Date.now()}.tmp`);
await writeFile(tmpPath, `${JSON.stringify({
hash: entry.hash,
invariants: [...entry.invariants]
}, null, 2)}\n`);
await rename(tmpPath, filePath);
}
async function deleteRef(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const filePath = refFilePath(refsDir, name);
try {
await unlink(filePath);
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
why: `No ref file found at "${filePath}".`,
fix: "Run `prisma-next ref list` to see available refs.",
details: {
refName: name,
filePath
}
});
throw error;
}
let dir = dirname(filePath);
while (dir !== refsDir && dir.startsWith(refsDir)) try {
await rmdir(dir);
dir = dirname(dir);
} catch (error) {
const code = error instanceof Error ? error.code : void 0;
if (code === "ENOTEMPTY" || code === "EEXIST" || code === "ENOENT") break;
throw error;
}
}
/**
* Index user-authored refs by the contract hash each ref points at.
* Each bucket is sorted lex-asc for deterministic output.
*/
function refsByContractHash(refs) {
const byHash = /* @__PURE__ */ new Map();
for (const [name, entry] of Object.entries(refs)) {
const bucket = byHash.get(entry.hash);
if (bucket) bucket.push(name);
else byHash.set(entry.hash, [name]);
}
for (const bucket of byHash.values()) bucket.sort();
return byHash;
}
/**
* Read `migrations/<space>/refs/*.json` and index by destination hash.
* Returns an empty map when the refs directory does not exist.
*/
async function resolveRefsByContractHash(refsDir) {
return refsByContractHash(await readRefs(refsDir));
}
function resolveRef(refs, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
if (!Object.hasOwn(refs, name)) throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
why: `No ref named "${name}" exists.`,
fix: `Available refs: ${Object.keys(refs).join(", ") || "(none)"}. Create a ref with: prisma-next ref set ${name} <hash>`,
details: {
refName: name,
availableRefs: Object.keys(refs)
}
});
return refs[name];
}
//#endregion
export { readRefsTolerant as a, resolveRefsByContractHash as c, writeRef as d, readRefs as i, validateRefName as l, deleteRef as n, refsByContractHash as o, readRef as r, resolveRef as s, HEAD_REF_NAME as t, validateRefValue as u };
//# sourceMappingURL=refs-BI9kMF4i.mjs.map
{"version":3,"file":"refs-BI9kMF4i.mjs","names":[],"sources":["../src/refs.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from 'node:fs/promises';\nimport { type } from 'arktype';\nimport { dirname, join, relative } from 'pathe';\nimport {\n errorInvalidRefFile,\n errorInvalidRefName,\n errorInvalidRefValue,\n MigrationToolsError,\n} from './errors';\n\nexport interface RefEntry {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\nexport type Refs = Readonly<Record<string, RefEntry>>;\n\n/**\n * The system head ref lives at `refs/head.json`. It is read (and its\n * corruption judged) through `readContractSpaceHeadRef`, not as a\n * user-authored ref, so {@link readRefsTolerant} excludes it.\n */\nexport const HEAD_REF_NAME = 'head';\n\n/**\n * A single ref file that exists on disk but cannot be turned into a\n * {@link RefEntry} (unparseable JSON or schema-invalid content). The ref\n * is omitted from the result; the problem is surfaced for the integrity\n * layer to report as `refUnreadable` rather than aborting the load.\n */\nexport interface RefLoadProblem {\n readonly refName: string;\n readonly detail: string;\n}\n\nexport interface TolerantRefsResult {\n readonly refs: Refs;\n readonly problems: readonly RefLoadProblem[];\n}\n\nconst REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\nconst REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;\n\nexport function validateRefName(name: string): boolean {\n if (name.length === 0) return false;\n if (name.includes('..')) return false;\n if (name.includes('//')) return false;\n if (name.startsWith('.')) return false;\n return REF_NAME_PATTERN.test(name);\n}\n\nexport function validateRefValue(value: string): boolean {\n return REF_VALUE_PATTERN.test(value);\n}\n\nconst RefEntrySchema = type({\n hash: 'string',\n invariants: 'string[]',\n}).narrow((entry, ctx) => {\n if (!validateRefValue(entry.hash))\n return ctx.mustBe(`a valid contract hash (got \"${entry.hash}\")`);\n return true;\n});\n\nfunction refFilePath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.json`);\n}\n\nfunction refNameFromPath(refsDir: string, filePath: string): string {\n const rel = relative(refsDir, filePath);\n return rel.replace(/\\.json$/, '');\n}\n\nexport async function readRef(refsDir: string, name: string): Promise<RefEntry> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const filePath = refFilePath(refsDir, name);\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref file found at \"${filePath}\".`,\n fix: `Create the ref with: prisma-next ref set ${name} <hash>`,\n details: { refName: name, filePath },\n });\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n return result;\n}\n\nexport async function readRefs(refsDir: string): Promise<Refs> {\n let entries: string[];\n try {\n entries = await readdir(refsDir, { recursive: true, encoding: 'utf-8' });\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n\n const jsonFiles = entries.filter(\n (entry) => entry.endsWith('.json') && !entry.endsWith('.contract.json'),\n );\n const refs: Record<string, RefEntry> = {};\n\n for (const jsonFile of jsonFiles) {\n const filePath = join(refsDir, jsonFile);\n const name = refNameFromPath(refsDir, filePath);\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n // Tolerate the TOCTOU race between `readdir` and `readFile` (ENOENT) and\n // benign EISDIR if a directory happens to end in `.json`. Anything else\n // (EACCES, EIO, EMFILE, …) is a real failure and propagates so the CLI\n // surfaces it rather than silently dropping the ref.\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOENT' || code === 'EISDIR') {\n continue;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n refs[name] = result;\n }\n\n return refs;\n}\n\n/**\n * Read a space's user-authored refs without ever throwing on disk\n * content. A ref whose JSON is unparseable or whose shape fails\n * {@link RefEntrySchema} is omitted from `refs` and reported as a\n * {@link RefLoadProblem}; the remaining well-formed refs are still\n * returned. A missing `refs/` directory yields no refs and no problems.\n *\n * `refs/head.json` is deliberately skipped here: the system head ref is\n * read through `readContractSpaceHeadRef` (which validates head-ref\n * shape, distinct from the strict user-ref hash grammar), so it is judged\n * there and never doubles as a user ref. Genuine I/O faults (EACCES, EIO,\n * …) still propagate — only parse / schema problems are made tolerant.\n */\nexport async function readRefsTolerant(refsDir: string): Promise<TolerantRefsResult> {\n let entries: string[];\n try {\n entries = await readdir(refsDir, { recursive: true, encoding: 'utf-8' });\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return { refs: {}, problems: [] };\n }\n throw error;\n }\n\n const jsonFiles = entries.filter(\n (entry) =>\n entry.endsWith('.json') &&\n !entry.endsWith('.contract.json') &&\n entry !== `${HEAD_REF_NAME}.json`,\n );\n const refs: Record<string, RefEntry> = {};\n const problems: RefLoadProblem[] = [];\n\n for (const jsonFile of jsonFiles) {\n const filePath = join(refsDir, jsonFile);\n const name = refNameFromPath(refsDir, filePath);\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n // Tolerate the TOCTOU race between `readdir` and `readFile` (ENOENT)\n // and benign EISDIR if a directory happens to end in `.json`.\n // Anything else (EACCES, EIO, …) is a real failure and propagates.\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOENT' || code === 'EISDIR') {\n continue;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n problems.push({ refName: name, detail: e instanceof Error ? e.message : String(e) });\n continue;\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n problems.push({ refName: name, detail: result.summary });\n continue;\n }\n\n refs[name] = result;\n }\n\n return { refs, problems };\n}\n\nexport async function writeRef(refsDir: string, name: string, entry: RefEntry): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n if (!validateRefValue(entry.hash)) {\n throw errorInvalidRefValue(entry.hash);\n }\n\n const filePath = refFilePath(refsDir, name);\n const dir = dirname(filePath);\n await mkdir(dir, { recursive: true });\n\n const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`);\n await writeFile(\n tmpPath,\n `${JSON.stringify({ hash: entry.hash, invariants: [...entry.invariants] }, null, 2)}\\n`,\n );\n await rename(tmpPath, filePath);\n}\n\nexport async function deleteRef(refsDir: string, name: string): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const filePath = refFilePath(refsDir, name);\n try {\n await unlink(filePath);\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref file found at \"${filePath}\".`,\n fix: 'Run `prisma-next ref list` to see available refs.',\n details: { refName: name, filePath },\n });\n }\n throw error;\n }\n\n // Clean empty parent directories up to refsDir. Stop walking on the expected\n // \"directory has siblings\" signal (ENOTEMPTY on Linux, EEXIST on some BSDs)\n // and on ENOENT (concurrent removal). Anything else (EACCES, EIO, …) is a\n // real failure and propagates.\n let dir = dirname(filePath);\n while (dir !== refsDir && dir.startsWith(refsDir)) {\n try {\n await rmdir(dir);\n dir = dirname(dir);\n } catch (error) {\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOTEMPTY' || code === 'EEXIST' || code === 'ENOENT') {\n break;\n }\n throw error;\n }\n }\n}\n\n/**\n * Index user-authored refs by the contract hash each ref points at.\n * Each bucket is sorted lex-asc for deterministic output.\n */\nexport function refsByContractHash(refs: Refs): ReadonlyMap<string, readonly string[]> {\n const byHash = new Map<string, string[]>();\n for (const [name, entry] of Object.entries(refs)) {\n const bucket = byHash.get(entry.hash);\n if (bucket) bucket.push(name);\n else byHash.set(entry.hash, [name]);\n }\n for (const bucket of byHash.values()) {\n bucket.sort();\n }\n return byHash;\n}\n\n/**\n * Read `migrations/<space>/refs/*.json` and index by destination hash.\n * Returns an empty map when the refs directory does not exist.\n */\nexport async function resolveRefsByContractHash(\n refsDir: string,\n): Promise<ReadonlyMap<string, readonly string[]>> {\n return refsByContractHash(await readRefs(refsDir));\n}\n\nexport function resolveRef(refs: Refs, name: string): RefEntry {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n // Object.hasOwn gate: plain-object `refs` would otherwise let\n // `refs['constructor']` return Object.prototype.constructor and bypass the\n // UNKNOWN_REF throw. validateRefName accepts `\"constructor\"` as a name shape.\n if (!Object.hasOwn(refs, name)) {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref named \"${name}\" exists.`,\n fix: `Available refs: ${Object.keys(refs).join(', ') || '(none)'}. Create a ref with: prisma-next ref set ${name} <hash>`,\n details: { refName: name, availableRefs: Object.keys(refs) },\n });\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Object.hasOwn gate above guarantees this is defined\n return refs[name]!;\n}\n"],"mappings":";;;;;;;;;;AAsBA,MAAa,gBAAgB;AAkB7B,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAE1B,SAAgB,gBAAgB,MAAuB;CACrD,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI,KAAK,SAAS,IAAI,GAAG,OAAO;CAChC,IAAI,KAAK,SAAS,IAAI,GAAG,OAAO;CAChC,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CACjC,OAAO,iBAAiB,KAAK,IAAI;AACnC;AAEA,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,kBAAkB,KAAK,KAAK;AACrC;AAEA,MAAM,iBAAiB,KAAK;CAC1B,MAAM;CACN,YAAY;AACd,CAAC,CAAC,CAAC,QAAQ,OAAO,QAAQ;CACxB,IAAI,CAAC,iBAAiB,MAAM,IAAI,GAC9B,OAAO,IAAI,OAAO,+BAA+B,MAAM,KAAK,GAAG;CACjE,OAAO;AACT,CAAC;AAED,SAAS,YAAY,SAAiB,MAAsB;CAC1D,OAAO,KAAK,SAAS,GAAG,KAAK,MAAM;AACrC;AAEA,SAAS,gBAAgB,SAAiB,UAA0B;CAElE,OADY,SAAS,SAAS,QACrB,CAAC,CAAC,QAAQ,WAAW,EAAE;AAClC;AAEA,eAAsB,QAAQ,SAAiB,MAAiC;CAC9E,IAAI,CAAC,gBAAgB,IAAI,GACvB,MAAM,oBAAoB,IAAI;CAGhC,MAAM,WAAW,YAAY,SAAS,IAAI;CAC1C,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,SAAS,UAAU,OAAO;CACxC,SAAS,OAAO;EACd,IAAI,iBAAiB,SAAU,MAA4B,SAAS,UAClE,MAAM,IAAI,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AAS,OAAO,IAAI,MAAM,IAAI;EACpC,IAAI,QAAQ,OAAO,KAAK,IAAI;OACvB,OAAO,IAAI,MAAM,MAAM,CAAC,IAAI,CAAC;CACpC;CACA,KAAK,MAAM,UAAU,OAAO,OAAO,GACjC,OAAO,KAAK;CAEd,OAAO;AACT;;;;;AAMA,eAAsB,0BACpB,SACiD;CACjD,OAAO,mBAAmB,MAAM,SAAS,OAAO,CAAC;AACnD;AAEA,SAAgB,WAAW,MAAY,MAAwB;CAC7D,IAAI,CAAC,gBAAgB,IAAI,GACvB,MAAM,oBAAoB,IAAI;CAMhC,IAAI,CAAC,OAAO,OAAO,MAAM,IAAI,GAC3B,MAAM,IAAI,oBAAoB,yBAAyB,gBAAgB,KAAK,IAAI;EAC9E,KAAK,iBAAiB,KAAK;EAC3B,KAAK,mBAAmB,OAAO,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,KAAK,SAAS,2CAA2C,KAAK;EACjH,SAAS;GAAE,SAAS;GAAM,eAAe,OAAO,KAAK,IAAI;EAAE;CAC7D,CAAC;CAIH,OAAO,KAAK;AACd"}
import { _ as errorInvalidRefFile, t as MigrationToolsError, v as errorInvalidRefName } from "./errors-DldT38lZ.mjs";
import { d as writeRef, l as validateRefName, n as deleteRef } from "./refs-BI9kMF4i.mjs";
import { basename, dirname, join } from "pathe";
import { access, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import { type } from "arktype";
import { randomBytes } from "node:crypto";
import { canonicalizeJson } from "@prisma-next/framework-components/utils";
//#region src/refs/snapshot.ts
const ContractIrSchema = type({
targetFamily: "string",
target: "string",
profileHash: "string",
storage: type({ storageHash: "string" }),
domain: type({ namespaces: "object" })
});
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
function snapshotJsonPath(refsDir, name) {
return join(refsDir, `${name}.contract.json`);
}
function snapshotDtsPath(refsDir, name) {
return join(refsDir, `${name}.contract.d.ts`);
}
function tmpPathFor(finalPath) {
return join(dirname(finalPath), `.${basename(finalPath)}.${Date.now()}-${randomBytes(4).toString("hex")}.tmp`);
}
async function atomicWriteFile(finalPath, content) {
await mkdir(dirname(finalPath), { recursive: true });
const tmpPath = tmpPathFor(finalPath);
await writeFile(tmpPath, content);
await rename(tmpPath, finalPath);
}
async function unlinkIfExists(filePath) {
try {
await unlink(filePath);
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return;
throw error;
}
}
function parseContractSnapshotJson(filePath, raw) {
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
}
const result = ContractIrSchema(parsed);
if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
return result;
}
async function writeRefSnapshot(refsDir, name, snapshot) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const jsonPath = snapshotJsonPath(refsDir, name);
const dtsPath = snapshotDtsPath(refsDir, name);
const jsonContent = `${canonicalizeJson(snapshot.contract)}\n`;
const dtsContent = snapshot.contractDts.endsWith("\n") ? snapshot.contractDts : `${snapshot.contractDts}\n`;
try {
await atomicWriteFile(jsonPath, jsonContent);
} catch (error) {
await unlinkIfExists(jsonPath);
throw error;
}
try {
await atomicWriteFile(dtsPath, dtsContent);
} catch (error) {
await unlinkIfExists(jsonPath);
await unlinkIfExists(dtsPath);
throw error;
}
}
async function readRefSnapshot(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const jsonPath = snapshotJsonPath(refsDir, name);
const dtsPath = snapshotDtsPath(refsDir, name);
let raw;
try {
raw = await readFile(jsonPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return null;
throw error;
}
const contract = parseContractSnapshotJson(jsonPath, raw);
let contractDts;
try {
contractDts = await readFile(dtsPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorInvalidRefFile(dtsPath, "Missing paired contract.d.ts snapshot file");
throw error;
}
return {
contract,
contractDts
};
}
async function deleteRefSnapshot(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
await unlinkIfExists(snapshotJsonPath(refsDir, name));
await unlinkIfExists(snapshotDtsPath(refsDir, name));
}
async function writeRefPaired(refsDir, name, entry, snapshot) {
await writeRefSnapshot(refsDir, name, snapshot);
try {
await writeRef(refsDir, name, entry);
} catch (writeError) {
try {
await deleteRefSnapshot(refsDir, name);
} catch {}
throw writeError;
}
}
function isUnknownRefError(error) {
return MigrationToolsError.is(error) && error.code === "MIGRATION.UNKNOWN_REF";
}
async function snapshotFilesExist(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const paths = [snapshotJsonPath(refsDir, name), snapshotDtsPath(refsDir, name)];
return (await Promise.allSettled(paths.map((filePath) => access(filePath)))).some((result) => result.status === "fulfilled");
}
async function deleteRefPaired(refsDir, name) {
if (await snapshotFilesExist(refsDir, name)) {
try {
await deleteRef(refsDir, name);
} catch (error) {
if (!isUnknownRefError(error)) throw error;
}
await deleteRefSnapshot(refsDir, name);
return;
}
await deleteRef(refsDir, name);
await deleteRefSnapshot(refsDir, name);
}
//#endregion
export { writeRefSnapshot as a, writeRefPaired as i, deleteRefSnapshot as n, readRefSnapshot as r, deleteRefPaired as t };
//# sourceMappingURL=snapshot-ByKdh1GJ.mjs.map
{"version":3,"file":"snapshot-ByKdh1GJ.mjs","names":[],"sources":["../src/refs/snapshot.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { access, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { type } from 'arktype';\nimport { basename, dirname, join } from 'pathe';\nimport { errorInvalidRefFile, errorInvalidRefName, MigrationToolsError } from '../errors';\nimport { deleteRef, type RefEntry, validateRefName, writeRef } from '../refs';\n\nexport interface ContractIR {\n readonly contract: unknown;\n readonly contractDts: string;\n}\n\nconst ContractIrSchema = type({\n targetFamily: 'string',\n target: 'string',\n profileHash: 'string',\n storage: type({\n storageHash: 'string',\n }),\n domain: type({\n namespaces: 'object',\n }),\n});\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\nfunction snapshotJsonPath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.contract.json`);\n}\n\nfunction snapshotDtsPath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.contract.d.ts`);\n}\n\nfunction tmpPathFor(finalPath: string): string {\n const dir = dirname(finalPath);\n const fileName = basename(finalPath);\n return join(dir, `.${fileName}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`);\n}\n\nasync function atomicWriteFile(finalPath: string, content: string): Promise<void> {\n const dir = dirname(finalPath);\n await mkdir(dir, { recursive: true });\n const tmpPath = tmpPathFor(finalPath);\n await writeFile(tmpPath, content);\n await rename(tmpPath, finalPath);\n}\n\nasync function unlinkIfExists(filePath: string): Promise<void> {\n try {\n await unlink(filePath);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) return;\n throw error;\n }\n}\n\nfunction parseContractSnapshotJson(filePath: string, raw: string): unknown {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = ContractIrSchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n return result;\n}\n\nexport async function writeRefSnapshot(\n refsDir: string,\n name: string,\n snapshot: ContractIR,\n): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const jsonPath = snapshotJsonPath(refsDir, name);\n const dtsPath = snapshotDtsPath(refsDir, name);\n const jsonContent = `${canonicalizeJson(snapshot.contract)}\\n`;\n const dtsContent = snapshot.contractDts.endsWith('\\n')\n ? snapshot.contractDts\n : `${snapshot.contractDts}\\n`;\n\n try {\n await atomicWriteFile(jsonPath, jsonContent);\n } catch (error) {\n await unlinkIfExists(jsonPath);\n throw error;\n }\n\n try {\n await atomicWriteFile(dtsPath, dtsContent);\n } catch (error) {\n await unlinkIfExists(jsonPath);\n await unlinkIfExists(dtsPath);\n throw error;\n }\n}\n\nexport async function readRefSnapshot(refsDir: string, name: string): Promise<ContractIR | null> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const jsonPath = snapshotJsonPath(refsDir, name);\n const dtsPath = snapshotDtsPath(refsDir, name);\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return null;\n }\n throw error;\n }\n\n const contract = parseContractSnapshotJson(jsonPath, raw);\n\n let contractDts: string;\n try {\n contractDts = await readFile(dtsPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorInvalidRefFile(dtsPath, 'Missing paired contract.d.ts snapshot file');\n }\n throw error;\n }\n\n return { contract, contractDts };\n}\n\nexport async function deleteRefSnapshot(refsDir: string, name: string): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n await unlinkIfExists(snapshotJsonPath(refsDir, name));\n await unlinkIfExists(snapshotDtsPath(refsDir, name));\n}\n\nexport async function writeRefPaired(\n refsDir: string,\n name: string,\n entry: RefEntry,\n snapshot: ContractIR,\n): Promise<void> {\n await writeRefSnapshot(refsDir, name, snapshot);\n try {\n await writeRef(refsDir, name, entry);\n } catch (writeError) {\n try {\n await deleteRefSnapshot(refsDir, name);\n } catch {\n // Rollback failure is secondary; preserve the original writeRef error.\n }\n throw writeError;\n }\n}\n\nfunction isUnknownRefError(error: unknown): boolean {\n return MigrationToolsError.is(error) && error.code === 'MIGRATION.UNKNOWN_REF';\n}\n\nasync function snapshotFilesExist(refsDir: string, name: string): Promise<boolean> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const paths = [snapshotJsonPath(refsDir, name), snapshotDtsPath(refsDir, name)];\n const checks = await Promise.allSettled(paths.map((filePath) => access(filePath)));\n return checks.some((result) => result.status === 'fulfilled');\n}\n\nexport async function deleteRefPaired(refsDir: string, name: string): Promise<void> {\n if (await snapshotFilesExist(refsDir, name)) {\n try {\n await deleteRef(refsDir, name);\n } catch (error) {\n if (!isUnknownRefError(error)) {\n throw error;\n }\n }\n await deleteRefSnapshot(refsDir, name);\n return;\n }\n\n await deleteRef(refsDir, name);\n await deleteRefSnapshot(refsDir, name);\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,mBAAmB,KAAK;CAC5B,cAAc;CACd,QAAQ;CACR,aAAa;CACb,SAAS,KAAK,EACZ,aAAa,SACf,CAAC;CACD,QAAQ,KAAK,EACX,YAAY,SACd,CAAC;AACH,CAAC;AAED,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;AAEA,SAAS,iBAAiB,SAAiB,MAAsB;CAC/D,OAAO,KAAK,SAAS,GAAG,KAAK,eAAe;AAC9C;AAEA,SAAS,gBAAgB,SAAiB,MAAsB;CAC9D,OAAO,KAAK,SAAS,GAAG,KAAK,eAAe;AAC9C;AAEA,SAAS,WAAW,WAA2B;CAG7C,OAAO,KAFK,QAAQ,SAEN,GAAG,IADA,SAAS,SACE,EAAE,GAAG,KAAK,IAAI,EAAE,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE,KAAK;AACrF;AAEA,eAAe,gBAAgB,WAAmB,SAAgC;CAEhF,MAAM,MADM,QAAQ,SACN,GAAG,EAAE,WAAW,KAAK,CAAC;CACpC,MAAM,UAAU,WAAW,SAAS;CACpC,MAAM,UAAU,SAAS,OAAO;CAChC,MAAM,OAAO,SAAS,SAAS;AACjC;AAEA,eAAe,eAAe,UAAiC;CAC7D,IAAI;EACF,MAAM,OAAO,QAAQ;CACvB,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAAG;EACnC,MAAM;CACR;AACF;AAEA,SAAS,0BAA0B,UAAkB,KAAsB;CACzE,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,QAAQ;EAC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AU;CAAY;AACjC;AAEA,eAAsB,kBAAkB,SAAiB,MAA6B;CACpF,IAAI,CAAC,gBAAgB,IAAI,GACvB,MAAM,oBAAoB,IAAI;CAGhC,MAAM,eAAe,iBAAiB,SAAS,IAAI,CAAC;CACpD,MAAM,eAAe,gBAAgB,SAAS,IAAI,CAAC;AACrD;AAEA,eAAsB,eACpB,SACA,MACA,OACA,UACe;CACf,MAAM,iBAAiB,SAAS,MAAM,QAAQ;CAC9C,IAAI;EACF,MAAM,SAAS,SAAS,MAAM,KAAK;CACrC,SAAS,YAAY;EACnB,IAAI;GACF,MAAM,kBAAkB,SAAS,IAAI;EACvC,QAAQ,CAER;EACA,MAAM;CACR;AACF;AAEA,SAAS,kBAAkB,OAAyB;CAClD,OAAO,oBAAoB,GAAG,KAAK,KAAK,MAAM,SAAS;AACzD;AAEA,eAAe,mBAAmB,SAAiB,MAAgC;CACjF,IAAI,CAAC,gBAAgB,IAAI,GACvB,MAAM,oBAAoB,IAAI;CAGhC,MAAM,QAAQ,CAAC,iBAAiB,SAAS,IAAI,GAAG,gBAAgB,SAAS,IAAI,CAAC;CAE9E,QAAO,MADc,QAAQ,WAAW,MAAM,KAAK,aAAa,OAAO,QAAQ,CAAC,CAAC,EAAA,CACnE,MAAM,WAAW,OAAO,WAAW,WAAW;AAC9D;AAEA,eAAsB,gBAAgB,SAAiB,MAA6B;CAClF,IAAI,MAAM,mBAAmB,SAAS,IAAI,GAAG;EAC3C,IAAI;GACF,MAAM,UAAU,SAAS,IAAI;EAC/B,SAAS,OAAO;GACd,IAAI,CAAC,kBAAkB,KAAK,GAC1B,MAAM;EAEV;EACA,MAAM,kBAAkB,SAAS,IAAI;EACrC;CACF;CAEA,MAAM,UAAU,SAAS,IAAI;CAC7B,MAAM,kBAAkB,SAAS,IAAI;AACvC"}
import { _ as errorInvalidRefFile, m as errorInvalidJson, x as errorInvalidSpaceId } from "./errors-DldT38lZ.mjs";
import { t as MANIFEST_FILE } from "./io-H4a-OJHL.mjs";
import { join } from "pathe";
import { readFile, readdir, stat } from "node:fs/promises";
import { APP_SPACE_ID, CONTRACT_SNAPSHOTS_DIRNAME } from "@prisma-next/framework-components/control";
//#region src/space-layout.ts
/**
* Pattern a contract-space identifier must match. The constraint is
* filesystem-friendly: lowercase letters / digits / hyphen / underscore,
* starts with a letter, max 64 characters.
*/
const SPACE_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
function isValidSpaceId(spaceId) {
return SPACE_ID_PATTERN.test(spaceId);
}
function assertValidSpaceId(spaceId) {
if (!isValidSpaceId(spaceId)) throw errorInvalidSpaceId(spaceId);
}
/**
* Resolve the migrations subdirectory for a given contract space.
*
* Every contract space — including the app space (default `'app'`) —
* lands under `<projectMigrationsDir>/<spaceId>/`. The space id is
* validated against {@link SPACE_ID_PATTERN} because it becomes a
* filesystem directory name verbatim.
*
* `projectMigrationsDir` is the project's top-level `migrations/`
* directory; the helper does not assume anything about its absolute /
* relative shape and is symmetric with `pathe.join`.
*/
function spaceMigrationDirectory(projectMigrationsDir, spaceId) {
assertValidSpaceId(spaceId);
return join(projectMigrationsDir, spaceId);
}
/**
* Per-space subdirectory name reserved for the ref store
* (`migrations/<space>/<SPACE_REFS_DIRNAME>/*.json`). Single source of
* truth: every helper that composes a per-space refs path imports this
* constant, and the enumerator uses it (via
* {@link RESERVED_SPACE_SUBDIR_NAMES}) to exclude reserved names from
* the contract-space candidate list.
*/
const SPACE_REFS_DIRNAME = "refs";
/**
* Names reserved under `migrations/` that must never be enumerated as a
* phantom contract space: `SPACE_REFS_DIRNAME` (e.g. a top-level
* `migrations/refs/` left in the wrong place) and
* `CONTRACT_SNAPSHOTS_DIRNAME` (the migrations-root-wide contract
* snapshot store, `migrations/snapshots/`).
*/
const RESERVED_SPACE_SUBDIR_NAMES = /* @__PURE__ */ new Set([SPACE_REFS_DIRNAME, CONTRACT_SNAPSHOTS_DIRNAME]);
/**
* Resolve the per-space refs directory for `spaceMigrationsDir`
* (typically the value returned by {@link spaceMigrationDirectory}).
* Composes the canonical {@link SPACE_REFS_DIRNAME} so callers do not
* hard-code the literal.
*/
function spaceRefsDirectory(spaceMigrationsDir) {
return join(spaceMigrationsDir, SPACE_REFS_DIRNAME);
}
//#endregion
//#region src/read-contract-space-head-ref.ts
function hasErrnoCode$1(error, code) {
return error instanceof Error && error.code === code;
}
/**
* Read the head ref (`hash` + `invariants`) for a contract space from
* `<projectMigrationsDir>/<spaceId>/refs/head.json`.
*
* Returns `null` when the file does not exist (first emit). Surfaces
* `MIGRATION.INVALID_JSON` / `MIGRATION.INVALID_REF_FILE` on a corrupt
* `refs/head.json` so callers can distinguish "no head ref on disk"
* (returns `null`) from "head ref present but unreadable" (throws).
*
* Validates the space id against `[a-z][a-z0-9_-]{0,63}` for the same
* filesystem-safety reasons as the rest of the per-space helpers. The
* helper is uniform across the app and extension spaces.
*/
async function readContractSpaceHeadRef(projectMigrationsDir, spaceId) {
assertValidSpaceId(spaceId);
const filePath = join(spaceRefsDirectory(spaceMigrationDirectory(projectMigrationsDir, spaceId)), "head.json");
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
if (hasErrnoCode$1(error, "ENOENT")) return null;
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (e) {
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
}
if (typeof parsed !== "object" || parsed === null) throw errorInvalidRefFile(filePath, "expected an object");
const obj = parsed;
if (typeof obj.hash !== "string") throw errorInvalidRefFile(filePath, "expected an object with a string `hash` field");
if (!Array.isArray(obj.invariants) || obj.invariants.some((value) => typeof value !== "string")) throw errorInvalidRefFile(filePath, "expected an object with an `invariants` array of strings");
return {
hash: obj.hash,
invariants: obj.invariants
};
}
//#endregion
//#region src/verify-contract-spaces.ts
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
/**
* List the per-space subdirectories under
* `<projectRoot>/migrations/`. Returns space-id directory names (sorted
* alphabetically) — i.e. any non-dot-prefixed, non-reserved
* ({@link RESERVED_SPACE_SUBDIR_NAMES}) subdirectory whose root does
* **not** contain a `migration.json` manifest. The manifest is the
* structural marker of a user-authored migration directory (see
* `readMigrationsDir` in `./io`); directory names themselves belong to
* the user and are not part of the contract. The reserved-name filter
* keeps `migrations/snapshots/` (the contract snapshot store) from ever
* being enumerated as a phantom contract space.
*
* Returns `[]` if the migrations directory does not exist (greenfield
* project).
*
* Reads only the user's repo. **No descriptor import.** The caller
* (verifier) feeds the result into {@link verifyContractSpaces} alongside
* the loaded-space set and the marker rows.
*/
async function listContractSpaceDirectories(projectMigrationsDir) {
let entries;
try {
entries = (await readdir(projectMigrationsDir, { withFileTypes: true })).map((d) => ({
name: d.name,
isDirectory: d.isDirectory()
}));
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return [];
throw error;
}
const namedCandidates = entries.filter((e) => e.isDirectory).map((e) => e.name).filter((name) => !name.startsWith(".")).filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name)).sort();
return (await Promise.all(namedCandidates.map(async (name) => {
try {
await stat(join(projectMigrationsDir, name, MANIFEST_FILE));
return {
name,
isMigrationDir: true
};
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return {
name,
isMigrationDir: false
};
throw error;
}
}))).filter((c) => !c.isMigrationDir).map((c) => c.name);
}
/**
* Pure structural verifier for the per-space mechanism. Aggregates the
* three orphan / missing checks plus per-space hash and invariant
* comparison.
*
* Algorithm:
*
* - For every extension space declared in `loadedSpaces` (`'app'`
* excluded — the per-space verifier is scoped to extension spaces;
* the app is verified through the aggregate path):
* - If no contract-space dir on disk → `declaredButUnmigrated`.
* - Else if `markerRowsBySpace` lacks an entry → no violation here;
* the live-DB compare done outside this helper is where the
* absence shows up.
* - Else compare marker hash / invariants vs. on-disk head hash /
* invariants → `hashMismatch` / `invariantsMismatch` on drift.
* - For every contract-space dir on disk that is not in `loadedSpaces` →
* `orphanSpaceDir`.
* - For every marker row whose `space` is not in `loadedSpaces` →
* `orphanMarker`. The app-space marker is always loaded (`'app'` is
* in `loadedSpaces` by definition).
*
* Output is deterministic: violations are sorted first by `kind`
* (`declaredButUnmigrated` → `orphanMarker` → `orphanSpaceDir` →
* `hashMismatch` → `invariantsMismatch`) then by `spaceId`. Two callers
* passing equivalent inputs see byte-identical violation lists.
*
* Synchronous, pure, no I/O. **Does not import the extension descriptor**
* (the inputs are pre-resolved by the caller); the verifier reads only
* the user repo, not `node_modules`.
*/
function verifyContractSpaces(inputs) {
const violations = [];
for (const spaceId of [...inputs.loadedSpaces].sort()) {
if (spaceId === APP_SPACE_ID) continue;
if (!inputs.spaceDirsOnDisk.includes(spaceId)) {
violations.push({
kind: "declaredButUnmigrated",
spaceId,
remediation: `Extension '${spaceId}' is declared in extensionPacks but has not been emitted; run \`prisma-next migrate\`.`
});
continue;
}
const head = inputs.headRefsBySpace.get(spaceId);
const marker = inputs.markerRowsBySpace.get(spaceId);
if (!head || !marker) continue;
if (head.hash !== marker.hash) {
violations.push({
kind: "hashMismatch",
spaceId,
priorHeadHash: head.hash,
markerHash: marker.hash,
remediation: `Marker row for space '${spaceId}' is keyed at ${marker.hash}, but the on-disk ${join("migrations", spaceId, "contract.json")} resolves to ${head.hash}. Run \`prisma-next db update\` to advance the database, or \`prisma-next migrate\` if the descriptor was bumped without re-emitting.`
});
continue;
}
const onDiskInvariants = [...head.invariants].sort();
const markerInvariants = new Set(marker.invariants);
const missing = onDiskInvariants.filter((id) => !markerInvariants.has(id));
if (missing.length > 0) violations.push({
kind: "invariantsMismatch",
spaceId,
onDiskInvariants,
markerInvariants: [...marker.invariants].sort(),
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.`
});
}
for (const dir of [...inputs.spaceDirsOnDisk].sort()) if (!inputs.loadedSpaces.has(dir)) violations.push({
kind: "orphanSpaceDir",
spaceId: dir,
remediation: `Orphan contract-space directory \`${join("migrations", dir)}/\` for an extension not in extensionPacks; remove the directory or re-add the extension.`
});
for (const space of [...inputs.markerRowsBySpace.keys()].sort()) if (!inputs.loadedSpaces.has(space)) violations.push({
kind: "orphanMarker",
spaceId: space,
remediation: `Orphan marker row for space '${space}' (no longer in extensionPacks); remediation: manually delete the row from \`prisma_contract.marker\`.`
});
if (violations.length === 0) return { ok: true };
const kindOrder = {
declaredButUnmigrated: 0,
orphanMarker: 1,
orphanSpaceDir: 2,
hashMismatch: 3,
invariantsMismatch: 4
};
violations.sort((a, b) => {
const k = kindOrder[a.kind] - kindOrder[b.kind];
if (k !== 0) return k;
if (a.spaceId < b.spaceId) return -1;
if (a.spaceId > b.spaceId) return 1;
return 0;
});
return {
ok: false,
violations
};
}
//#endregion
export { RESERVED_SPACE_SUBDIR_NAMES as a, isValidSpaceId as c, APP_SPACE_ID as i, spaceMigrationDirectory as l, verifyContractSpaces as n, SPACE_REFS_DIRNAME as o, readContractSpaceHeadRef as r, assertValidSpaceId as s, listContractSpaceDirectories as t, spaceRefsDirectory as u };
//# sourceMappingURL=verify-contract-spaces-DbLI1miK.mjs.map
{"version":3,"file":"verify-contract-spaces-DbLI1miK.mjs","names":["hasErrnoCode"],"sources":["../src/space-layout.ts","../src/read-contract-space-head-ref.ts","../src/verify-contract-spaces.ts"],"sourcesContent":["import {\n APP_SPACE_ID,\n CONTRACT_SNAPSHOTS_DIRNAME,\n} 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 */\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 * Every contract space — including the app space (default `'app'`) —\n * lands under `<projectMigrationsDir>/<spaceId>/`. The space id is\n * validated against {@link SPACE_ID_PATTERN} because it becomes a\n * 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 assertValidSpaceId(spaceId);\n return join(projectMigrationsDir, spaceId);\n}\n\n/**\n * Per-space subdirectory name reserved for the ref store\n * (`migrations/<space>/<SPACE_REFS_DIRNAME>/*.json`). Single source of\n * truth: every helper that composes a per-space refs path imports this\n * constant, and the enumerator uses it (via\n * {@link RESERVED_SPACE_SUBDIR_NAMES}) to exclude reserved names from\n * the contract-space candidate list.\n */\nexport const SPACE_REFS_DIRNAME = 'refs';\n\n/**\n * Names reserved under `migrations/` that must never be enumerated as a\n * phantom contract space: `SPACE_REFS_DIRNAME` (e.g. a top-level\n * `migrations/refs/` left in the wrong place) and\n * `CONTRACT_SNAPSHOTS_DIRNAME` (the migrations-root-wide contract\n * snapshot store, `migrations/snapshots/`).\n */\nexport const RESERVED_SPACE_SUBDIR_NAMES: ReadonlySet<string> = new Set([\n SPACE_REFS_DIRNAME,\n CONTRACT_SNAPSHOTS_DIRNAME,\n]);\n\n/**\n * Resolve the per-space refs directory for `spaceMigrationsDir`\n * (typically the value returned by {@link spaceMigrationDirectory}).\n * Composes the canonical {@link SPACE_REFS_DIRNAME} so callers do not\n * hard-code the literal.\n */\nexport function spaceRefsDirectory(spaceMigrationsDir: string): string {\n return join(spaceMigrationsDir, SPACE_REFS_DIRNAME);\n}\n","import { readFile } from 'node:fs/promises';\nimport type { ContractSpaceHeadRef } from '@prisma-next/framework-components/control';\nimport { join } from 'pathe';\nimport { errorInvalidJson, errorInvalidRefFile } from './errors';\nimport { assertValidSpaceId, spaceMigrationDirectory, spaceRefsDirectory } from './space-layout';\n\nexport type { ContractSpaceHeadRef };\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 head ref (`hash` + `invariants`) for a contract space from\n * `<projectMigrationsDir>/<spaceId>/refs/head.json`.\n *\n * Returns `null` when the file does not exist (first emit). Surfaces\n * `MIGRATION.INVALID_JSON` / `MIGRATION.INVALID_REF_FILE` on a corrupt\n * `refs/head.json` so callers can distinguish \"no head ref on disk\"\n * (returns `null`) from \"head ref present but unreadable\" (throws).\n *\n * Validates the space id against `[a-z][a-z0-9_-]{0,63}` for the same\n * filesystem-safety reasons as the rest of the per-space helpers. The\n * helper is uniform across the app and extension spaces.\n */\nexport async function readContractSpaceHeadRef(\n projectMigrationsDir: string,\n spaceId: string,\n): Promise<ContractSpaceHeadRef | null> {\n assertValidSpaceId(spaceId);\n\n const filePath = join(\n spaceRefsDirectory(spaceMigrationDirectory(projectMigrationsDir, spaceId)),\n 'head.json',\n );\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 (typeof parsed !== 'object' || parsed === null) {\n throw errorInvalidRefFile(filePath, 'expected an object');\n }\n const obj = parsed as { hash?: unknown; invariants?: unknown };\n if (typeof obj.hash !== 'string') {\n throw errorInvalidRefFile(filePath, 'expected an object with a string `hash` field');\n }\n if (!Array.isArray(obj.invariants) || obj.invariants.some((value) => typeof value !== 'string')) {\n throw errorInvalidRefFile(filePath, 'expected an object with an `invariants` array of strings');\n }\n\n return { hash: obj.hash, invariants: obj.invariants as readonly string[] };\n}\n","import { readdir, stat } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { MANIFEST_FILE } from './io';\nimport { APP_SPACE_ID, RESERVED_SPACE_SUBDIR_NAMES } 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 subdirectories under\n * `<projectRoot>/migrations/`. Returns space-id directory names (sorted\n * alphabetically) — i.e. any non-dot-prefixed, non-reserved\n * ({@link RESERVED_SPACE_SUBDIR_NAMES}) subdirectory whose root does\n * **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. The reserved-name filter\n * keeps `migrations/snapshots/` (the contract snapshot store) from ever\n * being enumerated as a phantom contract space.\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 */\nexport async function listContractSpaceDirectories(\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 .filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name))\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 * On-disk 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 artifacts and the live DB\n * marker.\n */\nexport interface ContractSpaceHeadRecord {\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 before\n * 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 * Per-space subdirectories observed under\n * `<projectRoot>/migrations/`. Resolved via\n * {@link listContractSpaceDirectories}.\n */\n readonly spaceDirsOnDisk: readonly string[];\n\n /**\n * Head ref per space, keyed by space id. Caller reads\n * `<projectRoot>/migrations/<space-id>/contract.json` and\n * `<projectRoot>/migrations/<space-id>/refs/head.json` to construct\n * this map. Spaces with no contract-space dir on disk simply omit a\n * map entry.\n */\n readonly headRefsBySpace: ReadonlyMap<string, ContractSpaceHeadRecord>;\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: 'orphanSpaceDir';\n readonly spaceId: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'hashMismatch';\n readonly spaceId: string;\n readonly priorHeadHash: string;\n readonly markerHash: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'invariantsMismatch';\n readonly spaceId: string;\n readonly onDiskInvariants: 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 plus per-space hash and invariant\n * comparison.\n *\n * Algorithm:\n *\n * - For every extension space declared in `loadedSpaces` (`'app'`\n * excluded — the per-space verifier is scoped to extension spaces;\n * the app is verified through the aggregate path):\n * - If no contract-space dir on disk → `declaredButUnmigrated`.\n * - Else if `markerRowsBySpace` lacks an entry → no violation here;\n * the live-DB compare done outside this helper is where the\n * absence shows up.\n * - Else compare marker hash / invariants vs. on-disk head hash /\n * invariants → `hashMismatch` / `invariantsMismatch` on drift.\n * - For every contract-space dir on disk that is not in `loadedSpaces` →\n * `orphanSpaceDir`.\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: violations are sorted first by `kind`\n * (`declaredButUnmigrated` → `orphanMarker` → `orphanSpaceDir` →\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); the verifier reads only\n * the user repo, not `node_modules`.\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.spaceDirsOnDisk.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 head = inputs.headRefsBySpace.get(spaceId);\n const marker = inputs.markerRowsBySpace.get(spaceId);\n if (!head || !marker) {\n continue;\n }\n\n if (head.hash !== marker.hash) {\n violations.push({\n kind: 'hashMismatch',\n spaceId,\n priorHeadHash: head.hash,\n markerHash: marker.hash,\n remediation: `Marker row for space '${spaceId}' is keyed at ${marker.hash}, but the on-disk ${join('migrations', spaceId, 'contract.json')} resolves to ${head.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 onDiskInvariants = [...head.invariants].sort();\n const markerInvariants = new Set(marker.invariants);\n const missing = onDiskInvariants.filter((id) => !markerInvariants.has(id));\n if (missing.length > 0) {\n violations.push({\n kind: 'invariantsMismatch',\n spaceId,\n onDiskInvariants,\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.spaceDirsOnDisk].sort()) {\n if (!inputs.loadedSpaces.has(dir)) {\n violations.push({\n kind: 'orphanSpaceDir',\n spaceId: dir,\n remediation: `Orphan contract-space 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 orphanSpaceDir: 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 k;\n if (a.spaceId < b.spaceId) return -1;\n if (a.spaceId > b.spaceId) return 1;\n return 0;\n });\n\n return { ok: false, violations };\n}\n"],"mappings":";;;;;;;;;;;AAuBA,MAAM,mBAAmB;AAEzB,SAAgB,eAAe,SAA0C;CACvE,OAAO,iBAAiB,KAAK,OAAO;AACtC;AAEA,SAAgB,mBAAmB,SAAkD;CACnF,IAAI,CAAC,eAAe,OAAO,GACzB,MAAM,oBAAoB,OAAO;AAErC;;;;;;;;;;;;;AAcA,SAAgB,wBAAwB,sBAA8B,SAAyB;CAC7F,mBAAmB,OAAO;CAC1B,OAAO,KAAK,sBAAsB,OAAO;AAC3C;;;;;;;;;AAUA,MAAa,qBAAqB;;;;;;;;AASlC,MAAa,8CAAmD,IAAI,IAAI,CACtE,oBACA,0BACF,CAAC;;;;;;;AAQD,SAAgB,mBAAmB,oBAAoC;CACrE,OAAO,KAAK,oBAAoB,kBAAkB;AACpD;;;AC1EA,SAASA,eAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;;;;;;;;;;;;;;AAeA,eAAsB,yBACpB,sBACA,SACsC;CACtC,mBAAmB,OAAO;CAE1B,MAAM,WAAW,KACf,mBAAmB,wBAAwB,sBAAsB,OAAO,CAAC,GACzE,WACF;CAEA,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,SAAS,UAAU,OAAO;CACxC,SAAS,OAAO;EACd,IAAIA,eAAa,OAAO,QAAQ,GAC9B,OAAO;EAET,MAAM;CACR;CAEA,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,SAAS,GAAG;EACV,MAAM,iBAAiB,UAAU,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;CAC7E;CAEA,IAAI,OAAO,W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,CAAC,KAAK,GACjD,IAAI,CAAC,OAAO,aAAa,IAAI,GAAG,GAC9B,WAAW,KAAK;EACd,MAAM;EACN,SAAS;EACT,aAAa,qCAAqC,KAAK,cAAc,GAAG,EAAE;CAC5E,CAAC;CAIL,KAAK,MAAM,SAAS,CAAC,GAAG,OAAO,kBAAkB,KAAK,CAAC,CAAC,CAAC,KAAK,GAC5D,IAAI,CAAC,OAAO,aAAa,IAAI,KAAK,GAChC,WAAW,KAAK;EACd,MAAM;EACN,SAAS;EACT,aAAa,gCAAgC,MAAM;CACrD,CAAC;CAIL,IAAI,WAAW,WAAW,GACxB,OAAO,EAAE,IAAI,KAAK;CAGpB,MAAM,YAA4D;EAChE,uBAAuB;EACvB,cAAc;EACd,gBAAgB;EAChB,cAAc;EACd,oBAAoB;CACtB;CAEA,WAAW,MAAM,GAAG,MAAM;EACxB,MAAM,IAAI,UAAU,EAAE,QAAQ,UAAU,EAAE;EAC1C,IAAI,MAAM,GAAG,OAAO;EACpB,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,OAAO;CACT,CAAC;CAED,OAAO;EAAE,IAAI;EAAO;CAAW;AACjC"}
//#region src/verify-contract-spaces.d.ts
/**
* List the per-space subdirectories under
* `<projectRoot>/migrations/`. Returns space-id directory names (sorted
* alphabetically) — i.e. any non-dot-prefixed, non-reserved
* ({@link RESERVED_SPACE_SUBDIR_NAMES}) subdirectory whose root does
* **not** contain a `migration.json` manifest. The manifest is the
* structural marker of a user-authored migration directory (see
* `readMigrationsDir` in `./io`); directory names themselves belong to
* the user and are not part of the contract. The reserved-name filter
* keeps `migrations/snapshots/` (the contract snapshot store) from ever
* being enumerated as a phantom contract space.
*
* Returns `[]` if the migrations directory does not exist (greenfield
* project).
*
* Reads only the user's repo. **No descriptor import.** The caller
* (verifier) feeds the result into {@link verifyContractSpaces} alongside
* the loaded-space set and the marker rows.
*/
declare function listContractSpaceDirectories(projectMigrationsDir: string): Promise<readonly string[]>;
/**
* On-disk head value (`(hash, invariants)`) for one contract space.
* The verifier compares this against the marker row for the same space
* to detect drift between the user-emitted artifacts and the live DB
* marker.
*/
interface ContractSpaceHeadRecord {
readonly hash: string;
readonly invariants: readonly string[];
}
/**
* Marker row read from `prisma_contract.marker` (one per `space`).
* Caller resolves these via the family runtime's marker reader before
* invoking {@link verifyContractSpaces}.
*/
interface SpaceMarkerRecord {
readonly hash: string;
readonly invariants: readonly string[];
}
interface VerifyContractSpacesInputs {
/**
* Set of contract spaces the project declares: `'app'` plus each
* extension space in `extensionPacks`. The caller's discovery path
* never reads the extension descriptor module — it walks the
* `extensionPacks` configuration in `prisma-next.config.ts` for the
* space ids.
*/
readonly loadedSpaces: ReadonlySet<string>;
/**
* Per-space subdirectories observed under
* `<projectRoot>/migrations/`. Resolved via
* {@link listContractSpaceDirectories}.
*/
readonly spaceDirsOnDisk: readonly string[];
/**
* Head ref per space, keyed by space id. Caller reads
* `<projectRoot>/migrations/<space-id>/contract.json` and
* `<projectRoot>/migrations/<space-id>/refs/head.json` to construct
* this map. Spaces with no contract-space dir on disk simply omit a
* map entry.
*/
readonly headRefsBySpace: ReadonlyMap<string, ContractSpaceHeadRecord>;
/**
* Marker rows keyed by `space`. Caller reads them from the
* `prisma_contract.marker` table.
*/
readonly markerRowsBySpace: ReadonlyMap<string, SpaceMarkerRecord>;
}
type SpaceVerifierViolation = {
readonly kind: 'declaredButUnmigrated';
readonly spaceId: string;
readonly remediation: string;
} | {
readonly kind: 'orphanMarker';
readonly spaceId: string;
readonly remediation: string;
} | {
readonly kind: 'orphanSpaceDir';
readonly spaceId: string;
readonly remediation: string;
} | {
readonly kind: 'hashMismatch';
readonly spaceId: string;
readonly priorHeadHash: string;
readonly markerHash: string;
readonly remediation: string;
} | {
readonly kind: 'invariantsMismatch';
readonly spaceId: string;
readonly onDiskInvariants: readonly string[];
readonly markerInvariants: readonly string[];
readonly remediation: string;
};
type VerifyContractSpacesResult = {
readonly ok: true;
} | {
readonly ok: false;
readonly violations: readonly SpaceVerifierViolation[];
};
/**
* Pure structural verifier for the per-space mechanism. Aggregates the
* three orphan / missing checks plus per-space hash and invariant
* comparison.
*
* Algorithm:
*
* - For every extension space declared in `loadedSpaces` (`'app'`
* excluded — the per-space verifier is scoped to extension spaces;
* the app is verified through the aggregate path):
* - If no contract-space dir on disk → `declaredButUnmigrated`.
* - Else if `markerRowsBySpace` lacks an entry → no violation here;
* the live-DB compare done outside this helper is where the
* absence shows up.
* - Else compare marker hash / invariants vs. on-disk head hash /
* invariants → `hashMismatch` / `invariantsMismatch` on drift.
* - For every contract-space dir on disk that is not in `loadedSpaces` →
* `orphanSpaceDir`.
* - For every marker row whose `space` is not in `loadedSpaces` →
* `orphanMarker`. The app-space marker is always loaded (`'app'` is
* in `loadedSpaces` by definition).
*
* Output is deterministic: violations are sorted first by `kind`
* (`declaredButUnmigrated` → `orphanMarker` → `orphanSpaceDir` →
* `hashMismatch` → `invariantsMismatch`) then by `spaceId`. Two callers
* passing equivalent inputs see byte-identical violation lists.
*
* Synchronous, pure, no I/O. **Does not import the extension descriptor**
* (the inputs are pre-resolved by the caller); the verifier reads only
* the user repo, not `node_modules`.
*/
declare function verifyContractSpaces(inputs: VerifyContractSpacesInputs): VerifyContractSpacesResult;
//#endregion
export { VerifyContractSpacesResult as a, VerifyContractSpacesInputs as i, SpaceMarkerRecord as n, listContractSpaceDirectories as o, SpaceVerifierViolation as r, verifyContractSpaces as s, ContractSpaceHeadRecord as t };
//# sourceMappingURL=verify-contract-spaces-DlEGEbW3.d.mts.map
{"version":3,"file":"verify-contract-spaces-DlEGEbW3.d.mts","names":[],"sources":["../src/verify-contract-spaces.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;iBA4BsB,6BACpB,+BACC;;;;;;;UA0Cc;WACN;WACA;;;;;;;UAQM;WACN;WACA;;UAGM;;;;;;;;WAQN,cAAc;;;;;;WAOd;;;;;;;;WASA,iBAAiB,oBAAoB;;;;;WAMrC,mBAAmB,oBAAoB;;KAGtC;WAEG;WACA;WACA;;WAGA;WACA;WACA;;WAGA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;KAGH;WACG;;WACA;WAAoB,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCxC,qBACd,QAAQ,6BACP"}
import { randomBytes } from 'node:crypto';
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import {
CONTRACT_SNAPSHOTS_DIRNAME,
storageHashHex,
} from '@prisma-next/framework-components/control';
import { canonicalizeJson } from '@prisma-next/framework-components/utils';
import { blindCast } from '@prisma-next/utils/casts';
import { join, relative } from 'pathe';
import {
errorContractSnapshotHashMismatch,
errorContractSnapshotMissing,
errorInvalidJson,
} from './errors';
const CONTRACT_JSON_FILE = 'contract.json';
const CONTRACT_DTS_FILE = 'contract.d.ts';
function hasErrnoCode(error: unknown, code: string): boolean {
return (
error instanceof Error &&
blindCast<
{ code?: string },
'Node fs errors carry an errno string `code` absent from the Error type'
>(error).code === code
);
}
async function directoryExists(p: string): Promise<boolean> {
try {
return (await stat(p)).isDirectory();
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) return false;
throw error;
}
}
export function contractSnapshotDir(migrationsDir: string, storageHash: string): string {
return join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME, storageHashHex(storageHash));
}
export interface ContractSnapshotInput {
readonly contractJson: unknown;
readonly contractDts: string;
}
export async function writeContractSnapshot(
migrationsDir: string,
storageHash: string,
input: ContractSnapshotInput,
): Promise<{ readonly written: boolean; readonly dir: string }> {
const dir = contractSnapshotDir(migrationsDir, storageHash);
// contractJson is unknown JSON; only storage.storageHash is read, to check
// it against the hash the snapshot is being written under.
const contractStorage = blindCast<
{ storage?: { storageHash?: unknown } },
'contractJson is unknown JSON; only the storage.storageHash field is read here'
>(input.contractJson);
const actualStorageHash = contractStorage.storage?.storageHash;
if (actualStorageHash !== storageHash) {
throw errorContractSnapshotHashMismatch(
storageHash,
typeof actualStorageHash === 'string' ? actualStorageHash : String(actualStorageHash),
dir,
);
}
if (await directoryExists(dir)) {
return { written: false, dir };
}
const snapshotsDir = join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME);
const tmpDir = join(
snapshotsDir,
`.tmp-${storageHashHex(storageHash)}-${Date.now()}-${randomBytes(4).toString('hex')}`,
);
await mkdir(tmpDir, { recursive: true });
const jsonContent = `${canonicalizeJson(input.contractJson)}\n`;
const dtsContent = input.contractDts.endsWith('\n')
? input.contractDts
: `${input.contractDts}\n`;
try {
await writeFile(join(tmpDir, CONTRACT_JSON_FILE), jsonContent);
await writeFile(join(tmpDir, CONTRACT_DTS_FILE), dtsContent);
await rename(tmpDir, dir);
} catch (error) {
await rm(tmpDir, { recursive: true, force: true });
if (hasErrnoCode(error, 'EEXIST') || hasErrnoCode(error, 'ENOTEMPTY')) {
return { written: false, dir };
}
throw error;
}
return { written: true, dir };
}
export async function readContractSnapshotJson(
migrationsDir: string,
storageHash: string,
): Promise<unknown> {
const jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);
let raw: string;
try {
raw = await readFile(jsonPath, 'utf-8');
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) {
throw errorContractSnapshotMissing(storageHash, jsonPath);
}
throw error;
}
try {
return JSON.parse(raw);
} catch (e) {
throw errorInvalidJson(jsonPath, e instanceof Error ? e.message : String(e));
}
}
/**
* Tolerant read: a missing store entry (ENOENT), an unparseable
* `contract.json`, the JSON literal `null`, or a `storageHash` that isn't a
* well-formed `sha256:<64hex>` value all resolve to `undefined` rather than
* throwing — parity with the catch-all tolerance of the pre-store
* `readEndContractJson` (`io.ts`), which never validated the hash it was
* keyed by either. Any other fs error (e.g. `EACCES` on a present-but-
* unreadable file) propagates rather than silently loading a contract-less
* package.
*/
export async function readContractSnapshotJsonTolerant(
migrationsDir: string,
storageHash: string,
): Promise<unknown | undefined> {
let jsonPath: string;
try {
jsonPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_JSON_FILE);
} catch {
return undefined;
}
let raw: string;
try {
raw = await readFile(jsonPath, 'utf-8');
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) {
return undefined;
}
throw error;
}
try {
const parsed: unknown = JSON.parse(raw);
return parsed === null ? undefined : parsed;
} catch {
return undefined;
}
}
export async function readContractSnapshotDts(
migrationsDir: string,
storageHash: string,
): Promise<string> {
const dtsPath = join(contractSnapshotDir(migrationsDir, storageHash), CONTRACT_DTS_FILE);
try {
return await readFile(dtsPath, 'utf-8');
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) {
throw errorContractSnapshotMissing(storageHash, dtsPath);
}
throw error;
}
}
export function snapshotsImportPathFrom(packageDir: string, migrationsDir: string): string {
const storeDir = join(migrationsDir, CONTRACT_SNAPSHOTS_DIRNAME);
return relative(packageDir, storeDir).split('\\').join('/');
}
import { mkdir, writeFile } from 'node:fs/promises';
import { canonicalizeJson } from '@prisma-next/framework-components/utils';
import { join } from 'pathe';
import { writeContractSnapshot } from './contract-snapshot-store';
import type { ContractSpaceHeadRef } from './read-contract-space-head-ref';
import { assertValidSpaceId, spaceRefsDirectory } from './space-layout';
/**
* Inputs for {@link emitContractSpaceArtifacts}.
*
* - `contract` is the canonical contract value the framework just emitted
* for the space; it is serialised through {@link canonicalizeJson}, so
* it must be a JSON-compatible value (objects / arrays / primitives).
* Typed as `unknown` rather than the SQL-family `Contract<SqlStorage>`
* to keep `migration-tools` framework-neutral; SQL-family callers pass
* their typed value through unchanged.
*
* - `contractDts` is the pre-rendered `.d.ts` text. Rendering happens in
* the SQL family (which owns the codec / typemap input the renderer
* needs), so this helper accepts the text verbatim and writes it out
* without further transformation.
*
* - `headRef` is the head reference for the space.
* `invariants` are sorted alphabetically before serialisation so two
* callers passing the same set in different orders produce
* byte-identical `refs/head.json`.
*/
export interface ContractSpaceArtifactInputs {
readonly contract: unknown;
readonly contractDts: string;
readonly headRef: ContractSpaceHeadRef;
}
/**
* Emit the per-space artifacts — the head contract snapshot (written into
* the migrations-root-wide `snapshots/` store, keyed by `headRef.hash`) and
* `refs/head.json` — under `<projectMigrationsDir>/<spaceId>/`.
*
* The head contract snapshot is write-if-absent (see
* {@link writeContractSnapshot}): a changed extension contract has a new
* hash, so it lands as a new store entry; an unchanged hash means identical
* canonical content already sits there. `refs/head.json` stays
* always-overwrite: the framework owns it, so running `migrate` twice with
* the same inputs is a no-op observably (idempotent), but the helper does
* not check pre-existing contents — re-emit always wins.
*
* Path layout matches the convention in
* [`spaceMigrationDirectory`](./space-layout.ts). The space id is
* validated against `[a-z][a-z0-9_-]{0,63}` via
* {@link assertValidSpaceId} for filesystem-safety reasons; the helper
* accepts every space uniformly (including the app space, default
* `'app'`).
*
* The migrations directory and space subdirectory are created if they
* do not yet exist (`mkdir { recursive: true }`).
*/
export async function emitContractSpaceArtifacts(
projectMigrationsDir: string,
spaceId: string,
inputs: ContractSpaceArtifactInputs,
): Promise<void> {
assertValidSpaceId(spaceId);
const dir = join(projectMigrationsDir, spaceId);
const refsDir = spaceRefsDirectory(dir);
await mkdir(refsDir, { recursive: true });
await writeContractSnapshot(projectMigrationsDir, inputs.headRef.hash, {
contractJson: inputs.contract,
contractDts: inputs.contractDts,
});
const sortedInvariants = [...inputs.headRef.invariants].sort();
const headJson = canonicalizeJson({
hash: inputs.headRef.hash,
invariants: sortedInvariants,
});
await writeFile(join(refsDir, 'head.json'), `${headJson}\n`);
}
export {
type ContractSnapshotInput,
contractSnapshotDir,
readContractSnapshotDts,
readContractSnapshotJson,
readContractSnapshotJsonTolerant,
snapshotsImportPathFrom,
writeContractSnapshot,
} from '../contract-snapshot-store';
+21
-17
import { n as OnDiskMigrationPackage } from "../package-CCIHXr9Z.mjs";
import { i as Refs, r as RefLoadProblem } from "../refs-BNCUu58Y.mjs";
import { t as ContractSpaceHeadRecord } from "../verify-contract-spaces-zYlAhXOK.mjs";
import { t as ContractSpaceHeadRecord } from "../verify-contract-spaces-DlEGEbW3.mjs";
import { n as MigrationGraph } from "../graph-bDjJ4GL9.mjs";
import { t as PackageLoadProblem } from "../io-DaQ5HRD7.mjs";
import { t as PackageLoadProblem } from "../io-Bbn6RnRd.mjs";
import { t as PathDecision } from "../migration-graph-DGZeXzav.mjs";
import { ControlAdapterInstance, ControlFamilyInstance, DiffSubjectGranularity, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlannerConflict, SchemaDiffIssue, SchemaEntityCoordinate, SchemaOwnership, TargetMigrationsCapability, VerifyDatabaseSchemaResult } from "@prisma-next/framework-components/control";
import { Result } from "@prisma-next/utils/result";
import { ControlAdapterInstance, ControlFamilyInstance, DiffSubjectGranularity, MigrationOperationPolicy, MigrationPlan, MigrationPlanOperation, MigrationPlannerConflict, SchemaDiffIssue, SchemaEntityCoordinate, SchemaOwnership, TargetMigrationsCapability, VerifyDatabaseSchemaResult } from "@prisma-next/framework-components/control";
import { Contract, StorageNamespace } from "@prisma-next/contract/types";

@@ -138,3 +138,2 @@ import { TargetBoundComponentDescriptor } from "@prisma-next/framework-components/components";

readonly provenance: 'graph-node';
readonly sourceDir: string;
readonly hash: string;

@@ -170,12 +169,14 @@ readonly contractJson: unknown;

* produced on first call and memoised. For the app it is the live
* contract the caller supplied; for an extension it is the on-disk
* `migrations/<spaceId>/contract.json` run through the family's
* `deserializeContract`. Throws if the on-disk contract is missing or
* undeserializable (surfaced as `contractUnreadable` by `checkIntegrity`
* under `checkContracts`); callers gate before querying it.
* contract the caller supplied; for an extension it is the contract
* snapshot store entry keyed by the space's head ref hash, run through
* the family's `deserializeContract`. Throws if the store entry is
* missing or undeserializable (surfaced as `contractUnreadable` by
* `checkIntegrity` under `checkContracts`); callers gate before
* querying it.
* - `contractAt(hash, opts?)`: materializes the contract at an arbitrary
* graph node — when `opts.refName` is set, prefer the ref's paired
* snapshot; else find the package whose `metadata.to === hash` and read
* its `end-contract.*`. Lazy per `(hash, refName?)` memoisation; throws
* typed {@link MigrationToolsError} values compatible with CLI mappers.
* the contract snapshot store entry keyed by that hash. Lazy per
* `(hash, refName?)` memoisation; throws typed {@link MigrationToolsError}
* values compatible with CLI mappers.
*/

@@ -257,3 +258,4 @@ interface AggregateContractSpace {

* the same resolution order as plan-time ref resolution: ref snapshot first
* (when `opts.refName` is set), else the matching package's `end-contract.*`.
* (when `opts.refName` is set), else the contract snapshot store entry
* keyed by the matching package's `to` hash.
*/

@@ -266,2 +268,3 @@ declare function createAggregateContractSpace(args: {

readonly refsDir: string;
readonly migrationsDir: string;
readonly resolveContract: () => Contract;

@@ -474,8 +477,8 @@ readonly deserializeContract: (raw: unknown) => Contract;

* Contract IR JSON of the edge's destination state, threaded from the
* bundle's on-disk `end-contract.json` snapshot (`resolveRecordedPath`)
* or the space's destination contract (`planFromDiff`). Runners persist it as the
* bundle's snapshot store entry (`resolveRecordedPath`) or the space's
* destination contract (`planFromDiff`). Runners persist it as the
* edge's ledger-linked contract row so database tooling can render
* model-level diffs per applied migration; an edge's *before* state is
* the previous row's snapshot by chain construction. Absent when the
* source bundle carries no snapshot.
* source bundle's snapshot store entry cannot be resolved.
*/

@@ -558,6 +561,7 @@ readonly destinationContractJson?: unknown;

* packages + refs + head refs). The app's *live* contract is not a disk
* artefact — in Prisma Next it is always compiled from the project's
* artifact — in Prisma Next it is always compiled from the project's
* central contract, so the caller always has it and threads it in as
* `appContract`. `deserializeContract` is held and called lazily only for
* the on-disk extension contracts (`migrations/<ext>/contract.json`).
* the extension contracts resolved from the contract snapshot store,
* keyed by each extension space's head ref hash.
*/

@@ -564,0 +568,0 @@ interface LoadAggregateInput {

@@ -1,1 +0,1 @@

{"version":3,"file":"aggregate.d.mts","names":[],"sources":["../../src/integrity-violation.ts","../../src/aggregate/types.ts","../../src/aggregate/aggregate.ts","../../src/aggregate/all-external.ts","../../src/aggregate/check-integrity.ts","../../src/aggregate/marker-types.ts","../../src/aggregate/planner-types.ts","../../src/aggregate/fabricated-migration-edge.ts","../../src/aggregate/loader.ts","../../src/aggregate/planner.ts","../../src/aggregate/strategies/resolve-recorded-path.ts","../../src/aggregate/unclaimed-elements.ts","../../src/aggregate/verifier.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAkBY;WAGG;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;WAGA;WACA;WACA;;WAEA;WAAiC;;WACjC;WAAoC;WAA0B;;WAE9D;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;;WAGA;WAAiC;;WACjC;WAAwC;;WAExC;WACA;WACA;WACA;;WAGA;WACA;WACA;;WAEA;WAAqC;WAA0B;;WAG/D;WACA;WACA;WACA;;;;;;;;;;;;;;UAeE;WACN;WACA;;;;;;;;;;;UAYM;;;;;;WAMN,8BAA8B;;;;;WAK9B;;;;UCrGM;WACN;;KAGC;WAEG;WACA;WACA;WACA;WACA,UAAU;;WAGV;WACA;WACA;WACA;WACA;WACA,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAuCR;WACN;WACA,mBAAmB;WACnB,MAAM;WACN,SAAS;EAClB,SAAS;EACT,YAAY;EACZ,WAAW,cAAc,OAAO,oBAAoB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAmC7C,+BAA+B;WACrC;WACA,KAAK;WACL,qBAAqB;EAC9B;EACA,SAAS;EACT,MAAM,aAAa;EACnB,mBAAmB;EACnB,eAAe,YAAY;EAC3B,gBAAgB,YAAY;EAC5B,eAAe,OAAO,iCAAiC;;;;;;;;;;;;iBCgDzC,eAAe,OAAO,yBAAyB;;;;;;;;;;;;;;iBAsB/C,6BAA6B;WAClC;WACA,mBAAmB;WACnB,MAAM;WACN,SAAS;WACT;WACA,uBAAuB;WACvB,sBAAsB,iBAAiB;IAC9C;;;;;;;;;;;iBAoDY,2BAA2B,WAAW;WAC3C;aAAoB,YAAY,SAAS,eAAe;;;;;;;;;;;iBAmCnD,6BAA6B;WAClC;WACA,KAAK;WACL,qBAAqB;WACrB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;;;;;;;;;;KCjCC;WACG;WAAqB,QAAQ;;WAC7B;;WACA;WAAgC;;UAE9B;WACN;WACA,OAAO;WACP,eAAe;;;;;;;WAOf;;;;;;;;;;;;;;;;;iBAkBK,oBAAoB,OAAO,4BAA4B;;;;;;;;;;KCnC3D,2BACV,OAAO,oBACJ;;;;;;;;KASO,8BAA8B,OAAO;;;;;;;;;UCJhC;WACN,WAAW;WACX,kBAAkB,oBAAoB;WACtC;WACA;;;;;;;;WAQA,uBACP,iBACA,OAAO,wBACP,+BACG;;;;;;;;WAQI,6BAA6B;;;;;;;;WAQ7B,qBAAqB;;;;;;;;KASpB;WACG;;WACA;;WAEA;WACA;WACA;;WAEA;WAAoC;;UAElC;WACN,UAAU,oBAAoB;WAC9B;aACE;aACA,KAAK;;;UAID;;;;;;;WAON,UAAU,oBAAoB;;;;;;;;WAQ9B;;UAGM;WACN,aAAa;WACb,aAAa;;KAGZ;WACD;WACA;;KAGC,iBAAiB,OAAO,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BrC,gBAAgB,OAAO,gBAAgB"}
{"version":3,"file":"aggregate.d.mts","names":[],"sources":["../../src/integrity-violation.ts","../../src/aggregate/types.ts","../../src/aggregate/aggregate.ts","../../src/aggregate/all-external.ts","../../src/aggregate/check-integrity.ts","../../src/aggregate/marker-types.ts","../../src/aggregate/planner-types.ts","../../src/aggregate/fabricated-migration-edge.ts","../../src/aggregate/loader.ts","../../src/aggregate/planner.ts","../../src/aggregate/strategies/resolve-recorded-path.ts","../../src/aggregate/unclaimed-elements.ts","../../src/aggregate/verifier.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAkBY;WAGG;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;WAGA;WACA;WACA;;WAEA;WAAiC;;WACjC;WAAoC;WAA0B;;WAE9D;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;;WAGA;WAAiC;;WACjC;WAAwC;;WAExC;WACA;WACA;WACA;;W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;;WAQI,6BAA6B;;;;;;;;WAQ7B,qBAAqB;;;;;;;;KASpB;WACG;;WACA;;WAEA;WACA;WACA;;WAEA;WAAoC;;UAElC;WACN,UAAU,oBAAoB;WAC9B;aACE;aACA,KAAK;;;UAID;;;;;;;WAON,UAAU,oBAAoB;;;;;;;;WAQ9B;;UAGM;WACN,aAAa;WACb,aAAa;;KAGZ;WACD;WACA;;KAGC,iBAAiB,OAAO,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BrC,gBAAgB,OAAO,gBAAgB"}

@@ -1,20 +0,17 @@

import { D as errorSnapshotMissing, S as errorMissingFile, f as errorInvalidJson, i as errorContractDeserializationFailed, l as errorHashNotInGraph, r as errorBundleNotFoundForGraphNode, t as MigrationToolsError } from "../errors-DIS_dcFJ.mjs";
import { s as readMigrationsDir } from "../io-CE79C4uK.mjs";
import { d as errorHashNotInGraph, i as errorContractDeserializationFailed, k as errorSnapshotMissing, r as errorBundleNotFoundForGraphNode, t as MigrationToolsError } from "../errors-DldT38lZ.mjs";
import { n as readContractSnapshotDts, r as readContractSnapshotJson, t as contractSnapshotDir } from "../contract-snapshot-store-DCFUkXwL.mjs";
import { s as readMigrationsDir } from "../io-H4a-OJHL.mjs";
import { t as EMPTY_CONTRACT_HASH } from "../constants-YnG8_EGO.mjs";
import { n as isGraphNode } from "../graph-membership-CNneL_Yy.mjs";
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-BXHOgdTg.mjs";
import { a as readRefsTolerant, t as HEAD_REF_NAME } from "../refs-CDIHeNcC.mjs";
import { r as readRefSnapshot } from "../snapshot-DiE5uFFJ.mjs";
import { a as APP_SPACE_ID, d as spaceRefsDirectory, i as readContractSpaceHeadRef, l as isValidSpaceId, n as listContractSpaceDirectories, o as RESERVED_SPACE_SUBDIR_NAMES, t as readContractSpaceContract, u as spaceMigrationDirectory } from "../read-contract-space-contract-DBW4-T5r.mjs";
import { n as isGraphNode } from "../graph-membership-DDYdPRwc.mjs";
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-k8O6g9j2.mjs";
import { a as readRefsTolerant, t as HEAD_REF_NAME } from "../refs-BI9kMF4i.mjs";
import { r as readRefSnapshot } from "../snapshot-ByKdh1GJ.mjs";
import { c as isValidSpaceId, i as APP_SPACE_ID, l as spaceMigrationDirectory, r as readContractSpaceHeadRef, t as listContractSpaceDirectories, u as spaceRefsDirectory } from "../verify-contract-spaces-DbLI1miK.mjs";
import { join } from "pathe";
import { readFile } from "node:fs/promises";
import { issueOutcome } from "@prisma-next/framework-components/control";
import { blindCast } from "@prisma-next/utils/casts";
import { notOk, ok } from "@prisma-next/utils/result";
import { issueOutcome } from "@prisma-next/framework-components/control";
import { UNBOUND_NAMESPACE_ID, coordinateKey, elementCoordinates, entityAt } from "@prisma-next/framework-components/ir";
import { effectiveControlPolicy } from "@prisma-next/contract/types";
import { blindCast } from "@prisma-next/utils/casts";
//#region src/aggregate/aggregate.ts
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
function contractAtMemoKey(hash, refName) {

@@ -31,34 +28,12 @@ return `${hash}\0${refName ?? ""}`;

}
async function readGraphNodeEndContract(packageDir, deserializeContract) {
const jsonPath = join(packageDir, "end-contract.json");
const dtsPath = join(packageDir, "end-contract.d.ts");
let rawJson;
try {
rawJson = await readFile(jsonPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile("end-contract.json", packageDir);
throw error;
}
let contractJson;
try {
contractJson = JSON.parse(rawJson);
} catch (error) {
throw errorInvalidJson(jsonPath, error instanceof Error ? error.message : String(error));
}
let contractDts;
try {
contractDts = await readFile(dtsPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile("end-contract.d.ts", packageDir);
throw error;
}
const contract = deserializeContractAtPath(jsonPath, contractJson, deserializeContract);
async function readGraphNodeEndContract(migrationsDir, hash, deserializeContract) {
const contractJson = await readContractSnapshotJson(migrationsDir, hash);
return {
contractJson,
contractDts,
contract
contractDts: await readContractSnapshotDts(migrationsDir, hash),
contract: deserializeContractAtPath(join(contractSnapshotDir(migrationsDir, hash), "contract.json"), contractJson, deserializeContract)
};
}
async function resolveContractAt(args) {
const { hash, opts, refsDir, packages, graph, deserializeContract } = args;
const { hash, opts, refsDir, migrationsDir, packages, graph, deserializeContract } = args;
const refName = opts?.refName;

@@ -79,2 +54,3 @@ if (refName !== void 0) {

hash,
migrationsDir,
packages,

@@ -88,2 +64,3 @@ deserializeContract,

hash,
migrationsDir,
packages,

@@ -95,6 +72,5 @@ deserializeContract

async function resolveGraphNodeContractAt(args) {
const { hash, packages, deserializeContract, explicitLabel } = args;
const matchingBundle = packages.find((pkg) => pkg.metadata.to === hash);
if (!matchingBundle) throw errorBundleNotFoundForGraphNode(hash, explicitLabel);
const { contractJson, contractDts, contract } = await readGraphNodeEndContract(matchingBundle.dirPath, deserializeContract);
const { hash, migrationsDir, packages, deserializeContract, explicitLabel } = args;
if (!packages.find((pkg) => pkg.metadata.to === hash)) throw errorBundleNotFoundForGraphNode(hash, explicitLabel);
const { contractJson, contractDts, contract } = await readGraphNodeEndContract(migrationsDir, hash, deserializeContract);
return {

@@ -105,4 +81,3 @@ hash,

contract,
provenance: "graph-node",
sourceDir: matchingBundle.dirPath
provenance: "graph-node"
};

@@ -133,6 +108,7 @@ }

* the same resolution order as plan-time ref resolution: ref snapshot first
* (when `opts.refName` is set), else the matching package's `end-contract.*`.
* (when `opts.refName` is set), else the contract snapshot store entry
* keyed by the matching package's `to` hash.
*/
function createAggregateContractSpace(args) {
const { spaceId, packages, refs, headRef, refsDir, resolveContract, deserializeContract } = args;
const { spaceId, packages, refs, headRef, refsDir, migrationsDir, resolveContract, deserializeContract } = args;
let graphMemo;

@@ -163,2 +139,3 @@ let contractMemo;

refsDir,
migrationsDir,
packages,

@@ -481,3 +458,3 @@ graph: spaceGraph(),

const spaceDir = spaceMigrationDirectory(migrationsDir, APP_SPACE_ID);
const { packages, problems } = await readMigrationsDir(spaceDir);
const { packages, problems } = await readMigrationsDir(spaceDir, { migrationsDir });
const { refs, problems: refProblems } = await readRefsTolerant(spaceRefsDirectory(spaceDir));

@@ -494,2 +471,3 @@ return {

refsDir: spaceRefsDirectory(spaceDir),
migrationsDir,
resolveContract: () => appContract,

@@ -505,3 +483,3 @@ deserializeContract

async function loadExtensionSpaces(migrationsDir, deserializeContract) {
const extensionIds = (await listContractSpaceDirectories(migrationsDir)).filter((name) => name !== APP_SPACE_ID).filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name)).filter(isValidSpaceId).sort();
const extensionIds = (await listContractSpaceDirectories(migrationsDir)).filter((name) => name !== APP_SPACE_ID).filter(isValidSpaceId).sort();
const states = [];

@@ -513,6 +491,6 @@ for (const spaceId of extensionIds) states.push(await loadExtensionSpace(migrationsDir, spaceId, deserializeContract));

const spaceDir = spaceMigrationDirectory(migrationsDir, spaceId);
const { packages, problems } = await readMigrationsDir(spaceDir);
const { packages, problems } = await readMigrationsDir(spaceDir, { migrationsDir });
const { refs, problems: refProblems } = await readRefsTolerant(spaceRefsDirectory(spaceDir));
const { headRef, problem: headRefProblem } = await readHeadRefTolerant(migrationsDir, spaceId);
const rawContract = await readRawContractDeferred(migrationsDir, spaceId);
const rawContract = await readRawContractDeferred(migrationsDir, spaceId, headRef);
return {

@@ -525,2 +503,3 @@ space: createAggregateContractSpace({

refsDir: spaceRefsDirectory(spaceDir),
migrationsDir,
resolveContract: () => deserializeContract(rawContract()),

@@ -571,10 +550,16 @@ deserializeContract

/**
* Read the raw on-disk contract eagerly (cheap I/O) but defer its
* (throwing) failure to call time, so a missing or unparseable
* `contract.json` becomes a `contract()` throw — surfaced as
* `contractUnreadable` — rather than a construction failure.
* Read the raw contract snapshot-store entry eagerly (cheap I/O) but defer
* its (throwing) failure to call time, so a missing or unparseable store
* entry becomes a `contract()` throw — surfaced as `contractUnreadable` —
* rather than a construction failure. When `headRef` is absent there is no
* hash to resolve against the store, so the deferred call always throws;
* `checkIntegrity` already reports that case as `headRefMissing`, and a
* `checkContracts` pass surfaces the same space as `contractUnreadable`.
*/
async function readRawContractDeferred(migrationsDir, spaceId) {
async function readRawContractDeferred(migrationsDir, spaceId, headRef) {
if (headRef === null) return () => {
throw new Error(`Contract space "${spaceId}" has no head ref; its contract cannot be resolved from the snapshot store without one.`);
};
try {
const raw = await readContractSpaceContract(migrationsDir, spaceId);
const raw = await readContractSnapshotJson(migrationsDir, headRef.hash);
return () => raw;

@@ -622,3 +607,4 @@ } catch (error) {

spaceId: input.space.spaceId,
ownership: input.ownership
ownership: input.ownership,
snapshotsImportPath: ""
});

@@ -625,0 +611,0 @@ if (plannerResult.kind === "failure") return {

@@ -66,4 +66,6 @@ //#region src/errors.d.ts

}): MigrationToolsError;
declare function errorContractSnapshotMissing(storageHash: string, expectedPath: string): MigrationToolsError;
declare function errorContractSnapshotHashMismatch(storageHash: string, actualHash: string, dir: string): MigrationToolsError;
//#endregion
export { MigrationToolsError, type NoInvariantPathStructuralEdge, errorDescriptorHeadHashMismatch, errorInvalidJson, errorNoInvariantPath, errorUnknownInvariant };
export { MigrationToolsError, type NoInvariantPathStructuralEdge, errorContractSnapshotHashMismatch, errorContractSnapshotMissing, errorDescriptorHeadHashMismatch, errorInvalidJson, errorNoInvariantPath, errorUnknownInvariant };
//# sourceMappingURL=errors.d.mts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"errors.d.mts","names":[],"sources":["../../src/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;cAoCa,4BAA4B;WAC9B;WACA;WACA;WACA;WACA,SAAS;cAGhB,cACA,iBACA;aACW;aACA;aACA,UAAU;;SAWhB,GAAG,iBAAiB,SAAS;;iBA0BtB,iBAAiB,kBAAkB,qBAAqB;iBAwDxD,gCAAgC;WACrC;WACA;WACA;IACP;;;;;;;;;;;;UAwLa;WACN;WACA;WACA;WACA;WACA;;iBAGK,qBAAqB;WAC1B;WACA;WACA;WACA,yBAAyB;IAChC;iBAqBY,sBAAsB;WAC3B;WACA;WACA;IACP"}
{"version":3,"file":"errors.d.mts","names":[],"sources":["../../src/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;cAoCa,4BAA4B;WAC9B;WACA;WACA;WACA;WACA,SAAS;cAGhB,cACA,iBACA;aACW;aACA;aACA,UAAU;;SAWhB,GAAG,iBAAiB,SAAS;;iBA0BtB,iBAAiB,kBAAkB,qBAAqB;iBAwDxD,gCAAgC;WACrC;WACA;WACA;IACP;;;;;;;;;;;;UAwLa;WACN;WACA;WACA;WACA;WACA;;iBAGK,qBAAqB;WAC1B;WACA;WACA;WACA,yBAAyB;IAChC;iBAqBY,sBAAsB;WAC3B;WACA;WACA;IACP;iBA0FY,6BACd,qBACA,uBACC;iBAYa,kCACd,qBACA,oBACA,cACC"}

@@ -1,2 +0,2 @@

import { O as errorUnknownInvariant, a as errorDescriptorHeadHashMismatch, f as errorInvalidJson, t as MigrationToolsError, w as errorNoInvariantPath } from "../errors-DIS_dcFJ.mjs";
export { MigrationToolsError, errorDescriptorHeadHashMismatch, errorInvalidJson, errorNoInvariantPath, errorUnknownInvariant };
import { A as errorUnknownInvariant, E as errorNoInvariantPath, a as errorContractSnapshotHashMismatch, m as errorInvalidJson, o as errorContractSnapshotMissing, s as errorDescriptorHeadHashMismatch, t as MigrationToolsError } from "../errors-DldT38lZ.mjs";
export { MigrationToolsError, errorContractSnapshotHashMismatch, errorContractSnapshotMissing, errorDescriptorHeadHashMismatch, errorInvalidJson, errorNoInvariantPath, errorUnknownInvariant };

@@ -1,2 +0,2 @@

import { n as validateInvariantId, t as deriveProvidedInvariants } from "../invariants-CH8ATaEp.mjs";
import { n as validateInvariantId, t as deriveProvidedInvariants } from "../invariants-BcT9Izto.mjs";
export { deriveProvidedInvariants, validateInvariantId };

@@ -1,2 +0,2 @@

import { a as materialiseExtensionMigrationPackageIfMissing, c as readMigrationsDir, d as writeMigrationPackage, i as formatMigrationDirName, l as writeMigrationMetadata, n as ReadMigrationsDirResult, o as materialiseMigrationPackage, r as copyFilesWithRename, s as readMigrationPackage, t as PackageLoadProblem, u as writeMigrationOps } from "../io-DaQ5HRD7.mjs";
import { a as materialiseExtensionMigrationPackageIfMissing, c as readMigrationsDir, d as writeMigrationPackage, i as formatMigrationDirName, l as writeMigrationMetadata, n as ReadMigrationsDirResult, o as materialiseMigrationPackage, r as copyFilesWithRename, s as readMigrationPackage, t as PackageLoadProblem, u as writeMigrationOps } from "../io-Bbn6RnRd.mjs";
export { type PackageLoadProblem, type ReadMigrationsDirResult, copyFilesWithRename, formatMigrationDirName, materialiseExtensionMigrationPackageIfMissing, materialiseMigrationPackage, readMigrationPackage, readMigrationsDir, writeMigrationMetadata, writeMigrationOps, writeMigrationPackage };

@@ -1,2 +0,2 @@

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-CE79C4uK.mjs";
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-H4a-OJHL.mjs";
export { copyFilesWithRename, formatMigrationDirName, materialiseExtensionMigrationPackageIfMissing, materialiseMigrationPackage, readMigrationPackage, readMigrationsDir, writeMigrationMetadata, writeMigrationOps, writeMigrationPackage };

@@ -1,3 +0,3 @@

import { n as isGraphNode, t as assertHashIsGraphNode } from "../graph-membership-CNneL_Yy.mjs";
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-BXHOgdTg.mjs";
import { n as isGraphNode, t as assertHashIsGraphNode } from "../graph-membership-DDYdPRwc.mjs";
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-k8O6g9j2.mjs";
export { assertHashIsGraphNode, detectCycles, detectOrphans, findLatestMigration, findLeaf, findPath, findPathWithDecision, findPathWithInvariants, findReachableLeaves, isGraphNode, reconstructGraph };

@@ -18,5 +18,6 @@ import { t as MigrationMetadata$1 } from "../metadata-DtStFLKa.mjs";

* one of two ways:
* - **Contract-derived (default):** assign the committed `start-contract.json`
* / `end-contract.json` imports to `startContractJson` / `endContractJson`;
* the concrete `describe()` below derives `to`/`from` from their
* - **Contract-derived (default):** assign the `contract.json` imports from
* the snapshot store (`migrations/snapshots/<hex>/contract.json`) to
* `startContractJson` / `endContractJson`; the concrete `describe()` below
* derives `to`/`from` from their
* `storage.storageHash`. The family bases additionally expose typed view

@@ -33,4 +34,4 @@ * getters (`startContract` / `endContract`) over the same JSON.

/**
* The migration's end-state contract JSON (the committed `end-contract.json`
* import). When set, the derived `describe()` reads `to` from its
* The migration's end-state contract JSON (the `contract.json` import from
* the snapshot store). When set, the derived `describe()` reads `to` from its
* `storage.storageHash`. Family bases build the typed `endContract` view from

@@ -51,4 +52,4 @@ * it. Optional so `describe()`-overriding migrations (no contract) compile.

/**
* The migration's start-state contract JSON (the committed
* `start-contract.json` import). Absent for a baseline migration (`from`
* The migration's start-state contract JSON (the `contract.json` import
* from the snapshot store). Absent for a baseline migration (`from`
* derives to `null`). Family bases build the typed `startContract` view from

@@ -55,0 +56,0 @@ * it.

@@ -1,1 +0,1 @@

{"version":3,"file":"migration.d.mts","names":[],"sources":["../../src/migration-base.ts"],"mappings":";;;;UAgBiB;WACN;WACA;;;;;;;;;;;;;;;;;;;;;;uBAiCW,UACpB,oBAAoB,yBAAyB,wBAC7C,mCACA,mCACA,eAAe,WAAW,UAC1B,aAAa,WAAW,qBACb;oBAEO;;;;;;;;;;;;;WAcT;aAA6B;eAAoB;;;;;;;;;WAQjD;aAA+B;eAAoB;;;;;;;;;;;;qBAWzC,OAAO,aAAa,WAAW;cAEtC,QAAQ,aAAa,WAAW;;;;;;;;eAW/B,wBAAwB,yBAAyB,QAAQ;;;;;;;;;;EAWtE,YAAY;MAaR;aAAqB;;MAKrB;aAA0B;;;;;;;;;;;;;;;;cAkBnB,uBAAuB;;mBAKf;mBACA;mBACA;cAFA,WAAW,WACX,mBACA,WAAW,kBAAkB;MAG5C,eAAe;MAWf,iBAAiB;;;;;;;;;iBAgBP,mBAAmB;;;;;;;;;;;;UAsBlB;WACN;WACA,UAAU;WACV;;;;;;;;;;;iBA4CW,wBACpB,UAAU,WACV,UAAU,QAAQ,8BACjB,QAAQ"}
{"version":3,"file":"migration.d.mts","names":[],"sources":["../../src/migration-base.ts"],"mappings":";;;;UAgBiB;WACN;WACA;;;;;;;;;;;;;;;;;;;;;;;uBAkCW,UACpB,oBAAoB,yBAAyB,wBAC7C,mCACA,mCACA,eAAe,WAAW,UAC1B,aAAa,WAAW,qBACb;oBAEO;;;;;;;;;;;;;WAcT;aAA6B;eAAoB;;;;;;;;;WAQjD;aAA+B;eAAoB;;;;;;;;;;;;qBAWzC,OAAO,aAAa,WAAW;cAEtC,QAAQ,aAAa,WAAW;;;;;;;;eAW/B,wBAAwB,yBAAyB,QAAQ;;;;;;;;;;EAWtE,YAAY;MAaR;aAAqB;;MAKrB;aAA0B;;;;;;;;;;;;;;;;cAkBnB,uBAAuB;;mBAKf;mBACA;mBACA;cAFA,WAAW,WACX,mBACA,WAAW,kBAAkB;MAG5C,eAAe;MAWf,iBAAiB;;;;;;;;;iBAgBP,mBAAmB;;;;;;;;;;;;UAsBlB;WACN;WACA,UAAU;WACV;;;;;;;;;;;iBA4CW,wBACpB,UAAU,WACV,UAAU,QAAQ,8BACjB,QAAQ"}

@@ -1,4 +0,4 @@

import { b as errorMigrationContractViewMissing, m as errorInvalidOperationEntry } from "../errors-DIS_dcFJ.mjs";
import { S as errorMigrationContractViewMissing, g as errorInvalidOperationEntry } from "../errors-DldT38lZ.mjs";
import { t as computeMigrationHash } from "../hash-BNCgfhir.mjs";
import { t as deriveProvidedInvariants } from "../invariants-CH8ATaEp.mjs";
import { t as deriveProvidedInvariants } from "../invariants-BcT9Izto.mjs";
import { t as MigrationOpSchema } from "../op-schema-BSVHzEQN.mjs";

@@ -22,5 +22,6 @@ import { type } from "arktype";

* one of two ways:
* - **Contract-derived (default):** assign the committed `start-contract.json`
* / `end-contract.json` imports to `startContractJson` / `endContractJson`;
* the concrete `describe()` below derives `to`/`from` from their
* - **Contract-derived (default):** assign the `contract.json` imports from
* the snapshot store (`migrations/snapshots/<hex>/contract.json`) to
* `startContractJson` / `endContractJson`; the concrete `describe()` below
* derives `to`/`from` from their
* `storage.storageHash`. The family bases additionally expose typed view

@@ -36,4 +37,4 @@ * getters (`startContract` / `endContract`) over the same JSON.

/**
* The migration's end-state contract JSON (the committed `end-contract.json`
* import). When set, the derived `describe()` reads `to` from its
* The migration's end-state contract JSON (the `contract.json` import from
* the snapshot store). When set, the derived `describe()` reads `to` from its
* `storage.storageHash`. Family bases build the typed `endContract` view from

@@ -50,4 +51,4 @@ * it. Optional so `describe()`-overriding migrations (no contract) compile.

/**
* The migration's start-state contract JSON (the committed
* `start-contract.json` import). Absent for a baseline migration (`from`
* The migration's start-state contract JSON (the `contract.json` import
* from the snapshot store). Absent for a baseline migration (`from`
* derives to `null`). Family bases build the typed `startContract` view from

@@ -54,0 +55,0 @@ * it.

@@ -1,1 +0,1 @@

{"version":3,"file":"migration.mjs","names":["#endView","#startView"],"sources":["../../src/migration-base.ts"],"sourcesContent":["import { realpathSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n ControlStack,\n MigrationPlan,\n MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport { type } from 'arktype';\nimport { errorInvalidOperationEntry, errorMigrationContractViewMissing } 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`.\n *\n * The from/to identities come from `describe()`. A migration provides them in\n * one of two ways:\n * - **Contract-derived (default):** assign the committed `start-contract.json`\n * / `end-contract.json` imports to `startContractJson` / `endContractJson`;\n * the concrete `describe()` below derives `to`/`from` from their\n * `storage.storageHash`. The family bases additionally expose typed view\n * getters (`startContract` / `endContract`) over the same JSON.\n * - **Override (e.g. extension migrations that carry no contract):** override\n * `describe()` directly; the override wins and the JSON fields are unused.\n *\n * The `Start` / `End` generics carry each migration's precise contract types so\n * the family-base view getters resolve to fully-typed views.\n */\nexport abstract class Migration<\n _TOperation extends MigrationPlanOperation = MigrationPlanOperation,\n TFamilyId extends string = string,\n TTargetId extends string = string,\n _Start extends Contract = Contract,\n _End extends Contract = Contract,\n> implements MigrationPlan\n{\n abstract readonly targetId: string;\n\n /**\n * The migration's end-state contract JSON (the committed `end-contract.json`\n * import). When set, the derived `describe()` reads `to` from its\n * `storage.storageHash`. Family bases build the typed `endContract` view from\n * it. Optional so `describe()`-overriding migrations (no contract) compile.\n *\n * Typed with a plain `storageHash: string`, not the branded\n * `StorageHashBase`, so a raw `contract.json` import — whose `storageHash`\n * is an untyped string literal — is assignable without a cast. The full\n * `Start`/`End` contract typing is applied downstream in the family bases'\n * view getters (via `<Family>ContractView.fromJson<…>`).\n */\n readonly endContractJson?: { readonly storage: { readonly storageHash: string } };\n\n /**\n * The migration's start-state contract JSON (the committed\n * `start-contract.json` import). Absent for a baseline migration (`from`\n * derives to `null`). Family bases build the typed `startContract` view from\n * it.\n */\n readonly startContractJson?: { readonly storage: { readonly storageHash: 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. Entries may be Promises\n * when the target requires async codec resolution (e.g. DDL literal defaults).\n */\n abstract get operations(): readonly (MigrationPlanOperation | Promise<MigrationPlanOperation>)[];\n\n /**\n * Metadata inputs used to build `migration.json` and to derive the plan's\n * origin/destination identities.\n *\n * Default derivation: `to = endContractJson.storage.storageHash`,\n * `from = startContractJson?.storage.storageHash ?? null`. A migration that\n * carries no contract JSON (e.g. an extension migration) must override this;\n * otherwise it throws, since `migration.json` requires a `to` identity.\n */\n describe(): MigrationMeta {\n const end = this.endContractJson;\n if (end === undefined) {\n throw new Error(\n 'Migration.describe(): provide endContractJson or override describe() — a migration needs a destination contract hash.',\n );\n }\n return {\n from: this.startContractJson?.storage.storageHash ?? null,\n to: end.storage.storageHash,\n };\n }\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 * Lazy-memoized `endContract` / `startContract` view accessors, one instance\n * held per migration. Each target base (`MongoMigration`, `SqliteMigration`,\n * `PostgresMigration`) creates one `MigrationContractViews` field from\n * `this` — passing its own `<Family>ContractView.fromJson<…>` as `fromJson`\n * and a name for error messages — and forwards its\n * `endContract`/`startContract` getters to it.\n *\n * `endContract` throws `MIGRATION.CONTRACT_VIEW_MISSING` when the migration\n * has no `endContractJson` (mirrors `describe()`'s own requirement).\n * `startContract` returns `null` for a baseline migration (no\n * `startContractJson`) instead of throwing.\n */\nexport class MigrationContractViews<TView> {\n #endView?: TView;\n #startView?: TView | null;\n\n constructor(\n private readonly migration: Migration,\n private readonly className: string,\n private readonly fromJson: (json: unknown) => TView,\n ) {}\n\n get endContract(): TView {\n if (this.#endView === undefined) {\n const json = this.migration.endContractJson;\n if (json === undefined) {\n throw errorMigrationContractViewMissing(this.className, 'endContract', 'endContractJson');\n }\n this.#endView = this.fromJson(json);\n }\n return this.#endView;\n }\n\n get startContract(): TView | null {\n if (this.#startView === undefined) {\n const json = this.migration.startContractJson;\n this.#startView = json === undefined ? null : this.fromJson(json);\n }\n return this.#startView;\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 async function buildMigrationArtifacts(\n instance: Migration,\n existing: Partial<MigrationMetadata> | null,\n): Promise<MigrationArtifacts> {\n const rawOps = instance.operations;\n if (!Array.isArray(rawOps)) {\n throw new Error('operations must be an array');\n }\n const ops = await Promise.all(rawOps);\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":";;;;;;;;AA0BA,MAAM,sBAAsB,KAAK;CAC/B,MAAM;CACN,IAAI;AACN,CAAC;;;;;;;;;;;;;;;;;;;;;AAsBD,IAAsB,YAAtB,MAOA;;;;;;;;;;;;;CAeE;;;;;;;CAQA;;;;;;;;;;CAWA;CAEA,YAAY,OAA4C;EACtD,KAAK,QAAQ;CACf;;;;;;;;;;CAoBA,WAA0B;EACxB,MAAM,MAAM,KAAK;EACjB,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,MACR,uHACF;EAEF,OAAO;GACL,MAAM,KAAK,mBAAmB,QAAQ,eAAe;GACrD,IAAI,IAAI,QAAQ;EAClB;CACF;CAEA,IAAI,SAAkD;EACpD,MAAM,OAAO,KAAK,SAAS,CAAC,CAAC;EAC7B,OAAO,SAAS,OAAO,OAAO,EAAE,aAAa,KAAK;CACpD;CAEA,IAAI,cAAgD;EAClD,OAAO,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,GAAG;CAC3C;AACF;;;;;;;;;;;;;;AAeA,IAAa,yBAAb,MAA2C;CAKtB;CACA;CACA;CANnB;CACA;CAEA,YACE,WACA,WACA,UACA;EAHiB,KAAA,YAAA;EACA,KAAA,YAAA;EACA,KAAA,WAAA;CAChB;CAEH,IAAI,cAAqB;EACvB,IAAI,KAAKA,aAAa,KAAA,GAAW;GAC/B,MAAM,OAAO,KAAK,UAAU;GAC5B,IAAI,SAAS,KAAA,GACX,MAAM,kCAAkC,KAAK,WAAW,eAAe,iBAAiB;GAE1F,KAAKA,WAAW,KAAK,SAAS,IAAI;EACpC;EACA,OAAO,KAAKA;CACd;CAEA,IAAI,gBAA8B;EAChC,IAAI,KAAKC,eAAe,KAAA,GAAW;GACjC,MAAM,OAAO,KAAK,UAAU;GAC5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AC;CAChD;AACF"}
{"version":3,"file":"migration.mjs","names":["#endView","#startView"],"sources":["../../src/migration-base.ts"],"sourcesContent":["import { realpathSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport type { Contract } from '@prisma-next/contract/types';\nimport type {\n ControlStack,\n MigrationPlan,\n MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport { type } from 'arktype';\nimport { errorInvalidOperationEntry, errorMigrationContractViewMissing } 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`.\n *\n * The from/to identities come from `describe()`. A migration provides them in\n * one of two ways:\n * - **Contract-derived (default):** assign the `contract.json` imports from\n * the snapshot store (`migrations/snapshots/<hex>/contract.json`) to\n * `startContractJson` / `endContractJson`; the concrete `describe()` below\n * derives `to`/`from` from their\n * `storage.storageHash`. The family bases additionally expose typed view\n * getters (`startContract` / `endContract`) over the same JSON.\n * - **Override (e.g. extension migrations that carry no contract):** override\n * `describe()` directly; the override wins and the JSON fields are unused.\n *\n * The `Start` / `End` generics carry each migration's precise contract types so\n * the family-base view getters resolve to fully-typed views.\n */\nexport abstract class Migration<\n _TOperation extends MigrationPlanOperation = MigrationPlanOperation,\n TFamilyId extends string = string,\n TTargetId extends string = string,\n _Start extends Contract = Contract,\n _End extends Contract = Contract,\n> implements MigrationPlan\n{\n abstract readonly targetId: string;\n\n /**\n * The migration's end-state contract JSON (the `contract.json` import from\n * the snapshot store). When set, the derived `describe()` reads `to` from its\n * `storage.storageHash`. Family bases build the typed `endContract` view from\n * it. Optional so `describe()`-overriding migrations (no contract) compile.\n *\n * Typed with a plain `storageHash: string`, not the branded\n * `StorageHashBase`, so a raw `contract.json` import — whose `storageHash`\n * is an untyped string literal — is assignable without a cast. The full\n * `Start`/`End` contract typing is applied downstream in the family bases'\n * view getters (via `<Family>ContractView.fromJson<…>`).\n */\n readonly endContractJson?: { readonly storage: { readonly storageHash: string } };\n\n /**\n * The migration's start-state contract JSON (the `contract.json` import\n * from the snapshot store). Absent for a baseline migration (`from`\n * derives to `null`). Family bases build the typed `startContract` view from\n * it.\n */\n readonly startContractJson?: { readonly storage: { readonly storageHash: 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. Entries may be Promises\n * when the target requires async codec resolution (e.g. DDL literal defaults).\n */\n abstract get operations(): readonly (MigrationPlanOperation | Promise<MigrationPlanOperation>)[];\n\n /**\n * Metadata inputs used to build `migration.json` and to derive the plan's\n * origin/destination identities.\n *\n * Default derivation: `to = endContractJson.storage.storageHash`,\n * `from = startContractJson?.storage.storageHash ?? null`. A migration that\n * carries no contract JSON (e.g. an extension migration) must override this;\n * otherwise it throws, since `migration.json` requires a `to` identity.\n */\n describe(): MigrationMeta {\n const end = this.endContractJson;\n if (end === undefined) {\n throw new Error(\n 'Migration.describe(): provide endContractJson or override describe() — a migration needs a destination contract hash.',\n );\n }\n return {\n from: this.startContractJson?.storage.storageHash ?? null,\n to: end.storage.storageHash,\n };\n }\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 * Lazy-memoized `endContract` / `startContract` view accessors, one instance\n * held per migration. Each target base (`MongoMigration`, `SqliteMigration`,\n * `PostgresMigration`) creates one `MigrationContractViews` field from\n * `this` — passing its own `<Family>ContractView.fromJson<…>` as `fromJson`\n * and a name for error messages — and forwards its\n * `endContract`/`startContract` getters to it.\n *\n * `endContract` throws `MIGRATION.CONTRACT_VIEW_MISSING` when the migration\n * has no `endContractJson` (mirrors `describe()`'s own requirement).\n * `startContract` returns `null` for a baseline migration (no\n * `startContractJson`) instead of throwing.\n */\nexport class MigrationContractViews<TView> {\n #endView?: TView;\n #startView?: TView | null;\n\n constructor(\n private readonly migration: Migration,\n private readonly className: string,\n private readonly fromJson: (json: unknown) => TView,\n ) {}\n\n get endContract(): TView {\n if (this.#endView === undefined) {\n const json = this.migration.endContractJson;\n if (json === undefined) {\n throw errorMigrationContractViewMissing(this.className, 'endContract', 'endContractJson');\n }\n this.#endView = this.fromJson(json);\n }\n return this.#endView;\n }\n\n get startContract(): TView | null {\n if (this.#startView === undefined) {\n const json = this.migration.startContractJson;\n this.#startView = json === undefined ? null : this.fromJson(json);\n }\n return this.#startView;\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 async function buildMigrationArtifacts(\n instance: Migration,\n existing: Partial<MigrationMetadata> | null,\n): Promise<MigrationArtifacts> {\n const rawOps = instance.operations;\n if (!Array.isArray(rawOps)) {\n throw new Error('operations must be an array');\n }\n const ops = await Promise.all(rawOps);\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":";;;;;;;;AA0BA,MAAM,sBAAsB,KAAK;CAC/B,MAAM;CACN,IAAI;AACN,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBD,IAAsB,YAAtB,MAOA;;;;;;;;;;;;;CAeE;;;;;;;CAQA;;;;;;;;;;CAWA;CAEA,YAAY,OAA4C;EACtD,KAAK,QAAQ;CACf;;;;;;;;;;CAoBA,WAA0B;EACxB,MAAM,MAAM,KAAK;EACjB,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,MACR,uHACF;EAEF,OAAO;GACL,MAAM,KAAK,mBAAmB,QAAQ,eAAe;GACrD,IAAI,IAAI,QAAQ;EAClB;CACF;CAEA,IAAI,SAAkD;EACpD,MAAM,OAAO,KAAK,SAAS,CAAC,CAAC;EAC7B,OAAO,SAAS,OAAO,OAAO,EAAE,aAAa,KAAK;CACpD;CAEA,IAAI,cAAgD;EAClD,OAAO,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,GAAG;CAC3C;AACF;;;;;;;;;;;;;;AAeA,IAAa,yBAAb,MAA2C;CAKtB;CACA;CACA;CANnB;CACA;C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SAAS;EAC/C,MAAM,SAAS,kBAAkB,IAAI,MAAM;EAC3C,IAAI,kBAAkB,KAAK,QACzB,MAAM,2BAA2B,OAAO,OAAO,OAAO;CAE1D;CAEA,MAAM,UAAmB,SAAS,SAAS;CAC3C,MAAM,SAAS,oBAAoB,OAAO;CAC1C,IAAI,kBAAkB,KAAK,QACzB,MAAM,IAAI,MAAM,yCAAyC,OAAO,SAAS;CAG3E,MAAM,WAAW,sBAAsB,QAAQ,KAAK,QAAQ;CAE5D,OAAO;EACL,SAAS,KAAK,UAAU,KAAK,MAAM,CAAC;EACpC;EACA,cAAc,KAAK,UAAU,UAAU,MAAM,CAAC;CAChD;AACF"}

@@ -1,2 +0,2 @@

import { l as validateRefName } from "../refs-CDIHeNcC.mjs";
import { l as validateRefName } from "../refs-BI9kMF4i.mjs";
import { notOk, ok } from "@prisma-next/utils/result";

@@ -3,0 +3,0 @@ //#region src/refs/types.ts

@@ -1,3 +0,3 @@

import { c as resolveRefsByContractHash, d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, r as readRef, s as resolveRef, t as HEAD_REF_NAME, u as validateRefValue } from "../refs-CDIHeNcC.mjs";
import { a as writeRefSnapshot, i as writeRefPaired, n as deleteRefSnapshot, r as readRefSnapshot, t as deleteRefPaired } from "../snapshot-DiE5uFFJ.mjs";
import { c as resolveRefsByContractHash, d as writeRef, i as readRefs, l as validateRefName, n as deleteRef, o as refsByContractHash, r as readRef, s as resolveRef, t as HEAD_REF_NAME, u as validateRefValue } from "../refs-BI9kMF4i.mjs";
import { a as writeRefSnapshot, i as writeRefPaired, n as deleteRefSnapshot, r as readRefSnapshot, t as deleteRefPaired } from "../snapshot-ByKdh1GJ.mjs";
export { HEAD_REF_NAME, deleteRef, deleteRefPaired, deleteRefSnapshot, readRef, readRefSnapshot, readRefs, refsByContractHash, resolveRef, resolveRefsByContractHash, validateRefName, validateRefValue, writeRef, writeRefPaired, writeRefSnapshot };
import { t as MigrationOps } from "../package-CCIHXr9Z.mjs";
import { a as VerifyContractSpacesResult, i as VerifyContractSpacesInputs, n as SpaceMarkerRecord, o as listContractSpaceDirectories, r as SpaceVerifierViolation, s as verifyContractSpaces, t as ContractSpaceHeadRecord } from "../verify-contract-spaces-zYlAhXOK.mjs";
import { a as VerifyContractSpacesResult, i as VerifyContractSpacesInputs, n as SpaceMarkerRecord, o as listContractSpaceDirectories, r as SpaceVerifierViolation, s as verifyContractSpaces, t as ContractSpaceHeadRecord } from "../verify-contract-spaces-DlEGEbW3.mjs";
import { APP_SPACE_ID, ContractSpace, ContractSpaceHeadRef, ContractSpaceHeadRef as ContractSpaceHeadRef$1 } from "@prisma-next/framework-components/control";
import { PreserveEmptyPredicate, StorageSort } from "@prisma-next/contract/hashing";
import { APP_SPACE_ID, ContractSpace, ContractSpaceHeadRef, ContractSpaceHeadRef as ContractSpaceHeadRef$1 } from "@prisma-next/framework-components/control";
import { Contract } from "@prisma-next/contract/types";

@@ -130,3 +130,3 @@ //#region src/assert-descriptor-self-consistency.d.ts

*
* Reads only on-disk artefacts (`migrations/<spaceId>/refs/head.json`
* Reads only on-disk artifacts (`migrations/<spaceId>/refs/head.json`
* and the per-space migration packages). **Does not import any

@@ -219,5 +219,5 @@ * extension descriptor module** — `db init` / `db update` must remain

//#endregion
//#region src/emit-contract-space-artefacts.d.ts
//#region src/emit-contract-space-artifacts.d.ts
/**
* Inputs for {@link emitContractSpaceArtefacts}.
* Inputs for {@link emitContractSpaceArtifacts}.
*

@@ -241,3 +241,3 @@ * - `contract` is the canonical contract value the framework just emitted

*/
interface ContractSpaceArtefactInputs {
interface ContractSpaceArtifactInputs {
readonly contract: unknown;

@@ -248,8 +248,13 @@ readonly contractDts: string;

/**
* Emit the per-space artefacts (`contract.json`, `contract.d.ts`,
* `refs/head.json`) under `<projectMigrationsDir>/<spaceId>/`.
* Emit the per-space artifacts — the head contract snapshot (written into
* the migrations-root-wide `snapshots/` store, keyed by `headRef.hash`) and
* `refs/head.json` — under `<projectMigrationsDir>/<spaceId>/`.
*
* Always-overwrite: the framework owns these files; running `migrate`
* twice with the same inputs is a no-op observably (idempotent), but the
* helper does not check pre-existing contents — re-emit always wins.
* The head contract snapshot is write-if-absent (see
* {@link writeContractSnapshot}): a changed extension contract has a new
* hash, so it lands as a new store entry; an unchanged hash means identical
* canonical content already sits there. `refs/head.json` stays
* always-overwrite: the framework owns it, so running `migrate` twice with
* the same inputs is a no-op observably (idempotent), but the helper does
* not check pre-existing contents — re-emit always wins.
*

@@ -266,3 +271,3 @@ * Path layout matches the convention in

*/
declare function emitContractSpaceArtefacts(projectMigrationsDir: string, spaceId: string, inputs: ContractSpaceArtefactInputs): Promise<void>;
declare function emitContractSpaceArtifacts(projectMigrationsDir: string, spaceId: string, inputs: ContractSpaceArtifactInputs): Promise<void>;
//#endregion

@@ -362,16 +367,2 @@ //#region src/gather-disk-contract-space-state.d.ts

//#endregion
//#region src/read-contract-space-contract.d.ts
/**
* Read the on-disk contract value for a contract space
* (`<projectMigrationsDir>/<spaceId>/contract.json`). Returns the parsed
* JSON value as `unknown` — callers that need a typed contract validate
* via their family's `deserializeContract` to surface schema issues.
*
* Companion to {@link import('./read-contract-space-head-ref').readContractSpaceHeadRef}
* — same ENOENT-throws / corrupt-file-error semantics. Returns the
* canonical-JSON value the framework wrote during emit, so re-running
* this helper across machines / runs yields a byte-identical value.
*/
declare function readContractSpaceContract(projectMigrationsDir: string, spaceId: string): Promise<unknown>;
//#endregion
//#region src/space-layout.d.ts

@@ -413,8 +404,7 @@ /**

/**
* Names reserved as per-space subdirectories of `migrations/<space>/`.
* Used by the enumerator to filter contract-space candidates so a
* reserved name (e.g. a top-level `migrations/refs/` left in the wrong
* place) is never enumerated as a phantom contract space. Currently
* holds `SPACE_REFS_DIRNAME`; extend if future per-space layouts add
* more reserved subdirectories.
* Names reserved under `migrations/` that must never be enumerated as a
* phantom contract space: `SPACE_REFS_DIRNAME` (e.g. a top-level
* `migrations/refs/` left in the wrong place) and
* `CONTRACT_SNAPSHOTS_DIRNAME` (the migrations-root-wide contract
* snapshot store, `migrations/snapshots/`).
*/

@@ -430,3 +420,3 @@ declare const RESERVED_SPACE_SUBDIR_NAMES: ReadonlySet<string>;

//#endregion
export { APP_SPACE_ID, type ComputeExtensionSpaceApplyPathInputs, type ContractSpaceArtefactInputs, type ContractSpaceHeadRecord, type ContractSpaceHeadRef, type DescriptorSelfConsistencyInputs, type DiskContractSpaceState, type ExtensionSpaceApplyPathOutcome, RESERVED_SPACE_SUBDIR_NAMES, SPACE_REFS_DIRNAME, type SpaceApplyInput, type SpaceMarkerRecord, type SpacePlanInput, type SpacePlanOutput, type SpaceVerifierViolation, type ValidSpaceId, type VerifyContractSpacesInputs, type VerifyContractSpacesResult, assertDescriptorSelfConsistency, assertValidSpaceId, computeExtensionSpaceApplyPath, contractSpaceFromJson, emitContractSpaceArtefacts, gatherDiskContractSpaceState, isValidSpaceId, listContractSpaceDirectories, planAllSpaces, readContractSpaceContract, readContractSpaceHeadRef, spaceMigrationDirectory, spaceRefsDirectory, verifyContractSpaces };
export { APP_SPACE_ID, type ComputeExtensionSpaceApplyPathInputs, type ContractSpaceArtifactInputs, type ContractSpaceHeadRecord, type ContractSpaceHeadRef, type DescriptorSelfConsistencyInputs, type DiskContractSpaceState, type ExtensionSpaceApplyPathOutcome, RESERVED_SPACE_SUBDIR_NAMES, SPACE_REFS_DIRNAME, type SpaceApplyInput, type SpaceMarkerRecord, type SpacePlanInput, type SpacePlanOutput, type SpaceVerifierViolation, type ValidSpaceId, type VerifyContractSpacesInputs, type VerifyContractSpacesResult, assertDescriptorSelfConsistency, assertValidSpaceId, computeExtensionSpaceApplyPath, contractSpaceFromJson, emitContractSpaceArtifacts, gatherDiskContractSpaceState, isValidSpaceId, listContractSpaceDirectories, planAllSpaces, readContractSpaceHeadRef, spaceMigrationDirectory, spaceRefsDirectory, verifyContractSpaces };
//# sourceMappingURL=spaces.d.mts.map

@@ -1,1 +0,1 @@

{"version":3,"file":"spaces.d.mts","names":[],"sources":["../../src/assert-descriptor-self-consistency.ts","../../src/read-contract-space-head-ref.ts","../../src/compute-extension-space-apply-path.ts","../../src/concatenate-space-apply-inputs.ts","../../src/contract-space-from-json.ts","../../src/emit-contract-space-artefacts.ts","../../src/gather-disk-contract-space-state.ts","../../src/plan-all-spaces.ts","../../src/read-contract-space-contract.ts","../../src/space-layout.ts"],"mappings":";;;;;;;;;;;;UAWiB;WACN;WACA;WACA;;;;;;;;WAQA;WACA;WACA,sBAAsB;WACtB,cAAc;;;;;;;;;;;;;;;;;;;;;iBAsBT,gCAAgC,QAAQ;;;;;;;;;;;;;;;;iBCtBlC,yBACpB,8BACA,kBACC,QAAQ;;;;;;;;;KCZC;WAEG;WACA,sBAAsB;;;;;;WAMtB;;;;;WAKA,SAAS;;;;;;WAMT;;WAEA;WAA8B,sBAAsB;;WAEpD;WACA,sBAAsB;WACtB;WACA;aAAoC;aAA0B;;;WAE9D;;;;;;;;;;;;;UAaE;WACN;WACA;WACA;WACA;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BW,+BACpB,QAAQ,uCACP,QAAQ;;;;;;;;;;;;;;;;;;;;;;;UCnEM,gBAAgB;WACtB;WACA;WACA;WACA;WACA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBCUV,sBAAsB,kBAAkB,WAAW,UAAU;WAClE;WACA,YAAY;aACV;aACA;aACA;;WAEF,SAAS;IAChB,cAAc;;;;;;;;;;;;;;;;;;;;;;;UCpBD;WACN;WACA;WACA,SAAS;;;;;;;;;;;;;;;;;;;;iBAqBE,2BACpB,8BACA,iBACA,QAAQ,8BACP;;;;;;;;;UCzCc;;WAEN;;WAEA,iBAAiB,oBAAoB;;;;;;;;;;;;;;;;;;;;iBAqB1B,6BAA6B;WACxC;;;;;;WAMA,gBAAgB;IACvB,QAAQ;;;;;;;;;;;;;;;;UC/BK,eAAe;WACrB;WACA,eAAe;WACf,aAAa;;UAGP,gBAAgB;WACtB;WACA,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BvB,cAAc,WAAW,UACvC,iBAAiB,eAAe,cAChC,YAAY,OAAO,eAAe,wBAAwB,sBAChD,gBAAgB;;;;;;;;;;;;;;iBCpCN,0BACpB,8BACA,kBACC;;;;;;;;;;KCVS;WAAmC;;iBAS/B,eAAe,kBAAkB,WAAW;iBAI5C,mBAAmB,0BAA0B,WAAW;;;;;;;;;;;;;iBAkBxD,wBAAwB,8BAA8B;;;;;;;;;cAazD;;;;;;;;;cAUA,6BAA6B;;;;;;;iBAQ1B,mBAAmB"}
{"version":3,"file":"spaces.d.mts","names":[],"sources":["../../src/assert-descriptor-self-consistency.ts","../../src/read-contract-space-head-ref.ts","../../src/compute-extension-space-apply-path.ts","../../src/concatenate-space-apply-inputs.ts","../../src/contract-space-from-json.ts","../../src/emit-contract-space-artifacts.ts","../../src/gather-disk-contract-space-state.ts","../../src/plan-all-spaces.ts","../../src/space-layout.ts"],"mappings":";;;;;;;;;;;;UAWiB;WACN;WACA;WACA;;;;;;;;WAQA;WACA;WACA,sBAAsB;WACtB,cAAc;;;;;;;;;;;;;;;;;;;;;iBAsBT,gCAAgC,QAAQ;;;;;;;;;;;;;;;;iBCtBlC,yBACpB,8BACA,kBACC,QAAQ;;;;;;;;;KCZC;WAEG;WACA,sBAAsB;;;;;;WAMtB;;;;;WAKA,SAAS;;;;;;WAMT;;WAEA;WAA8B,sBAAsB;;WAEpD;WACA,sBAAsB;WACtB;WACA;aAAoC;aAA0B;;;WAE9D;;;;;;;;;;;;;UAaE;WACN;WACA;WACA;WACA;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BW,+BACpB,QAAQ,uCACP,QAAQ;;;;;;;;;;;;;;;;;;;;;;;UCnEM,gBAAgB;WACtB;WACA;WACA;WACA;WACA,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBCUV,sBAAsB,kBAAkB,WAAW,UAAU;WAClE;WACA,YAAY;aACV;aACA;aACA;;WAEF,SAAS;IAChB,cAAc;;;;;;;;;;;;;;;;;;;;;;;UCnBD;WACN;WACA;WACA,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;iBA0BE,2BACpB,8BACA,iBACA,QAAQ,8BACP;;;;;;;;;UC/Cc;;WAEN;;WAEA,iBAAiB,oBAAoB;;;;;;;;;;;;;;;;;;;;iBAqB1B,6BAA6B;WACxC;;;;;;WAMA,gBAAgB;IACvB,QAAQ;;;;;;;;;;;;;;;;UC/BK,eAAe;WACrB;WACA,eAAe;WACf,aAAa;;UAGP,gBAAgB;WACtB;WACA,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BvB,cAAc,WAAW,UACvC,iBAAiB,eAAe,cAChC,YAAY,OAAO,eAAe,wBAAwB,sBAChD,gBAAgB;;;;;;;;;;KCxChB;WAAmC;;iBAS/B,eAAe,kBAAkB,WAAW;iBAI5C,mBAAmB,0BAA0B,WAAW;;;;;;;;;;;;;iBAkBxD,wBAAwB,8BAA8B;;;;;;;;;cAazD;;;;;;;;cASA,6BAA6B;;;;;;;iBAW1B,mBAAmB"}

@@ -1,6 +0,7 @@

import { a as errorDescriptorHeadHashMismatch, c as errorDuplicateSpaceId } from "../errors-DIS_dcFJ.mjs";
import { s as readMigrationsDir } from "../io-CE79C4uK.mjs";
import { s as errorDescriptorHeadHashMismatch, u as errorDuplicateSpaceId } from "../errors-DldT38lZ.mjs";
import { o as writeContractSnapshot } from "../contract-snapshot-store-DCFUkXwL.mjs";
import { s as readMigrationsDir } from "../io-H4a-OJHL.mjs";
import "../constants-YnG8_EGO.mjs";
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-BXHOgdTg.mjs";
import { a as APP_SPACE_ID, c as assertValidSpaceId, d as spaceRefsDirectory, i as readContractSpaceHeadRef, l as isValidSpaceId, n as listContractSpaceDirectories, o as RESERVED_SPACE_SUBDIR_NAMES, r as verifyContractSpaces, s as SPACE_REFS_DIRNAME, t as readContractSpaceContract, u as spaceMigrationDirectory } from "../read-contract-space-contract-DBW4-T5r.mjs";
import { l as reconstructGraph, o as findPathWithDecision } from "../migration-graph-k8O6g9j2.mjs";
import { a as RESERVED_SPACE_SUBDIR_NAMES, c as isValidSpaceId, i as APP_SPACE_ID, l as spaceMigrationDirectory, n as verifyContractSpaces, o as SPACE_REFS_DIRNAME, r as readContractSpaceHeadRef, s as assertValidSpaceId, t as listContractSpaceDirectories, u as spaceRefsDirectory } from "../verify-contract-spaces-DbLI1miK.mjs";
import { ifDefined } from "@prisma-next/utils/defined";

@@ -54,3 +55,3 @@ import { join } from "pathe";

*
* Reads only on-disk artefacts (`migrations/<spaceId>/refs/head.json`
* Reads only on-disk artifacts (`migrations/<spaceId>/refs/head.json`
* and the per-space migration packages). **Does not import any

@@ -76,3 +77,3 @@ * extension descriptor module** — `db init` / `db update` must remain

if (contractSpaceHeadRef === null) return { kind: "contractSpaceHeadRefMissing" };
const { packages } = await readMigrationsDir(spaceMigrationDirectory(projectMigrationsDir, spaceId));
const { packages } = await readMigrationsDir(spaceMigrationDirectory(projectMigrationsDir, spaceId), { migrationsDir: projectMigrationsDir });
const graph = reconstructGraph(packages);

@@ -158,10 +159,15 @@ const fromHash = currentMarkerHash ?? "sha256:empty";

//#endregion
//#region src/emit-contract-space-artefacts.ts
//#region src/emit-contract-space-artifacts.ts
/**
* Emit the per-space artefacts (`contract.json`, `contract.d.ts`,
* `refs/head.json`) under `<projectMigrationsDir>/<spaceId>/`.
* Emit the per-space artifacts — the head contract snapshot (written into
* the migrations-root-wide `snapshots/` store, keyed by `headRef.hash`) and
* `refs/head.json` — under `<projectMigrationsDir>/<spaceId>/`.
*
* Always-overwrite: the framework owns these files; running `migrate`
* twice with the same inputs is a no-op observably (idempotent), but the
* helper does not check pre-existing contents — re-emit always wins.
* The head contract snapshot is write-if-absent (see
* {@link writeContractSnapshot}): a changed extension contract has a new
* hash, so it lands as a new store entry; an unchanged hash means identical
* canonical content already sits there. `refs/head.json` stays
* always-overwrite: the framework owns it, so running `migrate` twice with
* the same inputs is a no-op observably (idempotent), but the helper does
* not check pre-existing contents — re-emit always wins.
*

@@ -178,9 +184,10 @@ * Path layout matches the convention in

*/
async function emitContractSpaceArtefacts(projectMigrationsDir, spaceId, inputs) {
async function emitContractSpaceArtifacts(projectMigrationsDir, spaceId, inputs) {
assertValidSpaceId(spaceId);
const dir = join(projectMigrationsDir, spaceId);
const refsDir = spaceRefsDirectory(dir);
const refsDir = spaceRefsDirectory(join(projectMigrationsDir, spaceId));
await mkdir(refsDir, { recursive: true });
await writeFile(join(dir, "contract.json"), `${canonicalizeJson(inputs.contract)}\n`);
await writeFile(join(dir, "contract.d.ts"), inputs.contractDts);
await writeContractSnapshot(projectMigrationsDir, inputs.headRef.hash, {
contractJson: inputs.contract,
contractDts: inputs.contractDts
});
const sortedInvariants = [...inputs.headRef.invariants].sort();

@@ -272,4 +279,4 @@ const headJson = canonicalizeJson({

//#endregion
export { APP_SPACE_ID, RESERVED_SPACE_SUBDIR_NAMES, SPACE_REFS_DIRNAME, assertDescriptorSelfConsistency, assertValidSpaceId, computeExtensionSpaceApplyPath, contractSpaceFromJson, emitContractSpaceArtefacts, gatherDiskContractSpaceState, isValidSpaceId, listContractSpaceDirectories, planAllSpaces, readContractSpaceContract, readContractSpaceHeadRef, spaceMigrationDirectory, spaceRefsDirectory, verifyContractSpaces };
export { APP_SPACE_ID, RESERVED_SPACE_SUBDIR_NAMES, SPACE_REFS_DIRNAME, assertDescriptorSelfConsistency, assertValidSpaceId, computeExtensionSpaceApplyPath, contractSpaceFromJson, emitContractSpaceArtifacts, gatherDiskContractSpaceState, isValidSpaceId, listContractSpaceDirectories, planAllSpaces, readContractSpaceHeadRef, spaceMigrationDirectory, spaceRefsDirectory, verifyContractSpaces };
//# sourceMappingURL=spaces.mjs.map

@@ -1,1 +0,1 @@

{"version":3,"file":"spaces.mjs","names":[],"sources":["../../src/assert-descriptor-self-consistency.ts","../../src/compute-extension-space-apply-path.ts","../../src/contract-space-from-json.ts","../../src/emit-contract-space-artefacts.ts","../../src/gather-disk-contract-space-state.ts","../../src/plan-all-spaces.ts"],"sourcesContent":["import type { PreserveEmptyPredicate, StorageSort } from '@prisma-next/contract/hashing';\nimport { computeStorageHash } from '@prisma-next/contract/hashing';\nimport { ifDefined } from '@prisma-next/utils/defined';\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 readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n readonly sortStorage?: StorageSort;\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 ...ifDefined('shouldPreserveEmpty', inputs.shouldPreserveEmpty),\n ...ifDefined('sortStorage', inputs.sortStorage),\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 `migrate` 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 type { Contract } from '@prisma-next/contract/types';\nimport type {\n ContractSpace,\n ContractSpaceHeadRef,\n MigrationPackage,\n MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMetadata } from './metadata';\n\n/**\n * Materialise a typed {@link ContractSpace} from the JSON artefacts a\n * contract-space extension package emits to disk.\n *\n * Extension descriptors wire `contract.json`, per-migration\n * `migration.json` / `ops.json`, and `refs/head.json` to the framework's\n * typed surfaces. TypeScript widens JSON imports to a structural record\n * that does not preserve readonly modifiers or branded scalars (e.g.\n * `StorageHashBase<'sha256:...'>`), so authoring the descriptor inline\n * forces every wiring site to cast through `unknown`. This helper\n * encapsulates the single narrowing point: descriptor sources stay\n * cast-free, and the (necessary) coercion is colocated with the\n * documentation explaining why it is safe.\n *\n * Safety: the JSON files passed here are produced by the framework's own\n * emit pipeline (`prisma-next contract emit` and `MigrationCLI.run`)\n * and re-validated downstream by the runner / verifier. The descriptor\n * is a pass-through wiring layer — no descriptor consumer treats the\n * narrowed types as a stronger guarantee than \"these came from the\n * canonical emit pipeline\".\n *\n * The helper does not introspect or schema-validate the inputs; runtime\n * validation is the responsibility of `family.deserializeContract`\n * (codec-aware, invoked at control-stack construction) and the\n * per-migration `readMigrationPackage` reader used when loading\n * from disk. JSON-imported packages flow through the descriptor without\n * a disk read, so the equivalent runtime guarantee comes from the emit\n * pipeline that produced the JSON in the first place.\n */\nexport function contractSpaceFromJson<TContract extends Contract = Contract>(inputs: {\n readonly contractJson: unknown;\n readonly migrations: ReadonlyArray<{\n readonly dirName: string;\n readonly metadata: unknown;\n readonly ops: unknown;\n }>;\n readonly headRef: ContractSpaceHeadRef;\n}): ContractSpace<TContract> {\n // The narrowing happens once, here. Casting via `unknown` rather than a\n // direct cast preserves TS's structural soundness checks for the\n // inputs (they must be assignable to `unknown`, which is trivial); the\n // resulting type is the family-specific Contract / MigrationPackage\n // surface descriptors publish.\n const migrations: readonly MigrationPackage[] = inputs.migrations.map((m) => ({\n dirName: m.dirName,\n metadata: m.metadata as MigrationMetadata,\n ops: m.ops as readonly MigrationPlanOperation[],\n }));\n return {\n contractJson: inputs.contractJson as TContract,\n migrations,\n headRef: inputs.headRef,\n };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { join } from 'pathe';\nimport type { ContractSpaceHeadRef } from './read-contract-space-head-ref';\nimport { assertValidSpaceId, spaceRefsDirectory } 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 const refsDir = spaceRefsDirectory(dir);\n await mkdir(refsDir, { 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(refsDir, '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 spaces.\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;\n });\n\n return sorted.map((input) => ({\n spaceId: input.spaceId,\n migrationPackages: planSpace(input),\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,gCAAgC,QAA+C;CAa7F,MAAM,EAAE,aAAa,WAAW,GAAG,uBADb,OAAO;CAE7B,MAAM,aAAa,mBAAmB;EACpC,QAAQ,OAAO;EACf,cAAc,OAAO;EACrB,SAAS;EACT,GAAG,UAAU,uBAAuB,OAAO,mBAAmB;EAC9D,GAAG,UAAU,eAAe,OAAO,WAAW;CAChD,CAAC;CACD,IAAI,eAAe,OAAO,aACxB,MAAM,gCAAgC;EACpC,aAAa,OAAO;EACpB,gBAAgB;EAChB,aAAa,OAAO;CACtB,CAAC;AAEL;;;;;;;;;;;;;;;;;;;;;;;;;;ACaA,eAAsB,+BACpB,QACy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ACRA,SAAgB,cACd,QACA,WACsC;CACtC,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,KAAK,IAAI,MAAM,OAAO,GACxB,MAAM,sBAAsB,MAAM,OAAO;EAE3C,KAAK,IAAI,MAAM,OAAO;CACxB;CAQA,OANe,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM;EACxC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,OAAO;CACT,CAEY,CAAC,CAAC,KAAK,WAAW;EAC5B,SAAS,MAAM;EACf,mBAAmB,UAAU,KAAK;CACpC,EAAE;AACJ"}
{"version":3,"file":"spaces.mjs","names":[],"sources":["../../src/assert-descriptor-self-consistency.ts","../../src/compute-extension-space-apply-path.ts","../../src/contract-space-from-json.ts","../../src/emit-contract-space-artifacts.ts","../../src/gather-disk-contract-space-state.ts","../../src/plan-all-spaces.ts"],"sourcesContent":["import type { PreserveEmptyPredicate, StorageSort } from '@prisma-next/contract/hashing';\nimport { computeStorageHash } from '@prisma-next/contract/hashing';\nimport { ifDefined } from '@prisma-next/utils/defined';\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 readonly shouldPreserveEmpty?: PreserveEmptyPredicate;\n readonly sortStorage?: StorageSort;\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 ...ifDefined('shouldPreserveEmpty', inputs.shouldPreserveEmpty),\n ...ifDefined('sortStorage', inputs.sortStorage),\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 artifacts (`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, { migrationsDir: projectMigrationsDir });\n const graph = reconstructGraph(packages);\n\n // Live-marker layer encodes \"no prior state\" as EMPTY_CONTRACT_HASH;\n // mirror the `migrate` 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 type { Contract } from '@prisma-next/contract/types';\nimport type {\n ContractSpace,\n ContractSpaceHeadRef,\n MigrationPackage,\n MigrationPlanOperation,\n} from '@prisma-next/framework-components/control';\nimport type { MigrationMetadata } from './metadata';\n\n/**\n * Materialise a typed {@link ContractSpace} from the JSON artefacts a\n * contract-space extension package emits to disk.\n *\n * Extension descriptors wire `contract.json`, per-migration\n * `migration.json` / `ops.json`, and `refs/head.json` to the framework's\n * typed surfaces. TypeScript widens JSON imports to a structural record\n * that does not preserve readonly modifiers or branded scalars (e.g.\n * `StorageHashBase<'sha256:...'>`), so authoring the descriptor inline\n * forces every wiring site to cast through `unknown`. This helper\n * encapsulates the single narrowing point: descriptor sources stay\n * cast-free, and the (necessary) coercion is colocated with the\n * documentation explaining why it is safe.\n *\n * Safety: the JSON files passed here are produced by the framework's own\n * emit pipeline (`prisma-next contract emit` and `MigrationCLI.run`)\n * and re-validated downstream by the runner / verifier. The descriptor\n * is a pass-through wiring layer — no descriptor consumer treats the\n * narrowed types as a stronger guarantee than \"these came from the\n * canonical emit pipeline\".\n *\n * The helper does not introspect or schema-validate the inputs; runtime\n * validation is the responsibility of `family.deserializeContract`\n * (codec-aware, invoked at control-stack construction) and the\n * per-migration `readMigrationPackage` reader used when loading\n * from disk. JSON-imported packages flow through the descriptor without\n * a disk read, so the equivalent runtime guarantee comes from the emit\n * pipeline that produced the JSON in the first place.\n */\nexport function contractSpaceFromJson<TContract extends Contract = Contract>(inputs: {\n readonly contractJson: unknown;\n readonly migrations: ReadonlyArray<{\n readonly dirName: string;\n readonly metadata: unknown;\n readonly ops: unknown;\n }>;\n readonly headRef: ContractSpaceHeadRef;\n}): ContractSpace<TContract> {\n // The narrowing happens once, here. Casting via `unknown` rather than a\n // direct cast preserves TS's structural soundness checks for the\n // inputs (they must be assignable to `unknown`, which is trivial); the\n // resulting type is the family-specific Contract / MigrationPackage\n // surface descriptors publish.\n const migrations: readonly MigrationPackage[] = inputs.migrations.map((m) => ({\n dirName: m.dirName,\n metadata: m.metadata as MigrationMetadata,\n ops: m.ops as readonly MigrationPlanOperation[],\n }));\n return {\n contractJson: inputs.contractJson as TContract,\n migrations,\n headRef: inputs.headRef,\n };\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { join } from 'pathe';\nimport { writeContractSnapshot } from './contract-snapshot-store';\nimport type { ContractSpaceHeadRef } from './read-contract-space-head-ref';\nimport { assertValidSpaceId, spaceRefsDirectory } from './space-layout';\n\n/**\n * Inputs for {@link emitContractSpaceArtifacts}.\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 ContractSpaceArtifactInputs {\n readonly contract: unknown;\n readonly contractDts: string;\n readonly headRef: ContractSpaceHeadRef;\n}\n\n/**\n * Emit the per-space artifacts — the head contract snapshot (written into\n * the migrations-root-wide `snapshots/` store, keyed by `headRef.hash`) and\n * `refs/head.json` — under `<projectMigrationsDir>/<spaceId>/`.\n *\n * The head contract snapshot is write-if-absent (see\n * {@link writeContractSnapshot}): a changed extension contract has a new\n * hash, so it lands as a new store entry; an unchanged hash means identical\n * canonical content already sits there. `refs/head.json` stays\n * always-overwrite: the framework owns it, so running `migrate` twice with\n * the same inputs is a no-op observably (idempotent), but the helper does\n * 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 emitContractSpaceArtifacts(\n projectMigrationsDir: string,\n spaceId: string,\n inputs: ContractSpaceArtifactInputs,\n): Promise<void> {\n assertValidSpaceId(spaceId);\n\n const dir = join(projectMigrationsDir, spaceId);\n const refsDir = spaceRefsDirectory(dir);\n await mkdir(refsDir, { recursive: true });\n\n await writeContractSnapshot(projectMigrationsDir, inputs.headRef.hash, {\n contractJson: inputs.contract,\n contractDts: inputs.contractDts,\n });\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(refsDir, '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 spaces.\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;\n });\n\n return sorted.map((input) => ({\n spaceId: input.spaceId,\n migrationPackages: planSpace(input),\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,gCAAgC,QAA+C;CAa7F,MAAM,EAAE,aAAa,WAAW,GAAG,uBADb,OAAO;CAE7B,MAAM,aAAa,mBAAmB;EACpC,QAAQ,OAAO;EACf,cAAc,OAAO;EACrB,SAAS;EACT,GAAG,UAAU,uBAAuB,OAAO,mBAAmB;EAC9D,GAAG,UAAU,eAAe,OAAO,WAAW;CAChD,CAAC;CACD,IAAI,eAAe,OAAO,aACxB,MAAM,gCAAgC;EACpC,aAAa,OAAO;EACpB,gBAAgB;EAChB,aAAa,OAAO;CACtB,CAAC;AAEL;;;;;;;;;;;;;;;;;;;;;;;;;;ACaA,eAAsB,+BACpB,QACyC;CACzC,MAAM,EAAE,sBAAsB,SAAS,mBAAmB,4BAA4B;CAEtF,MAAM,uBAAuB,MAAM,yBAAyB,sBAAsB,OAAO;CACzF,IAAI,yBAAyB,MAC3B,OAAO,EAAE,MAAM,8BAA8B;CAI/C,MAAM,EAAE,aAAa,MAAM,kBADV,wBAAwB,sBAAsB,OACX,GAAG,EAAE,eAAe,qBAAqB,CAAC;CAC9F,MAAM,QAAQ,iBAAiB,QAAQ;CAKvC,MAAM,WAAW,qBAAA;CACjB,MAAM,WAAW,IAAI,IACnB,qBAAqB,WAAW,QAAQ,OAAO,CAAC,wBAAwB,SAAS,EAAE,CAAC,CACtF;CAEA,MAAM,UAAU,qBAAqB,OAAO,UAAU,qBAAqB,MAAM,EAAE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.4",
"version": "0.16.0-dev.5",
"license": "Apache-2.0",

@@ -9,5 +9,5 @@ "type": "module",

"dependencies": {
"@prisma-next/contract": "0.16.0-dev.4",
"@prisma-next/framework-components": "0.16.0-dev.4",
"@prisma-next/utils": "0.16.0-dev.4",
"@prisma-next/contract": "0.16.0-dev.5",
"@prisma-next/framework-components": "0.16.0-dev.5",
"@prisma-next/utils": "0.16.0-dev.5",
"arktype": "^2.2.2",

@@ -18,5 +18,5 @@ "pathe": "^2.0.3",

"devDependencies": {
"@prisma-next/test-utils": "0.16.0-dev.4",
"@prisma-next/tsconfig": "0.16.0-dev.4",
"@prisma-next/tsdown": "0.16.0-dev.4",
"@prisma-next/test-utils": "0.16.0-dev.5",
"@prisma-next/tsconfig": "0.16.0-dev.5",
"@prisma-next/tsdown": "0.16.0-dev.5",
"tsdown": "0.22.8",

@@ -59,2 +59,6 @@ "typescript": "5.9.3",

},
"./contract-snapshot-store": {
"types": "./dist/exports/contract-snapshot-store.d.mts",
"import": "./dist/exports/contract-snapshot-store.mjs"
},
"./hash": {

@@ -61,0 +65,0 @@ "types": "./dist/exports/hash.d.mts",

@@ -1,2 +0,1 @@

import { readFile } from 'node:fs/promises';
import type { Contract, StorageNamespace } from '@prisma-next/contract/types';

@@ -7,7 +6,10 @@ import type { SchemaEntityCoordinate } from '@prisma-next/framework-components/control';

import {
contractSnapshotDir,
readContractSnapshotDts,
readContractSnapshotJson,
} from '../contract-snapshot-store';
import {
errorBundleNotFoundForGraphNode,
errorContractDeserializationFailed,
errorHashNotInGraph,
errorInvalidJson,
errorMissingFile,
errorSnapshotMissing,

@@ -31,6 +33,2 @@ MigrationToolsError,

function hasErrnoCode(error: unknown, code: string): boolean {
return error instanceof Error && (error as { code?: string }).code === code;
}
function contractAtMemoKey(hash: string, refName: string | undefined): string {

@@ -57,35 +55,9 @@ return `${hash}\0${refName ?? ''}`;

async function readGraphNodeEndContract(
packageDir: string,
migrationsDir: string,
hash: string,
deserializeContract: (raw: unknown) => Contract,
): Promise<{ contractJson: unknown; contractDts: string; contract: Contract }> {
const jsonPath = join(packageDir, 'end-contract.json');
const dtsPath = join(packageDir, 'end-contract.d.ts');
let rawJson: string;
try {
rawJson = await readFile(jsonPath, 'utf-8');
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) {
throw errorMissingFile('end-contract.json', packageDir);
}
throw error;
}
let contractJson: unknown;
try {
contractJson = JSON.parse(rawJson);
} catch (error) {
throw errorInvalidJson(jsonPath, error instanceof Error ? error.message : String(error));
}
let contractDts: string;
try {
contractDts = await readFile(dtsPath, 'utf-8');
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) {
throw errorMissingFile('end-contract.d.ts', packageDir);
}
throw error;
}
const contractJson = await readContractSnapshotJson(migrationsDir, hash);
const contractDts = await readContractSnapshotDts(migrationsDir, hash);
const jsonPath = join(contractSnapshotDir(migrationsDir, hash), 'contract.json');
const contract = deserializeContractAtPath(jsonPath, contractJson, deserializeContract);

@@ -99,2 +71,3 @@ return { contractJson, contractDts, contract };

readonly refsDir: string;
readonly migrationsDir: string;
readonly packages: readonly OnDiskMigrationPackage[];

@@ -104,3 +77,3 @@ readonly graph: MigrationGraph;

}): Promise<ContractAtResult> {
const { hash, opts, refsDir, packages, graph, deserializeContract } = args;
const { hash, opts, refsDir, migrationsDir, packages, graph, deserializeContract } = args;
const refName = opts?.refName;

@@ -124,2 +97,3 @@

hash,
migrationsDir,
packages,

@@ -135,3 +109,3 @@ deserializeContract,

if (isGraphNode(hash, graph)) {
return resolveGraphNodeContractAt({ hash, packages, deserializeContract });
return resolveGraphNodeContractAt({ hash, migrationsDir, packages, deserializeContract });
}

@@ -144,2 +118,3 @@

readonly hash: string;
readonly migrationsDir: string;
readonly packages: readonly OnDiskMigrationPackage[];

@@ -149,3 +124,3 @@ readonly deserializeContract: (raw: unknown) => Contract;

}): Promise<ContractAtResult> {
const { hash, packages, deserializeContract, explicitLabel } = args;
const { hash, migrationsDir, packages, deserializeContract, explicitLabel } = args;
const matchingBundle = packages.find((pkg) => pkg.metadata.to === hash);

@@ -157,3 +132,4 @@ if (!matchingBundle) {

const { contractJson, contractDts, contract } = await readGraphNodeEndContract(
matchingBundle.dirPath,
migrationsDir,
hash,
deserializeContract,

@@ -167,3 +143,2 @@ );

provenance: 'graph-node',
sourceDir: matchingBundle.dirPath,
};

@@ -200,3 +175,4 @@ }

* the same resolution order as plan-time ref resolution: ref snapshot first
* (when `opts.refName` is set), else the matching package's `end-contract.*`.
* (when `opts.refName` is set), else the contract snapshot store entry
* keyed by the matching package's `to` hash.
*/

@@ -209,6 +185,16 @@ export function createAggregateContractSpace(args: {

readonly refsDir: string;
readonly migrationsDir: string;
readonly resolveContract: () => Contract;
readonly deserializeContract: (raw: unknown) => Contract;
}): AggregateContractSpace {
const { spaceId, packages, refs, headRef, refsDir, resolveContract, deserializeContract } = args;
const {
spaceId,
packages,
refs,
headRef,
refsDir,
migrationsDir,
resolveContract,
deserializeContract,
} = args;
let graphMemo: MigrationGraph | undefined;

@@ -244,2 +230,3 @@ let contractMemo: Contract | undefined;

refsDir,
migrationsDir,
packages,

@@ -246,0 +233,0 @@ graph: spaceGraph(),

import type { Contract } from '@prisma-next/contract/types';
import { readContractSnapshotJson } from '../contract-snapshot-store';
import { MigrationToolsError } from '../errors';
import { readMigrationsDir } from '../io';
import { readContractSpaceContract } from '../read-contract-space-contract';
import { readContractSpaceHeadRef } from '../read-contract-space-head-ref';
import {
type ContractSpaceHeadRef,
readContractSpaceHeadRef,
} from '../read-contract-space-head-ref';
import { HEAD_REF_NAME, type RefLoadProblem, readRefsTolerant } from '../refs';

@@ -10,3 +13,2 @@ import {

isValidSpaceId,
RESERVED_SPACE_SUBDIR_NAMES,
spaceMigrationDirectory,

@@ -27,6 +29,7 @@ spaceRefsDirectory,

* packages + refs + head refs). The app's *live* contract is not a disk
* artefact — in Prisma Next it is always compiled from the project's
* artifact — in Prisma Next it is always compiled from the project's
* central contract, so the caller always has it and threads it in as
* `appContract`. `deserializeContract` is held and called lazily only for
* the on-disk extension contracts (`migrations/<ext>/contract.json`).
* the extension contracts resolved from the contract snapshot store,
* keyed by each extension space's head ref hash.
*/

@@ -82,3 +85,3 @@ export interface LoadAggregateInput {

const spaceDir = spaceMigrationDirectory(migrationsDir, APP_SPACE_ID);
const { packages, problems } = await readMigrationsDir(spaceDir);
const { packages, problems } = await readMigrationsDir(spaceDir, { migrationsDir });
const { refs, problems: refProblems } = await readRefsTolerant(spaceRefsDirectory(spaceDir));

@@ -92,2 +95,3 @@

refsDir: spaceRefsDirectory(spaceDir),
migrationsDir,
resolveContract: () => appContract,

@@ -115,3 +119,2 @@ deserializeContract,

.filter((name) => name !== APP_SPACE_ID)
.filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name))
.filter(isValidSpaceId)

@@ -133,7 +136,7 @@ .sort();

const spaceDir = spaceMigrationDirectory(migrationsDir, spaceId);
const { packages, problems } = await readMigrationsDir(spaceDir);
const { packages, problems } = await readMigrationsDir(spaceDir, { migrationsDir });
const { refs, problems: refProblems } = await readRefsTolerant(spaceRefsDirectory(spaceDir));
const { headRef, problem: headRefProblem } = await readHeadRefTolerant(migrationsDir, spaceId);
const rawContract = await readRawContractDeferred(migrationsDir, spaceId);
const rawContract = await readRawContractDeferred(migrationsDir, spaceId, headRef);

@@ -146,2 +149,3 @@ const space = createAggregateContractSpace({

refsDir: spaceRefsDirectory(spaceDir),
migrationsDir,
resolveContract: () => deserializeContract(rawContract()),

@@ -200,6 +204,9 @@ deserializeContract,

/**
* Read the raw on-disk contract eagerly (cheap I/O) but defer its
* (throwing) failure to call time, so a missing or unparseable
* `contract.json` becomes a `contract()` throw — surfaced as
* `contractUnreadable` — rather than a construction failure.
* Read the raw contract snapshot-store entry eagerly (cheap I/O) but defer
* its (throwing) failure to call time, so a missing or unparseable store
* entry becomes a `contract()` throw — surfaced as `contractUnreadable` —
* rather than a construction failure. When `headRef` is absent there is no
* hash to resolve against the store, so the deferred call always throws;
* `checkIntegrity` already reports that case as `headRefMissing`, and a
* `checkContracts` pass surfaces the same space as `contractUnreadable`.
*/

@@ -209,5 +216,13 @@ async function readRawContractDeferred(

spaceId: string,
headRef: ContractSpaceHeadRef | null,
): Promise<() => unknown> {
if (headRef === null) {
return () => {
throw new Error(
`Contract space "${spaceId}" has no head ref; its contract cannot be resolved from the snapshot store without one.`,
);
};
}
try {
const raw = await readContractSpaceContract(migrationsDir, spaceId);
const raw = await readContractSnapshotJson(migrationsDir, headRef.hash);
return () => raw;

@@ -214,0 +229,0 @@ } catch (error) {

@@ -125,8 +125,8 @@ import type { Contract } from '@prisma-next/contract/types';

* Contract IR JSON of the edge's destination state, threaded from the
* bundle's on-disk `end-contract.json` snapshot (`resolveRecordedPath`)
* or the space's destination contract (`planFromDiff`). Runners persist it as the
* bundle's snapshot store entry (`resolveRecordedPath`) or the space's
* destination contract (`planFromDiff`). Runners persist it as the
* edge's ledger-linked contract row so database tooling can render
* model-level diffs per applied migration; an edge's *before* state is
* the previous row's snapshot by chain construction. Absent when the
* source bundle carries no snapshot.
* source bundle's snapshot store entry cannot be resolved.
*/

@@ -133,0 +133,0 @@ readonly destinationContractJson?: unknown;

@@ -91,2 +91,7 @@ import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';

ownership: input.ownership,
// This plan is wrapped as a plain `MigrationPlan` below (no authoring
// surface) and applied directly — `renderTypeScript()` is never called
// for a diff-fabricated reconciliation plan, so there is no migration
// package dir to compute a real snapshots import path from.
snapshotsImportPath: '',
}) as MaybeAsyncPlannerResult);

@@ -93,0 +98,0 @@

@@ -26,3 +26,2 @@ import type { Contract } from '@prisma-next/contract/types';

readonly provenance: 'graph-node';
readonly sourceDir: string;
readonly hash: string;

@@ -59,12 +58,14 @@ readonly contractJson: unknown;

* produced on first call and memoised. For the app it is the live
* contract the caller supplied; for an extension it is the on-disk
* `migrations/<spaceId>/contract.json` run through the family's
* `deserializeContract`. Throws if the on-disk contract is missing or
* undeserializable (surfaced as `contractUnreadable` by `checkIntegrity`
* under `checkContracts`); callers gate before querying it.
* contract the caller supplied; for an extension it is the contract
* snapshot store entry keyed by the space's head ref hash, run through
* the family's `deserializeContract`. Throws if the store entry is
* missing or undeserializable (surfaced as `contractUnreadable` by
* `checkIntegrity` under `checkContracts`); callers gate before
* querying it.
* - `contractAt(hash, opts?)`: materializes the contract at an arbitrary
* graph node — when `opts.refName` is set, prefer the ref's paired
* snapshot; else find the package whose `metadata.to === hash` and read
* its `end-contract.*`. Lazy per `(hash, refName?)` memoisation; throws
* typed {@link MigrationToolsError} values compatible with CLI mappers.
* the contract snapshot store entry keyed by that hash. Lazy per
* `(hash, refName?)` memoisation; throws typed {@link MigrationToolsError}
* values compatible with CLI mappers.
*/

@@ -71,0 +72,0 @@ export interface AggregateContractSpace {

@@ -72,3 +72,3 @@ import { EMPTY_CONTRACT_HASH } from './constants';

*
* Reads only on-disk artefacts (`migrations/<spaceId>/refs/head.json`
* Reads only on-disk artifacts (`migrations/<spaceId>/refs/head.json`
* and the per-space migration packages). **Does not import any

@@ -101,3 +101,3 @@ * extension descriptor module** — `db init` / `db update` must remain

const spaceDir = spaceMigrationDirectory(projectMigrationsDir, spaceId);
const { packages } = await readMigrationsDir(spaceDir);
const { packages } = await readMigrationsDir(spaceDir, { migrationsDir: projectMigrationsDir });
const graph = reconstructGraph(packages);

@@ -104,0 +104,0 @@

@@ -424,3 +424,3 @@ import { ifDefined } from '@prisma-next/utils/defined';

return new MigrationToolsError('MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE', summary, {
why: `The hash ${hash} is a graph node but no on-disk migration package has an end-contract hash matching it.`,
why: `The hash ${hash} is a graph node but no on-disk migration package has a destination (\`to\`) hash matching it.`,
fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',

@@ -460,2 +460,33 @@ details: { hash, ...(explicitLabel ? { explicitLabel } : {}) },

export function errorContractSnapshotMissing(
storageHash: string,
expectedPath: string,
): MigrationToolsError {
return new MigrationToolsError(
'MIGRATION.CONTRACT_SNAPSHOT_MISSING',
'Contract snapshot is missing',
{
why: `Expected a contract snapshot for ${storageHash} at "${expectedPath}" but the file does not exist.`,
fix: "Re-emit the contract snapshot by re-running the command that authored the migration referencing this hash (`prisma-next migration plan` for app-space migrations; the extension's contract-space build for extension spaces), or restore migrations/snapshots/ from version control.",
details: { storageHash, expectedPath },
},
);
}
export function errorContractSnapshotHashMismatch(
storageHash: string,
actualHash: string,
dir: string,
): MigrationToolsError {
return new MigrationToolsError(
'MIGRATION.CONTRACT_SNAPSHOT_HASH_MISMATCH',
'Contract snapshot hash mismatch',
{
why: `The contract JSON's inner storage.storageHash ("${actualHash}") does not match the requested storage hash ("${storageHash}") for snapshot directory "${dir}".`,
fix: 'Pass a contractJson whose storage.storageHash equals the storageHash argument passed to writeContractSnapshot — the two must agree by construction.',
details: { storageHash, actualHash, dir },
},
);
}
export function errorMigrationContractViewMissing(

@@ -462,0 +493,0 @@ className: string,

export {
errorContractSnapshotHashMismatch,
errorContractSnapshotMissing,
errorDescriptorHeadHashMismatch,

@@ -3,0 +5,0 @@ errorInvalidJson,

@@ -13,5 +13,5 @@ export {

export {
type ContractSpaceArtefactInputs,
emitContractSpaceArtefacts,
} from '../emit-contract-space-artefacts';
type ContractSpaceArtifactInputs,
emitContractSpaceArtifacts,
} from '../emit-contract-space-artifacts';
export {

@@ -26,3 +26,2 @@ type DiskContractSpaceState,

} from '../plan-all-spaces';
export { readContractSpaceContract } from '../read-contract-space-contract';
export {

@@ -29,0 +28,0 @@ type ContractSpaceHeadRef,

+23
-38

@@ -9,2 +9,3 @@ import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';

import { basename, dirname, join, resolve } from 'pathe';
import { readContractSnapshotJsonTolerant } from './contract-snapshot-store';
import {

@@ -28,5 +29,8 @@ errorDirectoryExists,

const OPS_FILE = 'ops.json';
const END_CONTRACT_FILE = 'end-contract.json';
const MAX_SLUG_LENGTH = 64;
export interface ReadMigrationPackageOptions {
readonly migrationsDir: string;
}
function hasErrnoCode(error: unknown, code: string): boolean {

@@ -91,5 +95,5 @@ return error instanceof Error && (error as { code?: string }).code === code;

*
* The per-space head contract lives at
* `<projectMigrationsDir>/<spaceId>/contract.json` (written by
* {@link import('./emit-contract-space-artefacts').emitContractSpaceArtefacts}),
* The per-space head contract resolves through
* `<projectMigrationsDir>/snapshots/<hex>/` (written by
* {@link import('./emit-contract-space-artifacts').emitContractSpaceArtifacts}),
* not inside the per-package directory. The runner reads only

@@ -155,6 +159,4 @@ * `migration.json` + `ops.json` from each package.

* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is
* intentionally generic: callers own the list of files (e.g. a contract
* emitter's emitted output) and the naming convention (e.g. renaming
* the destination contract to `end-contract.*` and the source contract
* to `start-contract.*`).
* intentionally generic: callers own the list of files and the naming
* convention for the copies.
*/

@@ -185,29 +187,6 @@ export async function copyFilesWithRename(

/**
* Reads the optional `end-contract.json` snapshot next to a migration
* manifest — the contract IR of the migration's destination state.
* Snapshots are author-time conveniences (ADR 197), never structural
* runner inputs, so a missing or unparseable file is treated as absent
* (`undefined`) — a package holding only `migration.json` + `ops.json`
* must keep loading (pinned regression in this package). A file holding
* the JSON literal `null` is also treated as absent: `undefined` is the
* single "no snapshot" sentinel downstream, and a null contract is not
* a storable state (the contract store's `contract_json` is NOT NULL).
*/
async function readEndContractJson(dir: string): Promise<unknown> {
let raw: string;
try {
raw = await readFile(join(dir, END_CONTRACT_FILE), 'utf-8');
} catch {
return undefined;
}
try {
const parsed: unknown = JSON.parse(raw);
return parsed === null ? undefined : parsed;
} catch {
return undefined;
}
}
export async function readMigrationPackage(dir: string): Promise<OnDiskMigrationPackage> {
export async function readMigrationPackage(
dir: string,
options: ReadMigrationPackageOptions,
): Promise<OnDiskMigrationPackage> {
const absoluteDir = resolve(dir);

@@ -265,3 +244,6 @@ const manifestPath = join(absoluteDir, MANIFEST_FILE);

const endContractJson = await readEndContractJson(absoluteDir);
const endContractJson = await readContractSnapshotJsonTolerant(
options.migrationsDir,
metadata.to,
);
const pkg: OnDiskMigrationPackage = {

@@ -414,3 +396,6 @@ dirName: basename(absoluteDir),

export async function readMigrationsDir(migrationsRoot: string): Promise<ReadMigrationsDirResult> {
export async function readMigrationsDir(
migrationsRoot: string,
options: ReadMigrationPackageOptions,
): Promise<ReadMigrationsDirResult> {
let entries: string[];

@@ -443,3 +428,3 @@ try {

try {
pkg = await readMigrationPackage(entryPath);
pkg = await readMigrationPackage(entryPath, options);
} catch (error) {

@@ -446,0 +431,0 @@ const dirName = entry;

@@ -41,5 +41,6 @@ import { realpathSync } from 'node:fs';

* one of two ways:
* - **Contract-derived (default):** assign the committed `start-contract.json`
* / `end-contract.json` imports to `startContractJson` / `endContractJson`;
* the concrete `describe()` below derives `to`/`from` from their
* - **Contract-derived (default):** assign the `contract.json` imports from
* the snapshot store (`migrations/snapshots/<hex>/contract.json`) to
* `startContractJson` / `endContractJson`; the concrete `describe()` below
* derives `to`/`from` from their
* `storage.storageHash`. The family bases additionally expose typed view

@@ -64,4 +65,4 @@ * getters (`startContract` / `endContract`) over the same JSON.

/**
* The migration's end-state contract JSON (the committed `end-contract.json`
* import). When set, the derived `describe()` reads `to` from its
* The migration's end-state contract JSON (the `contract.json` import from
* the snapshot store). When set, the derived `describe()` reads `to` from its
* `storage.storageHash`. Family bases build the typed `endContract` view from

@@ -79,4 +80,4 @@ * it. Optional so `describe()`-overriding migrations (no contract) compile.

/**
* The migration's start-state contract JSON (the committed
* `start-contract.json` import). Absent for a baseline migration (`from`
* The migration's start-state contract JSON (the `contract.json` import
* from the snapshot store). Absent for a baseline migration (`from`
* derives to `null`). Family bases build the typed `startContract` view from

@@ -83,0 +84,0 @@ * it.

@@ -1,2 +0,5 @@

import { APP_SPACE_ID } from '@prisma-next/framework-components/control';
import {
APP_SPACE_ID,
CONTRACT_SNAPSHOTS_DIRNAME,
} from '@prisma-next/framework-components/control';
import { join } from 'pathe';

@@ -61,10 +64,12 @@ import { errorInvalidSpaceId } from './errors';

/**
* Names reserved as per-space subdirectories of `migrations/<space>/`.
* Used by the enumerator to filter contract-space candidates so a
* reserved name (e.g. a top-level `migrations/refs/` left in the wrong
* place) is never enumerated as a phantom contract space. Currently
* holds `SPACE_REFS_DIRNAME`; extend if future per-space layouts add
* more reserved subdirectories.
* Names reserved under `migrations/` that must never be enumerated as a
* phantom contract space: `SPACE_REFS_DIRNAME` (e.g. a top-level
* `migrations/refs/` left in the wrong place) and
* `CONTRACT_SNAPSHOTS_DIRNAME` (the migrations-root-wide contract
* snapshot store, `migrations/snapshots/`).
*/
export const RESERVED_SPACE_SUBDIR_NAMES: ReadonlySet<string> = new Set([SPACE_REFS_DIRNAME]);
export const RESERVED_SPACE_SUBDIR_NAMES: ReadonlySet<string> = new Set([
SPACE_REFS_DIRNAME,
CONTRACT_SNAPSHOTS_DIRNAME,
]);

@@ -71,0 +76,0 @@ /**

import { readdir, stat } from 'node:fs/promises';
import { join } from 'pathe';
import { MANIFEST_FILE } from './io';
import { APP_SPACE_ID } from './space-layout';
import { APP_SPACE_ID, RESERVED_SPACE_SUBDIR_NAMES } from './space-layout';

@@ -13,7 +13,10 @@ function hasErrnoCode(error: unknown, code: string): boolean {

* `<projectRoot>/migrations/`. Returns space-id directory names (sorted
* alphabetically) — i.e. any non-dot-prefixed subdirectory whose root
* does **not** contain a `migration.json` manifest. The manifest is the
* alphabetically) — i.e. any non-dot-prefixed, non-reserved
* ({@link RESERVED_SPACE_SUBDIR_NAMES}) subdirectory whose root does
* **not** contain a `migration.json` manifest. The manifest is the
* structural marker of a user-authored migration directory (see
* `readMigrationsDir` in `./io`); directory names themselves belong to
* the user and are not part of the contract.
* the user and are not part of the contract. The reserved-name filter
* keeps `migrations/snapshots/` (the contract snapshot store) from ever
* being enumerated as a phantom contract space.
*

@@ -45,2 +48,3 @@ * Returns `[]` if the migrations directory does not exist (greenfield

.filter((name) => !name.startsWith('.'))
.filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name))
.sort();

@@ -68,3 +72,3 @@

* The verifier compares this against the marker row for the same space
* to detect drift between the user-emitted artefacts and the live DB
* to detect drift between the user-emitted artifacts and the live DB
* marker.

@@ -71,0 +75,0 @@ */

import { ifDefined } from "@prisma-next/utils/defined";
import { dirname, relative } from "pathe";
//#region src/errors.ts
/**
* Build the canonical "re-emit this package" remediation hint.
*
* Every on-disk migration package ships its own `migration.ts` author-time
* file. Running it regenerates `migration.json` and `ops.json` with the
* correct hash + metadata, so it is the right primitive whenever a single
* package's on-disk artifacts are missing, malformed, or otherwise corrupt.
* Pointing users at `migration plan` would emit a *new* package rather than
* heal the broken one.
*/
function reemitHint(dir, fallback) {
const reemit = `Re-emit the package by running \`node "${relative(process.cwd(), dir)}/migration.ts"\``;
return fallback ? `${reemit}, ${fallback}` : `${reemit}.`;
}
/**
* Structured error for migration tooling operations.
*
* Follows the NAMESPACE.SUBCODE convention from ADR 027. All codes live under
* the MIGRATION namespace. These are tooling-time errors (file I/O, hash
* verification, migration history reconstruction), distinct from the runtime
* MIGRATION.* codes for apply-time failures (PRECHECK_FAILED, POSTCHECK_FAILED,
* etc.).
*
* Fields:
* - code: Stable machine-readable code (MIGRATION.SUBCODE)
* - category: Always 'MIGRATION'
* - why: Explains the cause in plain language
* - fix: Actionable remediation step
* - details: Machine-readable structured data for agents
*/
var MigrationToolsError = class extends Error {
code;
category = "MIGRATION";
why;
fix;
details;
constructor(code, summary, options) {
super(summary);
this.name = "MigrationToolsError";
this.code = code;
this.why = options.why;
this.fix = options.fix;
this.details = options.details;
}
static is(error) {
if (!(error instanceof Error)) return false;
const candidate = error;
return candidate.name === "MigrationToolsError" && typeof candidate.code === "string";
}
};
function errorDirectoryExists(dir) {
return new MigrationToolsError("MIGRATION.DIR_EXISTS", "Migration directory already exists", {
why: `The directory "${dir}" already exists. Each migration must have a unique directory.`,
fix: "Use --name to pick a different name, or delete the existing directory and re-run.",
details: { dir }
});
}
function errorMissingFile(file, dir) {
return new MigrationToolsError("MIGRATION.FILE_MISSING", `Missing ${file}`, {
why: `Expected "${file}" in "${dir}" but the file does not exist.`,
fix: reemitHint(dir, "or delete the directory if the migration is unwanted and the source TypeScript is gone."),
details: {
file,
dir
}
});
}
function errorInvalidJson(filePath, parseError) {
return new MigrationToolsError("MIGRATION.INVALID_JSON", "Invalid JSON in migration file", {
why: `Failed to parse "${filePath}": ${parseError}`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
parseError
}
});
}
function errorInvalidManifest(filePath, reason) {
return new MigrationToolsError("MIGRATION.INVALID_MANIFEST", "Invalid migration manifest", {
why: `Migration manifest at "${filePath}" is invalid: ${reason}`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
reason
}
});
}
function errorInvalidOperationEntry(index, reason) {
return new MigrationToolsError("MIGRATION.INVALID_OPERATION_ENTRY", "Migration operation entry is malformed", {
why: `Operation at index ${index} returned by the migration class failed schema validation: ${reason}.`,
fix: "Update the migration class so each entry of `operations` carries `id` (string), `label` (string), and `operationClass` (one of 'additive' | 'widening' | 'destructive' | 'data').",
details: {
index,
reason
}
});
}
function errorInvalidSlug(slug) {
return new MigrationToolsError("MIGRATION.INVALID_NAME", "Invalid migration name", {
why: `The slug "${slug}" contains no valid characters after sanitization (only a-z, 0-9 are kept).`,
fix: "Provide a name with at least one alphanumeric character, e.g. --name add_users.",
details: { slug }
});
}
function errorInvalidDestName(destName) {
return new MigrationToolsError("MIGRATION.INVALID_DEST_NAME", "Invalid copy destination name", {
why: `The destination name "${destName}" must be a single path segment (no ".." or directory separators).`,
fix: "Use a simple file name such as \"contract.json\" for each destination in the copy list.",
details: { destName }
});
}
function errorInvalidSpaceId(spaceId) {
return new MigrationToolsError("MIGRATION.INVALID_SPACE_ID", "Invalid contract space identifier", {
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.`,
fix: "Pick a lowercase identifier that begins with a letter and contains only lowercase letters, digits, hyphens, or underscores; max 64 characters total.",
details: { spaceId }
});
}
function errorDescriptorHeadHashMismatch(args) {
const { extensionId, recomputedHash, headRefHash } = args;
return new MigrationToolsError("MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH", "Extension descriptor's headRef.hash does not match its contractJson", {
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.`,
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).",
details: {
extensionId,
recomputedHash,
headRefHash
}
});
}
function errorDuplicateSpaceId(spaceId) {
return new MigrationToolsError("MIGRATION.DUPLICATE_SPACE_ID", "Duplicate contract space identifier", {
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).`,
fix: "Deduplicate the inputs before passing them to `planAllSpaces` — typically by checking your `extensionPacks` declaration for repeated entries.",
details: { spaceId }
});
}
function errorAmbiguousTarget(branchTips, context) {
const divergenceInfo = context ? `\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")}` : "";
return new MigrationToolsError("MIGRATION.AMBIGUOUS_TARGET", "Ambiguous migration target", {
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}`,
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.",
details: {
branchTips,
...context ? {
divergencePoint: context.divergencePoint,
branches: context.branches
} : {}
}
});
}
function errorNoInitialMigration(nodes) {
return new MigrationToolsError("MIGRATION.NO_INITIAL_MIGRATION", "No initial migration found", {
why: `No migration starts from the empty contract state (known hashes: ${nodes.join(", ")}). At least one migration must originate from the empty state.`,
fix: "Inspect the migrations directory for corrupted migration.json files. At least one migration must start from the empty contract hash.",
details: { nodes }
});
}
function errorInvalidRefFile(filePath, reason) {
return new MigrationToolsError("MIGRATION.INVALID_REF_FILE", "Invalid ref file", {
why: `Ref file at "${filePath}" is invalid: ${reason}`,
fix: "Ensure the ref file contains valid JSON with { \"hash\": \"sha256:<64 hex chars>\", \"invariants\": [\"...\"] }.",
details: {
path: filePath,
reason
}
});
}
function errorInvalidRefName(refName) {
return new MigrationToolsError("MIGRATION.INVALID_REF_NAME", "Invalid ref name", {
why: `Ref name "${refName}" is invalid. Names must be lowercase alphanumeric with hyphens or forward slashes (no "." or ".." segments).`,
fix: `Use a valid ref name (e.g., "staging", "envs/production").`,
details: { refName }
});
}
function errorNoTarget(reachableHashes) {
return new MigrationToolsError("MIGRATION.NO_TARGET", "No migration target could be resolved", {
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).`,
fix: "Use --from <hash> to specify the planning origin explicitly.",
details: { reachableHashes }
});
}
function errorInvalidRefValue(value) {
return new MigrationToolsError("MIGRATION.INVALID_REF_VALUE", "Invalid ref value", {
why: `Ref value "${value}" is not a valid contract hash. Values must be in the format "sha256:<64 hex chars>" or "sha256:empty".`,
fix: "Use a valid storage hash from `prisma-next contract emit` output or an existing migration.",
details: { value }
});
}
function errorInvalidInvariantId(invariantId) {
return new MigrationToolsError("MIGRATION.INVALID_INVARIANT_ID", "Invalid invariantId", {
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.`,
fix: "Pick an invariantId without spaces, tabs, newlines, or control characters — e.g. \"backfill-user-phone\", \"users/backfill-phone\", or \"BackfillUserPhone\".",
details: { invariantId }
});
}
function errorDuplicateInvariantInEdge(invariantId) {
return new MigrationToolsError("MIGRATION.DUPLICATE_INVARIANT_IN_EDGE", "Duplicate invariantId on a single migration", {
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.`,
fix: "Rename one of the conflicting dataTransform invariantIds, or drop invariantId on the op that does not need to be routing-visible.",
details: { invariantId }
});
}
function errorProvidedInvariantsMismatch(filePath, stored, derived) {
const storedSet = new Set(stored);
const derivedSet = new Set(derived);
const missing = [...derivedSet].filter((id) => !storedSet.has(id));
const extra = [...storedSet].filter((id) => !derivedSet.has(id));
return new MigrationToolsError("MIGRATION.PROVIDED_INVARIANTS_MISMATCH", "providedInvariants on migration.json disagrees with ops.json", {
why: missing.length === 0 && extra.length === 0 ? `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.` : `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.`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
stored,
derived,
difference: {
missing,
extra
}
}
});
}
function errorNoInvariantPath(args) {
const { refName, required, missing, structuralPath } = args;
const refClause = refName ? `Ref "${refName}"` : "Target";
const missingList = missing.map((id) => JSON.stringify(id)).join(", ");
return new MigrationToolsError("MIGRATION.NO_INVARIANT_PATH", "No path covers the required invariants", {
why: `${refClause} requires invariants the reachable path doesn't cover. required=[${required.map((id) => JSON.stringify(id)).join(", ")}], missing=[${missingList}].`,
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.",
details: {
required,
missing,
structuralPath,
...ifDefined("refName", refName)
}
});
}
function errorUnknownInvariant(args) {
const { refName, unknown, declared } = args;
return new MigrationToolsError("MIGRATION.UNKNOWN_INVARIANT", "Ref declares invariants no migration in the graph provides", {
why: `${refName ? `Ref "${refName}" declares` : "Declares"} invariants no migration in the graph provides. unknown=[${unknown.map((id) => JSON.stringify(id)).join(", ")}].`,
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.",
details: {
unknown,
declared,
...ifDefined("refName", refName)
}
});
}
function errorMigrationHashMismatch(dir, storedHash, computedHash) {
return new MigrationToolsError("MIGRATION.HASH_MISMATCH", "Migration package is corrupt", {
why: `Stored migrationHash "${storedHash}" does not match the recomputed hash "${computedHash}" for "${relative(process.cwd(), dir)}". The migration.json or ops.json has been edited or partially written since emit.`,
fix: reemitHint(dir, "or restore the directory from version control."),
details: {
dir,
storedHash,
computedHash
}
});
}
function errorSnapshotMissing(refName) {
return new MigrationToolsError("MIGRATION.SNAPSHOT_MISSING", `Ref "${refName}" has no paired contract snapshot`, {
why: `Ref "${refName}" exists but its paired snapshot files are missing.`,
fix: `Run "prisma-next db update --advance-ref ${refName}" to repopulate the snapshot, or "prisma-next ref delete ${refName}" to clear the orphan pointer.`,
details: {
refName,
identifier: refName,
viaRef: true
}
});
}
function errorBundleNotFoundForGraphNode(hash, explicitLabel) {
return new MigrationToolsError("MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE", explicitLabel ? `No migration bundle found for reference "${explicitLabel}" (resolved hash: ${hash})` : `No migration bundle found for graph node ${hash}`, {
why: `The hash ${hash} is a graph node but no on-disk migration package has an end-contract hash matching it.`,
fix: "Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.",
details: {
hash,
...explicitLabel ? { explicitLabel } : {}
}
});
}
function errorContractDeserializationFailed(filePath, message) {
return new MigrationToolsError("MIGRATION.CONTRACT_DESERIALIZATION_FAILED", "Contract failed to deserialize", {
why: `Contract at "${filePath}" failed to deserialize: ${message}`,
fix: reemitHint(dirname(filePath), "or restore the directory from version control."),
details: {
filePath,
message
}
});
}
function errorHashNotInGraph(hash, graph) {
const reachableHashes = [...graph.nodes].sort();
const reachableList = reachableHashes.length > 0 ? reachableHashes.join(", ") : "(none)";
return new MigrationToolsError("MIGRATION.HASH_NOT_IN_GRAPH", `Hash "${hash}" is not a node in the migration graph`, {
why: `The migration graph contains nodes ${reachableList}; "${hash}" isn't one of them.`,
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.`,
details: {
hash,
reachableHashes
}
});
}
function errorMigrationContractViewMissing(className, accessor, jsonField) {
return new MigrationToolsError("MIGRATION.CONTRACT_VIEW_MISSING", `${className}.${accessor} requires ${jsonField}`, {
why: `${className}.${accessor} was read, but this instance has no ${jsonField} to build the view from.`,
fix: `Set ${jsonField} to the migration's committed contract JSON, or avoid reading ${accessor} on a migration that overrides describe() and carries no contract.`,
details: {
className,
accessor,
jsonField
}
});
}
//#endregion
export { errorNoInitialMigration as C, errorSnapshotMissing as D, errorProvidedInvariantsMismatch as E, errorUnknownInvariant as O, errorMissingFile as S, errorNoTarget as T, errorInvalidRefValue as _, errorDescriptorHeadHashMismatch as a, errorMigrationContractViewMissing as b, errorDuplicateSpaceId as c, errorInvalidInvariantId as d, errorInvalidJson as f, errorInvalidRefName as g, errorInvalidRefFile as h, errorContractDeserializationFailed as i, errorHashNotInGraph as l, errorInvalidOperationEntry as m, errorAmbiguousTarget as n, errorDirectoryExists as o, errorInvalidManifest as p, errorBundleNotFoundForGraphNode as r, errorDuplicateInvariantInEdge as s, MigrationToolsError as t, errorInvalidDestName as u, errorInvalidSlug as v, errorNoInvariantPath as w, errorMigrationHashMismatch as x, errorInvalidSpaceId as y };
//# sourceMappingURL=errors-DIS_dcFJ.mjs.map
{"version":3,"file":"errors-DIS_dcFJ.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 errorSnapshotMissing(refName: string): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.SNAPSHOT_MISSING',\n `Ref \"${refName}\" has no paired contract snapshot`,\n {\n why: `Ref \"${refName}\" exists but its paired snapshot files are missing.`,\n fix: `Run \"prisma-next db update --advance-ref ${refName}\" to repopulate the snapshot, or \"prisma-next ref delete ${refName}\" to clear the orphan pointer.`,\n details: { refName, identifier: refName, viaRef: true },\n },\n );\n}\n\nexport function errorBundleNotFoundForGraphNode(\n hash: string,\n explicitLabel?: string,\n): MigrationToolsError {\n const summary = explicitLabel\n ? `No migration bundle found for reference \"${explicitLabel}\" (resolved hash: ${hash})`\n : `No migration bundle found for graph node ${hash}`;\n return new MigrationToolsError('MIGRATION.BUNDLE_NOT_FOUND_FOR_GRAPH_NODE', summary, {\n why: `The hash ${hash} is a graph node but no on-disk migration package has an end-contract hash matching it.`,\n fix: 'Provide a ref or hash that corresponds to an existing migration package, or run `migration list` to see available migrations.',\n details: { hash, ...(explicitLabel ? { explicitLabel } : {}) },\n });\n}\n\nexport function errorContractDeserializationFailed(\n filePath: string,\n message: string,\n): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.CONTRACT_DESERIALIZATION_FAILED',\n 'Contract failed to deserialize',\n {\n why: `Contract at \"${filePath}\" failed to deserialize: ${message}`,\n fix: reemitHint(dirname(filePath), 'or restore the directory from version control.'),\n details: { filePath, message },\n },\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\nexport function errorMigrationContractViewMissing(\n className: string,\n accessor: 'endContract' | 'startContract',\n jsonField: 'endContractJson' | 'startContractJson',\n): MigrationToolsError {\n return new MigrationToolsError(\n 'MIGRATION.CONTRACT_VIEW_MISSING',\n `${className}.${accessor} requires ${jsonField}`,\n {\n why: `${className}.${accessor} was read, but this instance has no ${jsonField} to build the view from.`,\n fix: `Set ${jsonField} to the migration's committed contract JSON, or avoid reading ${accessor} on a migration that overrides describe() and carries no contract.`,\n details: { className, accessor, jsonField },\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,SAAS,WAAW,KAAa,UAA2B;CAE1D,MAAM,SAAS,0CADK,SAAS,QAAQ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E;GAAU;EAAQ;CAC/B,CACF;AACF;AAEA,SAAgB,oBAAoB,MAAc,OAA4C;CAC5F,MAAM,kBAAkB,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC,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;AAEA,SAAgB,kCACd,WACA,UACA,WACqB;CACrB,OAAO,IAAI,oBACT,mCACA,GAAG,UAAU,GAAG,SAAS,YAAY,aACrC;EACE,KAAK,GAAG,UAAU,GAAG,SAAS,sCAAsC,UAAU;EAC9E,KAAK,OAAO,UAAU,gEAAgE,SAAS;EAC/F,SAAS;GAAE;GAAW;GAAU;EAAU;CAC5C,CACF;AACF"}
import { l as errorHashNotInGraph } from "./errors-DIS_dcFJ.mjs";
import "./constants-YnG8_EGO.mjs";
//#region src/graph-membership.ts
function isGraphNode(hash, graph) {
if (hash === "sha256:empty") return true;
return graph.nodes.has(hash);
}
function assertHashIsGraphNode(hash, graph) {
if (isGraphNode(hash, graph)) return;
throw errorHashNotInGraph(hash, graph);
}
//#endregion
export { isGraphNode as n, assertHashIsGraphNode as t };
//# sourceMappingURL=graph-membership-CNneL_Yy.mjs.map
{"version":3,"file":"graph-membership-CNneL_Yy.mjs","names":[],"sources":["../src/graph-membership.ts"],"sourcesContent":["import { EMPTY_CONTRACT_HASH } from './constants';\nimport { errorHashNotInGraph } from './errors';\nimport type { MigrationGraph } from './graph';\n\nexport function isGraphNode(hash: string, graph: MigrationGraph): boolean {\n if (hash === EMPTY_CONTRACT_HASH) {\n return true;\n }\n return graph.nodes.has(hash);\n}\n\nexport function assertHashIsGraphNode(hash: string, graph: MigrationGraph): asserts hash is string {\n if (isGraphNode(hash, graph)) {\n return;\n }\n throw errorHashNotInGraph(hash, graph);\n}\n"],"mappings":";;;AAIA,SAAgB,YAAY,MAAc,OAAgC;CACxE,IAAI,SAAA,gBACF,OAAO;CAET,OAAO,MAAM,MAAM,IAAI,IAAI;AAC7B;AAEA,SAAgB,sBAAsB,MAAc,OAA+C;CACjG,IAAI,YAAY,MAAM,KAAK,GACzB;CAEF,MAAM,oBAAoB,MAAM,KAAK;AACvC"}
import { d as errorInvalidInvariantId, s as errorDuplicateInvariantInEdge } from "./errors-DIS_dcFJ.mjs";
//#region src/invariants.ts
/**
* Hygiene check for `invariantId`. Rejects empty values plus any
* whitespace or control character (including Unicode whitespace like
* NBSP and em space, which are visually identical to ASCII space and
* routinely sneak in via paste).
*/
function validateInvariantId(invariantId) {
if (invariantId.length === 0) return false;
return !/[\p{Cc}\p{White_Space}]/u.test(invariantId);
}
/**
* Walk a migration's operations and produce its `providedInvariants`
* aggregate: the sorted, deduplicated list of `invariantId`s declared
* by ops in the migration. Ops without an `invariantId` are skipped.
*
* Both `data`-class ops (data-transforms, e.g. backfills) and
* `additive`-class opaque DDL (e.g. cipherstash's vendored EQL bundle
* via `installEqlBundleOp`) may declare invariantIds: the
* `operationClass` axis classifies *policy gating* (which kinds of ops
* a `db init` / `db update` policy permits), while `invariantId`
* classifies *marker bookkeeping* (which named bundles of work a
* future regeneration knows to skip). The two concerns are
* intentionally orthogonal — an extension can ship additive
* non-IR-derivable DDL (the only way the planner can know the bundle
* is already applied is via the invariantId on the marker) without
* needing to mis-classify it as `data`-class.
*
* Throws `MIGRATION.INVALID_INVARIANT_ID` on a malformed id and
* `MIGRATION.DUPLICATE_INVARIANT_IN_EDGE` on duplicates.
*
* @see docs/architecture docs/adrs/ADR 212 - Contract spaces.md
* — extension migrations carry `invariantId`s on additive ops; e.g.
* cipherstash's `installEqlBundle` and structural `create-*` ops are
* additive-class but carry `cipherstash:*` invariantIds.
*/
function deriveProvidedInvariants(ops) {
const seen = /* @__PURE__ */ new Set();
for (const op of ops) {
const invariantId = readInvariantId(op);
if (invariantId === void 0) continue;
if (!validateInvariantId(invariantId)) throw errorInvalidInvariantId(invariantId);
if (seen.has(invariantId)) throw errorDuplicateInvariantInEdge(invariantId);
seen.add(invariantId);
}
return [...seen].sort();
}
function readInvariantId(op) {
if (!Object.hasOwn(op, "invariantId")) return void 0;
const candidate = op.invariantId;
return typeof candidate === "string" ? candidate : void 0;
}
//#endregion
export { validateInvariantId as n, deriveProvidedInvariants as t };
//# sourceMappingURL=invariants-CH8ATaEp.mjs.map
{"version":3,"file":"invariants-CH8ATaEp.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 *\n * @see docs/architecture docs/adrs/ADR 212 - Contract spaces.md\n * — extension migrations carry `invariantId`s on additive ops; e.g.\n * cipherstash's `installEqlBundle` and structural `create-*` ops are\n * additive-class but carry `cipherstash:*` invariantIds.\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,WAAW;AACrD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,yBAAyB,KAAsC;CAC7E,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,cAAc,gBAAgB,EAAE;EACtC,IAAI,gBAAgB,KAAA,GAAW;EAC/B,IAAI,CAAC,oBAAoB,WAAW,GAClC,MAAM,wBAAwB,WAAW;EAE3C,IAAI,KAAK,IAAI,WAAW,GACtB,MAAM,8BAA8B,WAAW;EAEjD,KAAK,IAAI,WAAW;CACtB;CACA,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,KAAK;AACxB;AAEA,SAAS,gBAAgB,IAAgD;CACvE,IAAI,CAAC,OAAO,OAAO,IAAI,aAAa,GAAG,OAAO,KAAA;CAC9C,MAAM,YAAa,GAAiC;CACpD,OAAO,OAAO,cAAc,WAAW,YAAY,KAAA;AACrD"}
import { E as errorProvidedInvariantsMismatch, S as errorMissingFile, f as errorInvalidJson, o as errorDirectoryExists, p as errorInvalidManifest, t as MigrationToolsError, u as errorInvalidDestName, v as errorInvalidSlug, x as errorMigrationHashMismatch } from "./errors-DIS_dcFJ.mjs";
import { n as verifyMigrationHash } from "./hash-BNCgfhir.mjs";
import { t as deriveProvidedInvariants } from "./invariants-CH8ATaEp.mjs";
import { n as MigrationOpsSchema } from "./op-schema-BSVHzEQN.mjs";
import { ifDefined } from "@prisma-next/utils/defined";
import { basename, dirname, join, resolve } from "pathe";
import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { type } from "arktype";
//#region src/io.ts
const MANIFEST_FILE = "migration.json";
const OPS_FILE = "ops.json";
const END_CONTRACT_FILE = "end-contract.json";
const MAX_SLUG_LENGTH = 64;
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
const MigrationMetadataSchema = type({
"+": "reject",
from: "string > 0 | null",
to: "string",
migrationHash: "string",
providedInvariants: "string[]",
createdAt: "string"
});
async function writeMigrationPackage(dir, metadata, ops) {
await mkdir(dirname(dir), { recursive: true });
try {
await mkdir(dir);
} catch (error) {
if (hasErrnoCode(error, "EEXIST")) throw errorDirectoryExists(dir);
throw error;
}
await writeFile(join(dir, MANIFEST_FILE), JSON.stringify(metadata, null, 2), { flag: "wx" });
await writeFile(join(dir, OPS_FILE), JSON.stringify(ops, null, 2), { flag: "wx" });
}
/**
* Materialise an in-memory {@link MigrationPackage} to a per-space
* directory on disk.
*
* Writes two files under `<targetDir>/<pkg.dirName>/`:
*
* - `migration.json` — the manifest (pretty-printed, matches
* {@link writeMigrationPackage}'s output for byte-for-byte parity with
* app-space migrations).
* - `ops.json` — the operation list (pretty-printed).
*
* Distinct verb from the lower-level {@link writeMigrationPackage}
* (which takes constituent `(metadata, ops)`): callers reading
* `materialise…` know they are persisting a struct-typed package.
*
* Overwrite-idempotent: the per-package directory is cleared before
* each emit, so re-running against the same `targetDir` produces
* byte-identical contents and never leaves stale files behind. The
* lower-level {@link writeMigrationPackage} stays strict because the
* CLI authoring path (`migration plan` / `migration new`) deliberately
* refuses to clobber an existing authored migration; this helper is
* the re-emit path that is supposed to converge on a single canonical
* on-disk shape.
*
* The per-space head contract lives at
* `<projectMigrationsDir>/<spaceId>/contract.json` (written by
* {@link import('./emit-contract-space-artefacts').emitContractSpaceArtefacts}),
* not inside the per-package directory. The runner reads only
* `migration.json` + `ops.json` from each package.
*/
async function materialiseMigrationPackage(targetDir, pkg) {
const dir = join(targetDir, pkg.dirName);
await rm(dir, {
recursive: true,
force: true
});
await writeMigrationPackage(dir, pkg.metadata, pkg.ops);
}
/**
* Idempotent variant of {@link materialiseMigrationPackage}: writes the
* package only if `<targetDir>/<pkg.dirName>/` does not already exist on
* disk as a directory; returns `{ written: false }` when the package
* directory is present (no rewrite, no comparison — by-existence skip).
*
* Concretely:
* - existing directory → skip silently, return `{ written: false }`.
* - missing path → write three files via {@link materialiseMigrationPackage},
* return `{ written: true }`.
* - path exists but is not a directory (file/symlink) → treated as
* missing; {@link materialiseMigrationPackage} will attempt creation
* and fail with an appropriate OS error.
* - any other I/O error from `stat` → propagated unchanged.
*
* Used by the CLI's `runContractSpaceExtensionMigrationsPass` to
* materialise extension migration packages into a project's
* `migrations/<spaceId>/` directory, and by extension-package tests
* that mirror the same idempotent-rematerialise property locally
* without taking a CLI dependency.
*/
async function materialiseExtensionMigrationPackageIfMissing(targetDir, pkg) {
if (await directoryExists(join(targetDir, pkg.dirName))) return { written: false };
await materialiseMigrationPackage(targetDir, pkg);
return { written: true };
}
async function directoryExists(p) {
try {
return (await stat(p)).isDirectory();
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return false;
throw error;
}
}
/**
* Copy a list of files into `destDir`, optionally renaming each one.
*
* The destination directory is created (with `recursive: true`) if it
* does not already exist. Each source path is copied byte-for-byte into
* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is
* intentionally generic: callers own the list of files (e.g. a contract
* emitter's emitted output) and the naming convention (e.g. renaming
* the destination contract to `end-contract.*` and the source contract
* to `start-contract.*`).
*/
async function copyFilesWithRename(destDir, files) {
await mkdir(destDir, { recursive: true });
for (const file of files) {
if (basename(file.destName) !== file.destName) throw errorInvalidDestName(file.destName);
await copyFile(file.sourcePath, join(destDir, file.destName));
}
}
async function writeMigrationMetadata(dir, metadata) {
await writeFile(join(dir, MANIFEST_FILE), `${JSON.stringify(metadata, null, 2)}\n`);
}
async function writeMigrationOps(dir, ops) {
await writeFile(join(dir, OPS_FILE), `${JSON.stringify(ops, null, 2)}\n`);
}
/**
* Reads the optional `end-contract.json` snapshot next to a migration
* manifest — the contract IR of the migration's destination state.
* Snapshots are author-time conveniences (ADR 197), never structural
* runner inputs, so a missing or unparseable file is treated as absent
* (`undefined`) — a package holding only `migration.json` + `ops.json`
* must keep loading (pinned regression in this package). A file holding
* the JSON literal `null` is also treated as absent: `undefined` is the
* single "no snapshot" sentinel downstream, and a null contract is not
* a storable state (the contract store's `contract_json` is NOT NULL).
*/
async function readEndContractJson(dir) {
let raw;
try {
raw = await readFile(join(dir, END_CONTRACT_FILE), "utf-8");
} catch {
return;
}
try {
const parsed = JSON.parse(raw);
return parsed === null ? void 0 : parsed;
} catch {
return;
}
}
async function readMigrationPackage(dir) {
const absoluteDir = resolve(dir);
const manifestPath = join(absoluteDir, MANIFEST_FILE);
const opsPath = join(absoluteDir, OPS_FILE);
let manifestRaw;
try {
manifestRaw = await readFile(manifestPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile(MANIFEST_FILE, absoluteDir);
throw error;
}
let opsRaw;
try {
opsRaw = await readFile(opsPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile(OPS_FILE, absoluteDir);
throw error;
}
let metadata;
try {
metadata = JSON.parse(manifestRaw);
} catch (e) {
throw errorInvalidJson(manifestPath, e instanceof Error ? e.message : String(e));
}
let ops;
try {
ops = JSON.parse(opsRaw);
} catch (e) {
throw errorInvalidJson(opsPath, e instanceof Error ? e.message : String(e));
}
validateMetadata(metadata, manifestPath);
validateOps(ops, opsPath);
const derivedInvariants = deriveProvidedInvariants(ops);
if (!arraysEqual(metadata.providedInvariants, derivedInvariants)) throw errorProvidedInvariantsMismatch(manifestPath, metadata.providedInvariants, derivedInvariants);
const endContractJson = await readEndContractJson(absoluteDir);
const pkg = {
dirName: basename(absoluteDir),
dirPath: absoluteDir,
metadata,
ops,
...ifDefined("endContractJson", endContractJson)
};
const verification = verifyMigrationHash(pkg);
if (!verification.ok) throw errorMigrationHashMismatch(absoluteDir, verification.storedHash, verification.computedHash);
return pkg;
}
/**
* Reads a migration package's manifest and ops without running hash or
* invariants verification. Returns `null` when the files cannot be read or
* parsed (i.e. when the package is genuinely unloadable).
*
* Used by {@link readMigrationsDir} to retain a package whose hash or
* invariants diverge from what is stored on disk — the raw content is still
* useful for display / querying; only integrity is in question.
*/
async function readMigrationPackageRaw(dir) {
const absoluteDir = resolve(dir);
const manifestPath = join(absoluteDir, MANIFEST_FILE);
const opsPath = join(absoluteDir, OPS_FILE);
let manifestRaw;
try {
manifestRaw = await readFile(manifestPath, "utf-8");
} catch {
return null;
}
let opsRaw;
try {
opsRaw = await readFile(opsPath, "utf-8");
} catch {
return null;
}
let metadata;
try {
metadata = JSON.parse(manifestRaw);
} catch {
return null;
}
let ops;
try {
ops = JSON.parse(opsRaw);
} catch {
return null;
}
if (MigrationMetadataSchema(metadata) instanceof type.errors) return null;
if (MigrationOpsSchema(ops) instanceof type.errors) return null;
return {
dirName: basename(absoluteDir),
dirPath: absoluteDir,
metadata,
ops
};
}
function arraysEqual(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
function validateMetadata(metadata, filePath) {
const result = MigrationMetadataSchema(metadata);
if (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);
}
function validateOps(ops, filePath) {
const result = MigrationOpsSchema(ops);
if (result instanceof type.errors) throw errorInvalidManifest(filePath, result.summary);
}
function packageLoadProblemDetailFromError(error) {
if (MigrationToolsError.is(error)) return error.why;
if (error instanceof Error) return error.message;
return String(error);
}
async function readMigrationsDir(migrationsRoot) {
let entries;
try {
entries = await readdir(migrationsRoot);
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return {
packages: [],
problems: []
};
throw error;
}
const packages = [];
const problems = [];
for (const entry of entries.sort()) {
const entryPath = join(migrationsRoot, entry);
if (!(await stat(entryPath)).isDirectory()) continue;
const manifestPath = join(entryPath, MANIFEST_FILE);
try {
await stat(manifestPath);
} catch {
continue;
}
let pkg;
try {
pkg = await readMigrationPackage(entryPath);
} catch (error) {
const dirName = entry;
if (MigrationToolsError.is(error)) {
if (error.code === "MIGRATION.HASH_MISMATCH") {
const details = error.details;
const rawPkg = await readMigrationPackageRaw(entryPath);
if (rawPkg !== null) packages.push(rawPkg);
problems.push({
kind: "hashMismatch",
dirName,
stored: typeof details?.["storedHash"] === "string" ? details["storedHash"] : "",
computed: typeof details?.["computedHash"] === "string" ? details["computedHash"] : ""
});
continue;
}
if (error.code === "MIGRATION.PROVIDED_INVARIANTS_MISMATCH") {
const rawPkg = await readMigrationPackageRaw(entryPath);
if (rawPkg !== null) packages.push(rawPkg);
problems.push({
kind: "providedInvariantsMismatch",
dirName
});
continue;
}
}
problems.push({
kind: "packageUnloadable",
dirName,
detail: packageLoadProblemDetailFromError(error)
});
continue;
}
packages.push(pkg);
}
return {
packages,
problems
};
}
function formatMigrationDirName(timestamp, slug) {
const sanitized = slug.toLowerCase().replace(/[^a-z0-9]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
if (sanitized.length === 0) throw errorInvalidSlug(slug);
const truncated = sanitized.slice(0, MAX_SLUG_LENGTH);
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}`;
}
//#endregion
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 };
//# sourceMappingURL=io-CE79C4uK.mjs.map
{"version":3,"file":"io-CE79C4uK.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 { ifDefined } from '@prisma-next/utils/defined';\nimport { type } from 'arktype';\nimport { basename, dirname, join, resolve } from 'pathe';\nimport {\n errorDirectoryExists,\n errorInvalidDestName,\n errorInvalidJson,\n errorInvalidManifest,\n errorInvalidSlug,\n errorMigrationHashMismatch,\n errorMissingFile,\n errorProvidedInvariantsMismatch,\n MigrationToolsError,\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 END_CONTRACT_FILE = 'end-contract.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 MigrationMetadataSchema = type({\n '+': 'reject',\n from: 'string > 0 | null',\n to: 'string',\n migrationHash: 'string',\n providedInvariants: 'string[]',\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 two 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 *\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 *\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 * lower-level {@link writeMigrationPackage} stays strict because the\n * CLI authoring path (`migration plan` / `migration new`) deliberately\n * refuses to clobber an existing authored migration; this helper is\n * the re-emit path that is supposed to converge on a single canonical\n * on-disk shape.\n *\n * The per-space head contract lives at\n * `<projectMigrationsDir>/<spaceId>/contract.json` (written by\n * {@link import('./emit-contract-space-artefacts').emitContractSpaceArtefacts}),\n * not inside the per-package directory. The runner reads only\n * `migration.json` + `ops.json` from each package.\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}\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\n/**\n * Reads the optional `end-contract.json` snapshot next to a migration\n * manifest — the contract IR of the migration's destination state.\n * Snapshots are author-time conveniences (ADR 197), never structural\n * runner inputs, so a missing or unparseable file is treated as absent\n * (`undefined`) — a package holding only `migration.json` + `ops.json`\n * must keep loading (pinned regression in this package). A file holding\n * the JSON literal `null` is also treated as absent: `undefined` is the\n * single \"no snapshot\" sentinel downstream, and a null contract is not\n * a storable state (the contract store's `contract_json` is NOT NULL).\n */\nasync function readEndContractJson(dir: string): Promise<unknown> {\n let raw: string;\n try {\n raw = await readFile(join(dir, END_CONTRACT_FILE), 'utf-8');\n } catch {\n return undefined;\n }\n try {\n const parsed: unknown = JSON.parse(raw);\n return parsed === null ? undefined : parsed;\n } catch {\n return undefined;\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 endContractJson = await readEndContractJson(absoluteDir);\n const pkg: OnDiskMigrationPackage = {\n dirName: basename(absoluteDir),\n dirPath: absoluteDir,\n metadata,\n ops,\n ...ifDefined('endContractJson', endContractJson),\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\n/**\n * Reads a migration package's manifest and ops without running hash or\n * invariants verification. Returns `null` when the files cannot be read or\n * parsed (i.e. when the package is genuinely unloadable).\n *\n * Used by {@link readMigrationsDir} to retain a package whose hash or\n * invariants diverge from what is stored on disk — the raw content is still\n * useful for display / querying; only integrity is in question.\n */\nasync function readMigrationPackageRaw(dir: string): Promise<OnDiskMigrationPackage | null> {\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 {\n return null;\n }\n let opsRaw: string;\n try {\n opsRaw = await readFile(opsPath, 'utf-8');\n } catch {\n return null;\n }\n\n let metadata: MigrationMetadata;\n try {\n metadata = JSON.parse(manifestRaw);\n } catch {\n return null;\n }\n let ops: MigrationOps;\n try {\n ops = JSON.parse(opsRaw);\n } catch {\n return null;\n }\n\n const result = MigrationMetadataSchema(metadata);\n if (result instanceof type.errors) return null;\n\n const opsResult = MigrationOpsSchema(ops);\n if (opsResult instanceof type.errors) return null;\n\n // Deliberately no `endContractJson`: this loader only runs for packages\n // that failed hash / invariants verification, and a snapshot from an\n // unverifiable package must never reach the ledger's contract store.\n return {\n dirName: basename(absoluteDir),\n dirPath: absoluteDir,\n metadata,\n ops,\n };\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\n/**\n * A per-package load-time problem returned by {@link readMigrationsDir}.\n *\n * Three variants, matching the relocated throws from the load path:\n *\n * - `hashMismatch` — stored `migrationHash` differs from the recomputed value.\n * The package is **retained** in the returned `packages` array.\n * - `providedInvariantsMismatch` — `migration.json` declares different\n * `providedInvariants` than `ops.json` implies. The package is **retained**.\n * - `packageUnloadable` — the manifest is missing, unparseable, or schema-\n * invalid. The package is **omitted** from `packages`.\n *\n * Callers that need the `spaceId` context (e.g. the aggregate loader) attach\n * it when converting to {@link import('./integrity-violation').IntegrityViolation}.\n */\nexport type PackageLoadProblem =\n | {\n readonly kind: 'hashMismatch';\n readonly dirName: string;\n readonly stored: string;\n readonly computed: string;\n }\n | { readonly kind: 'providedInvariantsMismatch'; readonly dirName: string }\n | { readonly kind: 'packageUnloadable'; readonly dirName: string; readonly detail: string };\n\n/**\n * Result returned by {@link readMigrationsDir}.\n *\n * - `packages` — every package that could be read; hash-mismatched and\n * invariants-mismatched packages are included here (the problem is\n * represented rather than fatal).\n * - `problems` — one entry per package that had a load-time issue.\n * `packageUnloadable` entries are **not** in `packages`.\n */\nexport interface ReadMigrationsDirResult {\n readonly packages: readonly OnDiskMigrationPackage[];\n readonly problems: readonly PackageLoadProblem[];\n}\n\nfunction packageLoadProblemDetailFromError(error: unknown): string {\n if (MigrationToolsError.is(error)) return error.why;\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nexport async function readMigrationsDir(migrationsRoot: string): Promise<ReadMigrationsDirResult> {\n let entries: string[];\n try {\n entries = await readdir(migrationsRoot);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return { packages: [], problems: [] };\n }\n throw error;\n }\n\n const packages: OnDiskMigrationPackage[] = [];\n const problems: PackageLoadProblem[] = [];\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 let pkg: OnDiskMigrationPackage;\n try {\n pkg = await readMigrationPackage(entryPath);\n } catch (error) {\n const dirName = entry;\n if (MigrationToolsError.is(error)) {\n if (error.code === 'MIGRATION.HASH_MISMATCH') {\n const details = error.details;\n const rawPkg = await readMigrationPackageRaw(entryPath);\n if (rawPkg !== null) packages.push(rawPkg);\n problems.push({\n kind: 'hashMismatch',\n dirName,\n stored: typeof details?.['storedHash'] === 'string' ? details['storedHash'] : '',\n computed: typeof details?.['computedHash'] === 'string' ? details['computedHash'] : '',\n });\n continue;\n }\n if (error.code === 'MIGRATION.PROVIDED_INVARIANTS_MISMATCH') {\n const rawPkg = await readMigrationPackageRaw(entryPath);\n if (rawPkg !== null) packages.push(rawPkg);\n problems.push({ kind: 'providedInvariantsMismatch', dirName });\n continue;\n }\n }\n // Any other error (missing file, invalid JSON, invalid manifest schema) →\n // package unloadable; omit from packages.\n problems.push({\n kind: 'packageUnloadable',\n dirName,\n detail: packageLoadProblemDetailFromError(error),\n });\n continue;\n }\n packages.push(pkg);\n }\n\n return { packages, problems };\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":";;;;;;;;;AAwBA,MAAa,gBAAgB;AAC7B,MAAM,WAAW;AACjB,MAAM,oBAAoB;AAC1B,MAAM,kBAAkB;AAExB,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;AAEA,MAAM,0BAA0B,KAAK;CACnC,KAAK;CACL,MAAM;CACN,IAAI;CACJ,eAAe;CACf,oBAAoB;CACpB,WAAW;AACb,CAAC;AAED,eAAsB,sBACpB,KACA,UACA,KACe;CACf,MAAM,MAAM,QAAQ,GAAG,GAAG,EAAE,WAAW,KAAK,CAAC;CAE7C,IAAI;EACF,MAAM,MAAM,GAAG;CACjB,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAC9B,MAAM,qBAAqB,GAAG;EAEhC,MAAM;CACR;CAEA,MAAM,UAAU,KAAK,KAAK,aAAa,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,GAAG,EAC3E,MAAM,KACR,CAAC;CACD,MAAM,UAAU,KAAK,KAAK,QAAQ,GAAG,KAAK,UAAU,KAAK,MAAM,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC;AACnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,4BACpB,WACA,KACe;CACf,MAAM,MAAM,KAAK,WAAW,IAAI,OAAO;CACvC,MAAM,GAAG,KAAK;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;CAC9C,MAAM,sBAAsB,KAAK,IAAI,UAAU,IAAI,GAAG;AACxD;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,8CACpB,WACA,KACwC;CAExC,IAAI,MAAM,gBADK,KAAK,WAAW,IAAI,OACJ,CAAC,GAC9B,OAAO,EAAE,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UAAU,WAAW,GACvB,MAAM,iBAAiB,IAAI;CAG7B,MAAM,YAAY,UAAU,MAAM,GAAG,eAAe;CAQpD,OAAO,GANG,UAAU,eAMV,IALC,OAAO,UAAU,YAAY,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAK5C,IAJL,OAAO,UAAU,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG,GAIlC,EAAE,GAHX,OAAO,UAAU,YAAY,CAAC,CAAC,CAAC,SAAS,GAAG,GAG9B,IAFb,OAAO,UAAU,cAAc,CAAC,CAAC,CAAC,SAAS,GAAG,GAE5B,EAAE,GAAG;AACpC"}
import { n as OnDiskMigrationPackage, t as MigrationOps } from "./package-CCIHXr9Z.mjs";
import { MigrationMetadata, MigrationPackage } from "@prisma-next/framework-components/control";
//#region src/io.d.ts
declare function writeMigrationPackage(dir: string, metadata: MigrationMetadata, ops: MigrationOps): Promise<void>;
/**
* Materialise an in-memory {@link MigrationPackage} to a per-space
* directory on disk.
*
* Writes two files under `<targetDir>/<pkg.dirName>/`:
*
* - `migration.json` — the manifest (pretty-printed, matches
* {@link writeMigrationPackage}'s output for byte-for-byte parity with
* app-space migrations).
* - `ops.json` — the operation list (pretty-printed).
*
* Distinct verb from the lower-level {@link writeMigrationPackage}
* (which takes constituent `(metadata, ops)`): callers reading
* `materialise…` know they are persisting a struct-typed package.
*
* Overwrite-idempotent: the per-package directory is cleared before
* each emit, so re-running against the same `targetDir` produces
* byte-identical contents and never leaves stale files behind. The
* lower-level {@link writeMigrationPackage} stays strict because the
* CLI authoring path (`migration plan` / `migration new`) deliberately
* refuses to clobber an existing authored migration; this helper is
* the re-emit path that is supposed to converge on a single canonical
* on-disk shape.
*
* The per-space head contract lives at
* `<projectMigrationsDir>/<spaceId>/contract.json` (written by
* {@link import('./emit-contract-space-artefacts').emitContractSpaceArtefacts}),
* not inside the per-package directory. The runner reads only
* `migration.json` + `ops.json` from each package.
*/
declare function materialiseMigrationPackage(targetDir: string, pkg: MigrationPackage): Promise<void>;
/**
* Idempotent variant of {@link materialiseMigrationPackage}: writes the
* package only if `<targetDir>/<pkg.dirName>/` does not already exist on
* disk as a directory; returns `{ written: false }` when the package
* directory is present (no rewrite, no comparison — by-existence skip).
*
* Concretely:
* - existing directory → skip silently, return `{ written: false }`.
* - missing path → write three files via {@link materialiseMigrationPackage},
* return `{ written: true }`.
* - path exists but is not a directory (file/symlink) → treated as
* missing; {@link materialiseMigrationPackage} will attempt creation
* and fail with an appropriate OS error.
* - any other I/O error from `stat` → propagated unchanged.
*
* Used by the CLI's `runContractSpaceExtensionMigrationsPass` to
* materialise extension migration packages into a project's
* `migrations/<spaceId>/` directory, and by extension-package tests
* that mirror the same idempotent-rematerialise property locally
* without taking a CLI dependency.
*/
declare function materialiseExtensionMigrationPackageIfMissing(targetDir: string, pkg: MigrationPackage): Promise<{
readonly written: boolean;
}>;
/**
* Copy a list of files into `destDir`, optionally renaming each one.
*
* The destination directory is created (with `recursive: true`) if it
* does not already exist. Each source path is copied byte-for-byte into
* `destDir/<destName>`; missing sources throw `ENOENT`. The helper is
* intentionally generic: callers own the list of files (e.g. a contract
* emitter's emitted output) and the naming convention (e.g. renaming
* the destination contract to `end-contract.*` and the source contract
* to `start-contract.*`).
*/
declare function copyFilesWithRename(destDir: string, files: readonly {
readonly sourcePath: string;
readonly destName: string;
}[]): Promise<void>;
declare function writeMigrationMetadata(dir: string, metadata: MigrationMetadata): Promise<void>;
declare function writeMigrationOps(dir: string, ops: MigrationOps): Promise<void>;
declare function readMigrationPackage(dir: string): Promise<OnDiskMigrationPackage>;
/**
* A per-package load-time problem returned by {@link readMigrationsDir}.
*
* Three variants, matching the relocated throws from the load path:
*
* - `hashMismatch` — stored `migrationHash` differs from the recomputed value.
* The package is **retained** in the returned `packages` array.
* - `providedInvariantsMismatch` — `migration.json` declares different
* `providedInvariants` than `ops.json` implies. The package is **retained**.
* - `packageUnloadable` — the manifest is missing, unparseable, or schema-
* invalid. The package is **omitted** from `packages`.
*
* Callers that need the `spaceId` context (e.g. the aggregate loader) attach
* it when converting to {@link import('./integrity-violation').IntegrityViolation}.
*/
type PackageLoadProblem = {
readonly kind: 'hashMismatch';
readonly dirName: string;
readonly stored: string;
readonly computed: string;
} | {
readonly kind: 'providedInvariantsMismatch';
readonly dirName: string;
} | {
readonly kind: 'packageUnloadable';
readonly dirName: string;
readonly detail: string;
};
/**
* Result returned by {@link readMigrationsDir}.
*
* - `packages` — every package that could be read; hash-mismatched and
* invariants-mismatched packages are included here (the problem is
* represented rather than fatal).
* - `problems` — one entry per package that had a load-time issue.
* `packageUnloadable` entries are **not** in `packages`.
*/
interface ReadMigrationsDirResult {
readonly packages: readonly OnDiskMigrationPackage[];
readonly problems: readonly PackageLoadProblem[];
}
declare function readMigrationsDir(migrationsRoot: string): Promise<ReadMigrationsDirResult>;
declare function formatMigrationDirName(timestamp: Date, slug: string): string;
//#endregion
export { materialiseExtensionMigrationPackageIfMissing as a, readMigrationsDir as c, writeMigrationPackage as d, formatMigrationDirName as i, writeMigrationMetadata as l, ReadMigrationsDirResult as n, materialiseMigrationPackage as o, copyFilesWithRename as r, readMigrationPackage as s, PackageLoadProblem as t, writeMigrationOps as u };
//# sourceMappingURL=io-DaQ5HRD7.d.mts.map
{"version":3,"file":"io-DaQ5HRD7.d.mts","names":[],"sources":["../src/io.ts"],"mappings":";;;iBA0CsB,sBACpB,aACA,UAAU,mBACV,KAAK,eACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgDmB,4BACpB,mBACA,KAAK,mBACJ;;;;;;;;;;;;;;;;;;;;;;iBA2BmB,8CACpB,mBACA,KAAK,mBACJ;WAAmB;;;;;;;;;;;;;iBA6BA,oBACpB,iBACA;WAA2B;WAA6B;MACvD;iBAUmB,uBACpB,aACA,UAAU,oBACT;iBAImB,kBAAkB,aAAa,KAAK,eAAe;iBA8BnD,qBAAqB,cAAc,QAAQ;;;;;;;;;;;;;;;;KA2KrD;WAEG;WACA;WACA;WACA;;WAEA;WAA6C;;WAC7C;WAAoC;WAA0B;;;;;;;;;;;UAW5D;WACN,mBAAmB;WACnB,mBAAmB;;iBASR,kBAAkB,yBAAyB,QAAQ;iBAkEzD,uBAAuB,WAAW,MAAM"}
import { C as errorNoInitialMigration, T as errorNoTarget, n as errorAmbiguousTarget } from "./errors-DIS_dcFJ.mjs";
import { t as EMPTY_CONTRACT_HASH } from "./constants-YnG8_EGO.mjs";
import { ifDefined } from "@prisma-next/utils/defined";
//#region src/queue.ts
/**
* FIFO queue with amortised O(1) push and shift.
*
* Uses a head-index cursor over a backing array rather than
* `Array.prototype.shift()`, which is O(n) on V8. Intended for BFS-shaped
* traversals where the queue is drained in a single pass — it does not
* reclaim memory for already-shifted items, so it is not suitable for
* long-lived queues with many push/shift cycles.
*/
var Queue = class {
items;
head = 0;
constructor(initial = []) {
this.items = [...initial];
}
push(item) {
this.items.push(item);
}
/**
* Remove and return the next item. Caller must check `isEmpty` first —
* shifting an empty queue throws.
*/
shift() {
if (this.head >= this.items.length) throw new Error("Queue.shift called on empty queue");
return this.items[this.head++];
}
get isEmpty() {
return this.head >= this.items.length;
}
};
//#endregion
//#region src/graph-ops.ts
function* bfs(starts, neighbours, key = (state) => state) {
const visited = /* @__PURE__ */ new Set();
const parentMap = /* @__PURE__ */ new Map();
const queue = new Queue();
for (const start of starts) {
const k = key(start);
if (!visited.has(k)) {
visited.add(k);
queue.push({
state: start,
key: k
});
}
}
while (!queue.isEmpty) {
const { state: current, key: curKey } = queue.shift();
const parentInfo = parentMap.get(curKey);
yield {
state: current,
parent: parentInfo?.parent ?? null,
incomingEdge: parentInfo?.edge ?? null
};
for (const { next, edge } of neighbours(current)) {
const k = key(next);
if (!visited.has(k)) {
visited.add(k);
parentMap.set(k, {
parent: current,
edge
});
queue.push({
state: next,
key: k
});
}
}
}
}
//#endregion
//#region src/migration-graph.ts
/** Forward-edge neighbours: edge `e` from `n` visits `e.to` next. */
function forwardNeighbours(graph, node) {
return (graph.forwardChain.get(node) ?? []).map((edge) => ({
next: edge.to,
edge
}));
}
/**
* Forward-edge neighbours, sorted by the deterministic tie-break.
* Used by path-finding so the resulting shortest path is stable across runs.
*/
function sortedForwardNeighbours(graph, node) {
return [...graph.forwardChain.get(node) ?? []].sort(compareTieBreak).map((edge) => ({
next: edge.to,
edge
}));
}
/** Reverse-edge neighbours: edge `e` from `n` visits `e.from` next. */
function reverseNeighbours(graph, node) {
return (graph.reverseChain.get(node) ?? []).map((edge) => ({
next: edge.from,
edge
}));
}
function appendEdge(map, key, entry) {
const bucket = map.get(key);
if (bucket) bucket.push(entry);
else map.set(key, [entry]);
}
function reconstructGraph(packages) {
const nodes = /* @__PURE__ */ new Set();
const forwardChain = /* @__PURE__ */ new Map();
const reverseChain = /* @__PURE__ */ new Map();
const migrationByHash = /* @__PURE__ */ new Map();
for (const pkg of packages) {
const from = pkg.metadata.from ?? "sha256:empty";
const { to } = pkg.metadata;
nodes.add(from);
nodes.add(to);
const migration = {
from,
to,
migrationHash: pkg.metadata.migrationHash,
dirName: pkg.dirName,
createdAt: pkg.metadata.createdAt,
invariants: pkg.metadata.providedInvariants
};
if (!migrationByHash.has(migration.migrationHash)) migrationByHash.set(migration.migrationHash, migration);
appendEdge(forwardChain, from, migration);
appendEdge(reverseChain, to, migration);
}
return {
nodes,
forwardChain,
reverseChain,
migrationByHash
};
}
function compareTieBreak(a, b) {
const ca = a.createdAt.localeCompare(b.createdAt);
if (ca !== 0) return ca;
const tc = a.to.localeCompare(b.to);
if (tc !== 0) return tc;
return a.migrationHash.localeCompare(b.migrationHash);
}
function sortedNeighbors(edges) {
return [...edges].sort(compareTieBreak);
}
/**
* Find the shortest path from `fromHash` to `toHash` using BFS over the
* contract-hash graph. Returns the ordered list of edges, or null if no path
* exists. Returns an empty array when `fromHash === toHash` (no-op).
*
* Neighbor ordering is deterministic via the tie-break sort key:
* createdAt → to → migrationHash.
*/
function findPath(graph, fromHash, toHash) {
if (fromHash === toHash) return [];
const parents = /* @__PURE__ */ new Map();
for (const step of bfs([fromHash], (n) => sortedForwardNeighbours(graph, n))) {
if (step.parent !== null && step.incomingEdge !== null) parents.set(step.state, {
parent: step.parent,
edge: step.incomingEdge
});
if (step.state === toHash) {
const path = [];
let cur = toHash;
let p = parents.get(cur);
while (p) {
path.push(p.edge);
cur = p.parent;
p = parents.get(cur);
}
path.reverse();
return path;
}
}
return null;
}
/**
* Find the shortest path from `fromHash` to `toHash` whose edges collectively
* cover every invariant in `required`. Returns `null` when no such path exists
* (either `fromHash`→`toHash` is structurally unreachable, or every reachable
* path leaves at least one required invariant uncovered). When `required` is
* empty, delegates to `findPath` so the result is byte-identical for that case.
*
* Algorithm: BFS over `(node, coveredSubset)` states with state-level dedup.
* The covered subset is a `Set<string>` of invariant ids; the state's dedup
* key is `${node}\0${[...covered].sort().join('\0')}`. State keys distinguish
* distinct `(node, covered)` tuples regardless of node-name length because
* `\0` cannot appear in any invariant id (validation rejects whitespace and
* control chars at authoring time).
*
* Neighbour ordering when `required ≠ ∅`: edges covering ≥1 still-needed
* invariant come first, with `createdAt → to → migrationHash` as the
* secondary key. The heuristic steers BFS toward the satisfying path;
* correctness (shortest, deterministic) does not depend on it.
*/
function findPathWithInvariants(graph, fromHash, toHash, required) {
if (required.size === 0) return findPath(graph, fromHash, toHash);
const stateKey = (s) => {
if (s.covered.size === 0) return `${s.node}\0`;
return `${s.node}\0${[...s.covered].sort().join("\0")}`;
};
const neighbours = (s) => {
const outgoing = graph.forwardChain.get(s.node) ?? [];
if (outgoing.length === 0) return [];
return [...outgoing].map((edge) => {
let useful = false;
let next = null;
for (const inv of edge.invariants) if (required.has(inv) && !s.covered.has(inv)) {
if (next === null) next = new Set(s.covered);
next.add(inv);
useful = true;
}
return {
edge,
useful,
nextCovered: next ?? s.covered
};
}).sort((a, b) => {
if (a.useful !== b.useful) return a.useful ? -1 : 1;
return compareTieBreak(a.edge, b.edge);
}).map(({ edge, nextCovered }) => ({
next: {
node: edge.to,
covered: nextCovered
},
edge
}));
};
const parents = /* @__PURE__ */ new Map();
for (const step of bfs([{
node: fromHash,
covered: /* @__PURE__ */ new Set()
}], neighbours, stateKey)) {
const curKey = stateKey(step.state);
if (step.parent !== null && step.incomingEdge !== null) parents.set(curKey, {
parentKey: stateKey(step.parent),
edge: step.incomingEdge
});
if (step.state.node === toHash && step.state.covered.size === required.size) {
const path = [];
let cur = curKey;
while (cur !== void 0) {
const p = parents.get(cur);
if (!p) break;
path.push(p.edge);
cur = p.parentKey;
}
path.reverse();
return path;
}
}
return null;
}
/**
* Reverse-BFS from `toHash` over `reverseChain` to collect every node from
* which `toHash` is reachable (inclusive of `toHash` itself).
*/
function collectNodesReachingTarget(graph, toHash) {
const reached = /* @__PURE__ */ new Set();
for (const step of bfs([toHash], (n) => reverseNeighbours(graph, n))) reached.add(step.state);
return reached;
}
/**
* Find the shortest path from `fromHash` to `toHash` and return structured
* path-decision metadata for machine-readable output. When `required` is
* non-empty, the returned path is the shortest one whose edges collectively
* cover every required invariant.
*
* The discriminated return type tells the caller *why* a path could not be
* found, so the CLI can pick the right structured error without re-running
* a structural BFS.
*/
function findPathWithDecision(graph, fromHash, toHash, options = {}) {
const { refName, required = /* @__PURE__ */ new Set() } = options;
const requiredInvariants = [...required].sort();
if (fromHash === toHash && required.size === 0) return {
kind: "ok",
decision: {
selectedPath: [],
fromHash,
toHash,
alternativeCount: 0,
tieBreakReasons: [],
requiredInvariants,
satisfiedInvariants: [],
...ifDefined("refName", refName)
}
};
const path = findPathWithInvariants(graph, fromHash, toHash, required);
if (!path) {
if (required.size === 0) return { kind: "unreachable" };
const structural = findPath(graph, fromHash, toHash);
if (structural === null) return { kind: "unreachable" };
const coveredByStructural = /* @__PURE__ */ new Set();
for (const edge of structural) for (const inv of edge.invariants) if (required.has(inv)) coveredByStructural.add(inv);
return {
kind: "unsatisfiable",
structuralPath: structural,
missing: requiredInvariants.filter((id) => !coveredByStructural.has(id))
};
}
const satisfiedInvariants = computeSatisfiedInvariants(required, path);
const reachesTarget = collectNodesReachingTarget(graph, toHash);
const coveragePrefixes = requiredCoveragePrefixes(required, path);
const tieBreakReasons = [];
let alternativeCount = 0;
for (const [i, edge] of path.entries()) {
const outgoing = graph.forwardChain.get(edge.from);
if (!outgoing || outgoing.length <= 1) continue;
const reachable = outgoing.filter((e) => reachesTarget.has(e.to));
if (reachable.length <= 1) continue;
let comparisonPool = reachable;
if (required.size > 0) {
const prefixSet = coveragePrefixes[i];
if (prefixSet === void 0) continue;
comparisonPool = invariantViableAlternativesAtStep(required, prefixSet, reachable);
}
alternativeCount += reachable.length - 1;
if (sortedNeighbors(reachable)[0]?.migrationHash !== edge.migrationHash) continue;
if (!reachable.some((e) => e.migrationHash !== edge.migrationHash)) continue;
const sortedViable = sortedNeighbors(comparisonPool);
if (sortedViable.length > 1 && sortedViable[0]?.migrationHash === edge.migrationHash && sortedViable.some((e) => e.migrationHash !== edge.migrationHash)) tieBreakReasons.push(`at ${edge.from}: ${comparisonPool.length} candidates, selected by tie-break`);
}
return {
kind: "ok",
decision: {
selectedPath: path,
fromHash,
toHash,
alternativeCount,
tieBreakReasons,
requiredInvariants,
satisfiedInvariants,
...ifDefined("refName", refName)
}
};
}
function computeSatisfiedInvariants(required, path) {
if (required.size === 0) return [];
const covered = /* @__PURE__ */ new Set();
for (const edge of path) for (const inv of edge.invariants) if (required.has(inv)) covered.add(inv);
return [...covered].sort();
}
/**
* For each edge on path, invariant coverage accumulated from earlier edges only —
* `(required ∩ ∪_{j<i} path[j].invariants)` represented as cumulative set along `required`,
* keyed as "full set of required ids satisfied before taking path[i]".
*/
function requiredCoveragePrefixes(required, path) {
const prefixes = [];
const acc = /* @__PURE__ */ new Set();
for (const edge of path) {
prefixes.push(new Set(acc));
for (const inv of edge.invariants) if (required.has(inv)) acc.add(inv);
}
return prefixes;
}
function invariantViableAlternativesAtStep(required, coverageBeforeTakingEdge, outgoing) {
if (required.size === 0) return [...outgoing];
return outgoing.filter((e) => [...required].every((id) => coverageBeforeTakingEdge.has(id) || e.invariants.includes(id)));
}
/**
* Walk ancestors of each branch tip back to find the last node
* that appears on all paths. Returns `fromHash` if no shared ancestor is found.
*/
function findDivergencePoint(graph, fromHash, leaves) {
const ancestorSets = leaves.map((leaf) => {
const ancestors = /* @__PURE__ */ new Set();
for (const step of bfs([leaf], (n) => reverseNeighbours(graph, n))) ancestors.add(step.state);
return ancestors;
});
const commonAncestors = [...ancestorSets[0] ?? []].filter((node) => ancestorSets.every((s) => s.has(node)));
let deepest = fromHash;
let deepestDepth = -1;
for (const ancestor of commonAncestors) {
const path = findPath(graph, fromHash, ancestor);
const depth = path ? path.length : 0;
if (depth > deepestDepth) {
deepestDepth = depth;
deepest = ancestor;
}
}
return deepest;
}
/**
* Find all branch tips (nodes with no outgoing edges) reachable from
* `fromHash` via forward edges.
*/
function findReachableLeaves(graph, fromHash) {
const leaves = [];
for (const step of bfs([fromHash], (n) => forwardNeighbours(graph, n))) if (!graph.forwardChain.get(step.state)?.length) leaves.push(step.state);
return leaves;
}
/**
* Find the target contract hash of the migration graph reachable from
* EMPTY_CONTRACT_HASH. Returns `null` for a graph that has no target
* state (either empty, or containing only the root with no outgoing
* edges). Throws NO_INITIAL_MIGRATION if the graph has nodes but none
* originate from the empty hash, and AMBIGUOUS_TARGET if multiple
* branch tips exist.
*/
function findLeaf(graph) {
if (graph.nodes.size === 0) return null;
if (!graph.nodes.has("sha256:empty")) throw errorNoInitialMigration([...graph.nodes]);
const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);
if (leaves.length === 0) {
const reachable = [...graph.nodes].filter((n) => n !== EMPTY_CONTRACT_HASH);
if (reachable.length > 0) throw errorNoTarget(reachable);
return null;
}
if (leaves.length > 1) {
const divergencePoint = findDivergencePoint(graph, EMPTY_CONTRACT_HASH, leaves);
throw errorAmbiguousTarget(leaves, {
divergencePoint,
branches: leaves.map((tip) => {
return {
tip,
edges: (findPath(graph, divergencePoint, tip) ?? []).map((e) => ({
dirName: e.dirName,
from: e.from,
to: e.to
}))
};
})
});
}
return leaves[0];
}
/**
* Find the latest migration entry by traversing from EMPTY_CONTRACT_HASH
* to the single target. Returns null for an empty graph.
* Throws AMBIGUOUS_TARGET if the graph has multiple branch tips.
*/
function findLatestMigration(graph) {
const leafHash = findLeaf(graph);
if (leafHash === null) return null;
return findPath(graph, "sha256:empty", leafHash)?.at(-1) ?? null;
}
function detectCycles(graph) {
const WHITE = 0;
const GRAY = 1;
const BLACK = 2;
const color = /* @__PURE__ */ new Map();
const parentMap = /* @__PURE__ */ new Map();
const cycles = [];
for (const node of graph.nodes) color.set(node, WHITE);
const stack = [];
function pushFrame(u) {
color.set(u, GRAY);
stack.push({
node: u,
outgoing: graph.forwardChain.get(u) ?? [],
index: 0
});
}
for (const root of graph.nodes) {
if (color.get(root) !== WHITE) continue;
parentMap.set(root, null);
pushFrame(root);
while (stack.length > 0) {
const frame = stack[stack.length - 1];
if (frame.index >= frame.outgoing.length) {
color.set(frame.node, BLACK);
stack.pop();
continue;
}
const v = frame.outgoing[frame.index++].to;
const vColor = color.get(v);
if (vColor === GRAY) {
const cycle = [v];
let cur = frame.node;
while (cur !== v) {
cycle.push(cur);
cur = parentMap.get(cur) ?? v;
}
cycle.reverse();
cycles.push(cycle);
} else if (vColor === WHITE) {
parentMap.set(v, frame.node);
pushFrame(v);
}
}
}
return cycles;
}
function detectOrphans(graph) {
if (graph.nodes.size === 0) return [];
const reachable = /* @__PURE__ */ new Set();
const startNodes = [];
if (graph.forwardChain.has("sha256:empty")) startNodes.push(EMPTY_CONTRACT_HASH);
else {
const allTargets = /* @__PURE__ */ new Set();
for (const edges of graph.forwardChain.values()) for (const edge of edges) allTargets.add(edge.to);
for (const node of graph.nodes) if (!allTargets.has(node)) startNodes.push(node);
}
for (const step of bfs(startNodes, (n) => forwardNeighbours(graph, n))) reachable.add(step.state);
const orphans = [];
for (const [from, migrations] of graph.forwardChain) if (!reachable.has(from)) orphans.push(...migrations);
return orphans;
}
//#endregion
export { findPath as a, findReachableLeaves as c, findLeaf as i, reconstructGraph as l, detectOrphans as n, findPathWithDecision as o, findLatestMigration as r, findPathWithInvariants as s, detectCycles as t };
//# sourceMappingURL=migration-graph-BXHOgdTg.mjs.map
{"version":3,"file":"migration-graph-BXHOgdTg.mjs","names":[],"sources":["../src/queue.ts","../src/graph-ops.ts","../src/migration-graph.ts"],"sourcesContent":["/**\n * FIFO queue with amortised O(1) push and shift.\n *\n * Uses a head-index cursor over a backing array rather than\n * `Array.prototype.shift()`, which is O(n) on V8. Intended for BFS-shaped\n * traversals where the queue is drained in a single pass — it does not\n * reclaim memory for already-shifted items, so it is not suitable for\n * long-lived queues with many push/shift cycles.\n */\nexport class Queue<T> {\n private readonly items: T[];\n private head = 0;\n\n constructor(initial: Iterable<T> = []) {\n this.items = [...initial];\n }\n\n push(item: T): void {\n this.items.push(item);\n }\n\n /**\n * Remove and return the next item. Caller must check `isEmpty` first —\n * shifting an empty queue throws.\n */\n shift(): T {\n if (this.head >= this.items.length) {\n throw new Error('Queue.shift called on empty queue');\n }\n // biome-ignore lint/style/noNonNullAssertion: bounds-checked on the line above\n return this.items[this.head++]!;\n }\n\n get isEmpty(): boolean {\n return this.head >= this.items.length;\n }\n}\n","import { Queue } from './queue';\n\n/**\n * One step of a BFS traversal.\n *\n * `parent` and `incomingEdge` are `null` for start states — they were not\n * reached via any edge. For every other state they record the predecessor\n * state and the edge by which this state was first reached.\n *\n * `state` is the BFS state, most often a string (graph node identifier) but\n * can be a composite object. The string overload keeps the common case\n * ergonomic; the generic overload accepts a caller-supplied `key` function\n * that produces a stable equality key for dedup.\n */\nexport interface BfsStep<S, E> {\n readonly state: S;\n readonly parent: S | null;\n readonly incomingEdge: E | null;\n}\n\n/**\n * Generic breadth-first traversal.\n *\n * Direction (forward/reverse) is expressed by the caller's `neighbours`\n * closure: return `{ next, edge }` pairs where `next` is the state to visit\n * next and `edge` is the edge that connects them. Callers that don't need\n * path reconstruction can ignore the `parent`/`incomingEdge` fields of each\n * yielded step.\n *\n * Ordering — when the result needs to be deterministic (path-finding) the\n * caller is responsible for sorting inside `neighbours`; this generator\n * does not impose an ordering hook of its own. State-dependent orderings\n * have full access to the source state inside the closure.\n *\n * Stops are intrinsic — callers `break` out of the `for..of` loop when\n * they've found what they're looking for.\n */\nexport function bfs<E>(\n starts: Iterable<string>,\n neighbours: (state: string) => Iterable<{ next: string; edge: E }>,\n): Generator<BfsStep<string, E>>;\nexport function bfs<S, E>(\n starts: Iterable<S>,\n neighbours: (state: S) => Iterable<{ next: S; edge: E }>,\n key: (state: S) => string,\n): Generator<BfsStep<S, E>>;\nexport function* bfs<S, E>(\n starts: Iterable<S>,\n neighbours: (state: S) => Iterable<{ next: S; edge: E }>,\n // Identity default for the string overload. TypeScript can't express\n // \"default applies only when S = string\", so this cast bridges the\n // generic implementation signature to the public overloads — which\n // guarantee `key` is omitted only when S = string at the call site.\n key: (state: S) => string = (state) => state as unknown as string,\n): Generator<BfsStep<S, E>> {\n // Queue entries carry the state alongside its key so we don't recompute\n // key() twice per visit (once on dedup, once on parent lookup). Composite\n // keys can be non-trivial to compute; string-overload callers pay nothing\n // since key() is identity there.\n interface Entry {\n readonly state: S;\n readonly key: string;\n }\n const visited = new Set<string>();\n const parentMap = new Map<string, { parent: S; edge: E }>();\n const queue = new Queue<Entry>();\n for (const start of starts) {\n const k = key(start);\n if (!visited.has(k)) {\n visited.add(k);\n queue.push({ state: start, key: k });\n }\n }\n while (!queue.isEmpty) {\n const { state: current, key: curKey } = queue.shift();\n const parentInfo = parentMap.get(curKey);\n yield {\n state: current,\n parent: parentInfo?.parent ?? null,\n incomingEdge: parentInfo?.edge ?? null,\n };\n\n for (const { next, edge } of neighbours(current)) {\n const k = key(next);\n if (!visited.has(k)) {\n visited.add(k);\n parentMap.set(k, { parent: current, edge });\n queue.push({ state: next, key: k });\n }\n }\n }\n}\n","import { ifDefined } from '@prisma-next/utils/defined';\nimport { EMPTY_CONTRACT_HASH } from './constants';\nimport { errorAmbiguousTarget, errorNoInitialMigration, errorNoTarget } from './errors';\nimport type { MigrationEdge, MigrationGraph } from './graph';\nimport { bfs } from './graph-ops';\nimport type { OnDiskMigrationPackage } from './package';\n\n/** Forward-edge neighbours: edge `e` from `n` visits `e.to` next. */\nfunction forwardNeighbours(graph: MigrationGraph, node: string) {\n return (graph.forwardChain.get(node) ?? []).map((edge) => ({ next: edge.to, edge }));\n}\n\n/**\n * Forward-edge neighbours, sorted by the deterministic tie-break.\n * Used by path-finding so the resulting shortest path is stable across runs.\n */\nfunction sortedForwardNeighbours(graph: MigrationGraph, node: string) {\n const edges = graph.forwardChain.get(node) ?? [];\n return [...edges].sort(compareTieBreak).map((edge) => ({ next: edge.to, edge }));\n}\n\n/** Reverse-edge neighbours: edge `e` from `n` visits `e.from` next. */\nfunction reverseNeighbours(graph: MigrationGraph, node: string) {\n return (graph.reverseChain.get(node) ?? []).map((edge) => ({ next: edge.from, edge }));\n}\n\nfunction appendEdge(map: Map<string, MigrationEdge[]>, key: string, entry: MigrationEdge): void {\n const bucket = map.get(key);\n if (bucket) bucket.push(entry);\n else map.set(key, [entry]);\n}\n\nexport function reconstructGraph(packages: readonly OnDiskMigrationPackage[]): MigrationGraph {\n const nodes = new Set<string>();\n const forwardChain = new Map<string, MigrationEdge[]>();\n const reverseChain = new Map<string, MigrationEdge[]>();\n const migrationByHash = new Map<string, MigrationEdge>();\n\n for (const pkg of packages) {\n // Manifest `from` is `string | null` (null = baseline). The graph layer\n // is the marker/path layer where \"no prior state\" is encoded as the\n // EMPTY_CONTRACT_HASH sentinel; bridge here so pathfinding stays string-\n // keyed.\n const from = pkg.metadata.from ?? EMPTY_CONTRACT_HASH;\n const { to } = pkg.metadata;\n\n nodes.add(from);\n nodes.add(to);\n\n const migration: MigrationEdge = {\n from,\n to,\n migrationHash: pkg.metadata.migrationHash,\n dirName: pkg.dirName,\n createdAt: pkg.metadata.createdAt,\n invariants: pkg.metadata.providedInvariants,\n };\n\n if (!migrationByHash.has(migration.migrationHash)) {\n migrationByHash.set(migration.migrationHash, migration);\n }\n\n appendEdge(forwardChain, from, migration);\n appendEdge(reverseChain, to, migration);\n }\n\n return { nodes, forwardChain, reverseChain, migrationByHash };\n}\n\n// ---------------------------------------------------------------------------\n// Deterministic tie-breaking for BFS neighbour order.\n// Used by path-finders only; not a general-purpose utility.\n// Ordering: createdAt → to → migrationHash.\n// ---------------------------------------------------------------------------\n\nfunction compareTieBreak(a: MigrationEdge, b: MigrationEdge): number {\n const ca = a.createdAt.localeCompare(b.createdAt);\n if (ca !== 0) return ca;\n const tc = a.to.localeCompare(b.to);\n if (tc !== 0) return tc;\n return a.migrationHash.localeCompare(b.migrationHash);\n}\n\nfunction sortedNeighbors(edges: readonly MigrationEdge[]): readonly MigrationEdge[] {\n return [...edges].sort(compareTieBreak);\n}\n\n/**\n * Find the shortest path from `fromHash` to `toHash` using BFS over the\n * contract-hash graph. Returns the ordered list of edges, or null if no path\n * exists. Returns an empty array when `fromHash === toHash` (no-op).\n *\n * Neighbor ordering is deterministic via the tie-break sort key:\n * createdAt → to → migrationHash.\n */\nexport function findPath(\n graph: MigrationGraph,\n fromHash: string,\n toHash: string,\n): readonly MigrationEdge[] | null {\n if (fromHash === toHash) return [];\n\n const parents = new Map<string, { parent: string; edge: MigrationEdge }>();\n for (const step of bfs([fromHash], (n) => sortedForwardNeighbours(graph, n))) {\n if (step.parent !== null && step.incomingEdge !== null) {\n parents.set(step.state, { parent: step.parent, edge: step.incomingEdge });\n }\n if (step.state === toHash) {\n const path: MigrationEdge[] = [];\n let cur = toHash;\n let p = parents.get(cur);\n while (p) {\n path.push(p.edge);\n cur = p.parent;\n p = parents.get(cur);\n }\n path.reverse();\n return path;\n }\n }\n\n return null;\n}\n\n/**\n * Find the shortest path from `fromHash` to `toHash` whose edges collectively\n * cover every invariant in `required`. Returns `null` when no such path exists\n * (either `fromHash`→`toHash` is structurally unreachable, or every reachable\n * path leaves at least one required invariant uncovered). When `required` is\n * empty, delegates to `findPath` so the result is byte-identical for that case.\n *\n * Algorithm: BFS over `(node, coveredSubset)` states with state-level dedup.\n * The covered subset is a `Set<string>` of invariant ids; the state's dedup\n * key is `${node}\\0${[...covered].sort().join('\\0')}`. State keys distinguish\n * distinct `(node, covered)` tuples regardless of node-name length because\n * `\\0` cannot appear in any invariant id (validation rejects whitespace and\n * control chars at authoring time).\n *\n * Neighbour ordering when `required ≠ ∅`: edges covering ≥1 still-needed\n * invariant come first, with `createdAt → to → migrationHash` as the\n * secondary key. The heuristic steers BFS toward the satisfying path;\n * correctness (shortest, deterministic) does not depend on it.\n */\nexport function findPathWithInvariants(\n graph: MigrationGraph,\n fromHash: string,\n toHash: string,\n required: ReadonlySet<string>,\n): readonly MigrationEdge[] | null {\n if (required.size === 0) {\n return findPath(graph, fromHash, toHash);\n }\n\n interface InvState {\n readonly node: string;\n readonly covered: ReadonlySet<string>;\n }\n // `\\0` is a safe segment separator: `validateInvariantId` rejects any id\n // containing whitespace or control characters (NUL is U+0000), and node\n // hashes are hex strings. Distinct `(node, covered)` tuples therefore\n // map to distinct strings. If `validateInvariantId` is ever relaxed,\n // re-confirm dedup correctness here.\n const stateKey = (s: InvState): string => {\n if (s.covered.size === 0) return `${s.node}\\0`;\n return `${s.node}\\0${[...s.covered].sort().join('\\0')}`;\n };\n\n const neighbours = (s: InvState): Iterable<{ next: InvState; edge: MigrationEdge }> => {\n const outgoing = graph.forwardChain.get(s.node) ?? [];\n if (outgoing.length === 0) return [];\n return [...outgoing]\n .map((edge) => {\n let useful = false;\n let next: Set<string> | null = null;\n for (const inv of edge.invariants) {\n if (required.has(inv) && !s.covered.has(inv)) {\n if (next === null) next = new Set(s.covered);\n next.add(inv);\n useful = true;\n }\n }\n return { edge, useful, nextCovered: next ?? s.covered };\n })\n .sort((a, b) => {\n if (a.useful !== b.useful) return a.useful ? -1 : 1;\n return compareTieBreak(a.edge, b.edge);\n })\n .map(({ edge, nextCovered }) => ({\n next: { node: edge.to, covered: nextCovered },\n edge,\n }));\n };\n\n // Path reconstruction is consumer-side, keyed on stateKey, same shape as\n // findPath's parents map.\n const parents = new Map<string, { parentKey: string; edge: MigrationEdge }>();\n for (const step of bfs<InvState, MigrationEdge>(\n [{ node: fromHash, covered: new Set() }],\n neighbours,\n stateKey,\n )) {\n const curKey = stateKey(step.state);\n if (step.parent !== null && step.incomingEdge !== null) {\n parents.set(curKey, { parentKey: stateKey(step.parent), edge: step.incomingEdge });\n }\n if (step.state.node === toHash && step.state.covered.size === required.size) {\n const path: MigrationEdge[] = [];\n let cur: string | undefined = curKey;\n while (cur !== undefined) {\n const p = parents.get(cur);\n if (!p) break;\n path.push(p.edge);\n cur = p.parentKey;\n }\n path.reverse();\n return path;\n }\n }\n\n return null;\n}\n\n/**\n * Reverse-BFS from `toHash` over `reverseChain` to collect every node from\n * which `toHash` is reachable (inclusive of `toHash` itself).\n */\nfunction collectNodesReachingTarget(graph: MigrationGraph, toHash: string): Set<string> {\n const reached = new Set<string>();\n for (const step of bfs([toHash], (n) => reverseNeighbours(graph, n))) {\n reached.add(step.state);\n }\n return reached;\n}\n\nexport interface PathDecision {\n readonly selectedPath: readonly MigrationEdge[];\n readonly fromHash: string;\n readonly toHash: string;\n readonly alternativeCount: number;\n readonly tieBreakReasons: readonly string[];\n readonly refName?: string;\n /** The caller-supplied required invariant set, sorted ascending. */\n readonly requiredInvariants: readonly string[];\n /**\n * The subset of `requiredInvariants` actually covered by edges on\n * `selectedPath`. Always a subset of `requiredInvariants` (when the path\n * is satisfying, equal to it); always derived from `selectedPath`.\n */\n readonly satisfiedInvariants: readonly string[];\n}\n\n/**\n * Outcome of {@link findPathWithDecision}. The pathfinder distinguishes\n * three cases up front so callers don't re-derive structural reachability:\n *\n * - `ok` — a path covering `required` exists; `decision` carries the\n * selection metadata and per-edge invariants.\n * - `unreachable` — `from`→`to` has no structural path. Mapped by callers\n * to the existing no-path / `NO_TARGET` diagnostic.\n * - `unsatisfiable` — `from`→`to` is structurally reachable but no path\n * covers every required invariant. `structuralPath` is the\n * `findPath(graph, from, to)` result, included so callers don't have to\n * recompute it when raising `MIGRATION.NO_INVARIANT_PATH`. `missing` is\n * the subset of `required` that the structural path does *not* cover —\n * correctly accounts for partial coverage when some required invariants\n * are met by the fallback path. Only emitted when `required` is\n * non-empty.\n */\nexport type FindPathOutcome =\n | { readonly kind: 'ok'; readonly decision: PathDecision }\n | { readonly kind: 'unreachable' }\n | {\n readonly kind: 'unsatisfiable';\n readonly structuralPath: readonly MigrationEdge[];\n readonly missing: readonly string[];\n };\n\n/**\n * Routing context for {@link findPathWithDecision}. Both fields are optional;\n * `refName` is only used to decorate the resulting `PathDecision` for the\n * JSON envelope, and `required` defaults to an empty set (purely structural\n * routing). They are passed via a single options object so the call sites\n * cannot silently swap two adjacent string parameters.\n */\nexport interface FindPathWithDecisionOptions {\n readonly refName?: string;\n readonly required?: ReadonlySet<string>;\n}\n\n/**\n * Find the shortest path from `fromHash` to `toHash` and return structured\n * path-decision metadata for machine-readable output. When `required` is\n * non-empty, the returned path is the shortest one whose edges collectively\n * cover every required invariant.\n *\n * The discriminated return type tells the caller *why* a path could not be\n * found, so the CLI can pick the right structured error without re-running\n * a structural BFS.\n */\nexport function findPathWithDecision(\n graph: MigrationGraph,\n fromHash: string,\n toHash: string,\n options: FindPathWithDecisionOptions = {},\n): FindPathOutcome {\n const { refName, required = new Set<string>() } = options;\n const requiredInvariants = [...required].sort();\n\n if (fromHash === toHash && required.size === 0) {\n return {\n kind: 'ok',\n decision: {\n selectedPath: [],\n fromHash,\n toHash,\n alternativeCount: 0,\n tieBreakReasons: [],\n requiredInvariants,\n satisfiedInvariants: [],\n ...ifDefined('refName', refName),\n },\n };\n }\n\n const path = findPathWithInvariants(graph, fromHash, toHash, required);\n if (!path) {\n if (required.size === 0) {\n return { kind: 'unreachable' };\n }\n const structural = findPath(graph, fromHash, toHash);\n if (structural === null) {\n return { kind: 'unreachable' };\n }\n const coveredByStructural = new Set<string>();\n for (const edge of structural) {\n for (const inv of edge.invariants) {\n if (required.has(inv)) coveredByStructural.add(inv);\n }\n }\n const missing = requiredInvariants.filter((id) => !coveredByStructural.has(id));\n return { kind: 'unsatisfiable', structuralPath: structural, missing };\n }\n\n const satisfiedInvariants = computeSatisfiedInvariants(required, path);\n\n // Single reverse BFS marks every node from which `toHash` is reachable.\n // Replaces a per-edge `findPath(e.to, toHash)` call inside the loop below,\n // which made the whole function O(|path| · (V + E)) instead of O(V + E).\n const reachesTarget = collectNodesReachingTarget(graph, toHash);\n const coveragePrefixes = requiredCoveragePrefixes(required, path);\n\n const tieBreakReasons: string[] = [];\n let alternativeCount = 0;\n\n for (const [i, edge] of path.entries()) {\n const outgoing = graph.forwardChain.get(edge.from);\n if (!outgoing || outgoing.length <= 1) continue;\n const reachable = outgoing.filter((e) => reachesTarget.has(e.to));\n if (reachable.length <= 1) continue;\n\n let comparisonPool: readonly MigrationEdge[] = reachable;\n if (required.size > 0) {\n // coveragePrefixes is built one-per-edge from path, so the index is\n // always in range here; the explicit guard keeps the type narrowed\n // without a non-null assertion.\n const prefixSet = coveragePrefixes[i];\n if (prefixSet === undefined) continue;\n comparisonPool = invariantViableAlternativesAtStep(required, prefixSet, reachable);\n }\n\n alternativeCount += reachable.length - 1;\n const sorted = sortedNeighbors(reachable);\n if (sorted[0]?.migrationHash !== edge.migrationHash) continue;\n if (!reachable.some((e) => e.migrationHash !== edge.migrationHash)) continue;\n\n const sortedViable = sortedNeighbors(comparisonPool);\n if (\n sortedViable.length > 1 &&\n sortedViable[0]?.migrationHash === edge.migrationHash &&\n sortedViable.some((e) => e.migrationHash !== edge.migrationHash)\n ) {\n tieBreakReasons.push(\n `at ${edge.from}: ${comparisonPool.length} candidates, selected by tie-break`,\n );\n }\n }\n\n return {\n kind: 'ok',\n decision: {\n selectedPath: path,\n fromHash,\n toHash,\n alternativeCount,\n tieBreakReasons,\n requiredInvariants,\n satisfiedInvariants,\n ...ifDefined('refName', refName),\n },\n };\n}\n\nfunction computeSatisfiedInvariants(\n required: ReadonlySet<string>,\n path: readonly MigrationEdge[],\n): readonly string[] {\n if (required.size === 0) return [];\n const covered = new Set<string>();\n for (const edge of path) {\n for (const inv of edge.invariants) {\n if (required.has(inv)) covered.add(inv);\n }\n }\n return [...covered].sort();\n}\n\n/**\n * For each edge on path, invariant coverage accumulated from earlier edges only —\n * `(required ∩ ∪_{j<i} path[j].invariants)` represented as cumulative set along `required`,\n * keyed as \"full set of required ids satisfied before taking path[i]\".\n */\nfunction requiredCoveragePrefixes(\n required: ReadonlySet<string>,\n path: readonly MigrationEdge[],\n): readonly ReadonlySet<string>[] {\n const prefixes: ReadonlySet<string>[] = [];\n const acc = new Set<string>();\n for (const edge of path) {\n prefixes.push(new Set(acc));\n for (const inv of edge.invariants) {\n if (required.has(inv)) acc.add(inv);\n }\n }\n return prefixes;\n}\n\nfunction invariantViableAlternativesAtStep(\n required: ReadonlySet<string>,\n coverageBeforeTakingEdge: ReadonlySet<string>,\n outgoing: readonly MigrationEdge[],\n): readonly MigrationEdge[] {\n if (required.size === 0) return [...outgoing];\n return outgoing.filter((e) =>\n [...required].every((id) => coverageBeforeTakingEdge.has(id) || e.invariants.includes(id)),\n );\n}\n\n/**\n * Walk ancestors of each branch tip back to find the last node\n * that appears on all paths. Returns `fromHash` if no shared ancestor is found.\n */\nfunction findDivergencePoint(\n graph: MigrationGraph,\n fromHash: string,\n leaves: readonly string[],\n): string {\n const ancestorSets = leaves.map((leaf) => {\n const ancestors = new Set<string>();\n for (const step of bfs([leaf], (n) => reverseNeighbours(graph, n))) {\n ancestors.add(step.state);\n }\n return ancestors;\n });\n\n const commonAncestors = [...(ancestorSets[0] ?? [])].filter((node) =>\n ancestorSets.every((s) => s.has(node)),\n );\n\n let deepest = fromHash;\n let deepestDepth = -1;\n for (const ancestor of commonAncestors) {\n const path = findPath(graph, fromHash, ancestor);\n const depth = path ? path.length : 0;\n if (depth > deepestDepth) {\n deepestDepth = depth;\n deepest = ancestor;\n }\n }\n return deepest;\n}\n\n/**\n * Find all branch tips (nodes with no outgoing edges) reachable from\n * `fromHash` via forward edges.\n */\nexport function findReachableLeaves(graph: MigrationGraph, fromHash: string): readonly string[] {\n const leaves: string[] = [];\n for (const step of bfs([fromHash], (n) => forwardNeighbours(graph, n))) {\n if (!graph.forwardChain.get(step.state)?.length) {\n leaves.push(step.state);\n }\n }\n return leaves;\n}\n\n/**\n * Find the target contract hash of the migration graph reachable from\n * EMPTY_CONTRACT_HASH. Returns `null` for a graph that has no target\n * state (either empty, or containing only the root with no outgoing\n * edges). Throws NO_INITIAL_MIGRATION if the graph has nodes but none\n * originate from the empty hash, and AMBIGUOUS_TARGET if multiple\n * branch tips exist.\n */\nexport function findLeaf(graph: MigrationGraph): string | null {\n if (graph.nodes.size === 0) {\n return null;\n }\n\n if (!graph.nodes.has(EMPTY_CONTRACT_HASH)) {\n throw errorNoInitialMigration([...graph.nodes]);\n }\n\n const leaves = findReachableLeaves(graph, EMPTY_CONTRACT_HASH);\n\n if (leaves.length === 0) {\n const reachable = [...graph.nodes].filter((n) => n !== EMPTY_CONTRACT_HASH);\n if (reachable.length > 0) {\n throw errorNoTarget(reachable);\n }\n return null;\n }\n\n if (leaves.length > 1) {\n const divergencePoint = findDivergencePoint(graph, EMPTY_CONTRACT_HASH, leaves);\n const branches = leaves.map((tip) => {\n const path = findPath(graph, divergencePoint, tip);\n return {\n tip,\n edges: (path ?? []).map((e) => ({ dirName: e.dirName, from: e.from, to: e.to })),\n };\n });\n throw errorAmbiguousTarget(leaves, { divergencePoint, branches });\n }\n\n // biome-ignore lint/style/noNonNullAssertion: leaves.length is neither 0 nor >1 per the branches above, so exactly one leaf remains\n return leaves[0]!;\n}\n\n/**\n * Find the latest migration entry by traversing from EMPTY_CONTRACT_HASH\n * to the single target. Returns null for an empty graph.\n * Throws AMBIGUOUS_TARGET if the graph has multiple branch tips.\n */\nexport function findLatestMigration(graph: MigrationGraph): MigrationEdge | null {\n const leafHash = findLeaf(graph);\n if (leafHash === null) return null;\n\n const path = findPath(graph, EMPTY_CONTRACT_HASH, leafHash);\n return path?.at(-1) ?? null;\n}\n\nexport function detectCycles(graph: MigrationGraph): readonly string[][] {\n const WHITE = 0;\n const GRAY = 1;\n const BLACK = 2;\n\n const color = new Map<string, number>();\n const parentMap = new Map<string, string | null>();\n const cycles: string[][] = [];\n\n for (const node of graph.nodes) {\n color.set(node, WHITE);\n }\n\n // Iterative three-color DFS. A frame is (node, outgoing edges, next-index).\n interface Frame {\n node: string;\n outgoing: readonly MigrationEdge[];\n index: number;\n }\n const stack: Frame[] = [];\n\n function pushFrame(u: string): void {\n color.set(u, GRAY);\n stack.push({ node: u, outgoing: graph.forwardChain.get(u) ?? [], index: 0 });\n }\n\n for (const root of graph.nodes) {\n if (color.get(root) !== WHITE) continue;\n parentMap.set(root, null);\n pushFrame(root);\n\n while (stack.length > 0) {\n // biome-ignore lint/style/noNonNullAssertion: stack.length > 0 should guarantee that this cannot be undefined\n const frame = stack[stack.length - 1]!;\n if (frame.index >= frame.outgoing.length) {\n color.set(frame.node, BLACK);\n stack.pop();\n continue;\n }\n // biome-ignore lint/style/noNonNullAssertion: the early-continue above guarantees frame.index < frame.outgoing.length here, so this is defined\n const edge = frame.outgoing[frame.index++]!;\n const v = edge.to;\n const vColor = color.get(v);\n if (vColor === GRAY) {\n const cycle: string[] = [v];\n let cur = frame.node;\n while (cur !== v) {\n cycle.push(cur);\n cur = parentMap.get(cur) ?? v;\n }\n cycle.reverse();\n cycles.push(cycle);\n } else if (vColor === WHITE) {\n parentMap.set(v, frame.node);\n pushFrame(v);\n }\n }\n }\n\n return cycles;\n}\n\nexport function detectOrphans(graph: MigrationGraph): readonly MigrationEdge[] {\n if (graph.nodes.size === 0) return [];\n\n const reachable = new Set<string>();\n const startNodes: string[] = [];\n\n if (graph.forwardChain.has(EMPTY_CONTRACT_HASH)) {\n startNodes.push(EMPTY_CONTRACT_HASH);\n } else {\n const allTargets = new Set<string>();\n for (const edges of graph.forwardChain.values()) {\n for (const edge of edges) {\n allTargets.add(edge.to);\n }\n }\n for (const node of graph.nodes) {\n if (!allTargets.has(node)) {\n startNodes.push(node);\n }\n }\n }\n\n for (const step of bfs(startNodes, (n) => forwardNeighbours(graph, n))) {\n reachable.add(step.state);\n }\n\n const orphans: MigrationEdge[] = [];\n for (const [from, migrations] of graph.forwardChain) {\n if (!reachable.has(from)) {\n orphans.push(...migrations);\n }\n }\n\n return orphans;\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAa,QAAb,MAAsB;CACpB;CACA,OAAe;CAEf,YAAY,UAAuB,CAAC,GAAG;EACrC,KAAK,QAAQ,CAAC,GAAG,OAAO;CAC1B;CAEA,KAAK,MAAe;EAClB,KAAK,MAAM,KAAK,IAAI;CACtB;;;;;CAMA,QAAW;EACT,IAAI,KAAK,QAAQ,KAAK,MAAM,QAC1B,MAAM,IAAI,MAAM,mCAAmC;EAGrD,OAAO,KAAK,MAAM,KAAK;CACzB;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,QAAQ,KAAK,MAAM;CACjC;AACF;;;ACUA,UAAiB,IACf,QACA,YAKA,OAA6B,UAAU,OACb;CAS1B,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,4BAAY,IAAI,IAAoC;CAC1D,MAAM,QAAQ,IAAI,MAAa;CAC/B,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,IAAI,IAAI,KAAK;EACnB,IAAI,CAAC,QAAQ,IAAI,CAAC,GAAG;GACnB,QAAQ,IAAI,CAAC;GACb,MAAM,KAAK;IAAE,OAAO;IAAO,KAAK;GAAE,CAAC;EACrC;CACF;CACA,OAAO,CAAC,MAAM,SAAS;EACrB,MAAM,EAAE,OAAO,SAAS,KAAK,WAAW,MAAM,MAAM;EACpD,MAAM,aAAa,UAAU,IAAI,MAAM;EACvC,MAAM;GACJ,OAAO;GACP,QAAQ,YAAY,UAAU;GAC9B,cAAc,YAAY,QAAQ;EACpC;EAEA,KAAK,MAAM,EAAE,MAAM,UAAU,WAAW,OAAO,GAAG;GAChD,MAAM,IAAI,IAAI,IAAI;GAClB,IAAI,CAAC,QAAQ,IAAI,C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WAAW,OAAO;IAC3B,UAAU,IAAI,GAAG,MAAM,IAAI;IAC3B,UAAU,CAAC;GACb;EACF;CACF;CAEA,OAAO;AACT;AAEA,SAAgB,cAAc,OAAiD;CAC7E,IAAI,MAAM,MAAM,SAAS,GAAG,OAAO,CAAC;CAEpC,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,aAAuB,CAAC;CAE9B,IAAI,MAAM,aAAa,IAAA,cAAuB,GAC5C,WAAW,KAAK,mBAAmB;MAC9B;EACL,MAAM,6BAAa,IAAI,IAAY;EACnC,KAAK,MAAM,SAAS,MAAM,aAAa,OAAO,GAC5C,KAAK,MAAM,QAAQ,OACjB,WAAW,IAAI,KAAK,EAAE;EAG1B,KAAK,MAAM,QAAQ,MAAM,OACvB,IAAI,CAAC,WAAW,IAAI,IAAI,GACtB,WAAW,KAAK,IAAI;CAG1B;CAEA,KAAK,MAAM,QAAQ,IAAI,aAAa,MAAM,kBAAkB,OAAO,CAAC,CAAC,GACnE,UAAU,IAAI,KAAK,KAAK;CAG1B,MAAM,UAA2B,CAAC;CAClC,KAAK,MAAM,CAAC,MAAM,eAAe,MAAM,cACrC,IAAI,CAAC,UAAU,IAAI,IAAI,GACrB,QAAQ,KAAK,GAAG,UAAU;CAI9B,OAAO;AACT"}
import { S as errorMissingFile, f as errorInvalidJson, h as errorInvalidRefFile, y as errorInvalidSpaceId } from "./errors-DIS_dcFJ.mjs";
import { t as MANIFEST_FILE } from "./io-CE79C4uK.mjs";
import { join } from "pathe";
import { readFile, readdir, stat } from "node:fs/promises";
import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
//#region src/space-layout.ts
/**
* Pattern a contract-space identifier must match. The constraint is
* filesystem-friendly: lowercase letters / digits / hyphen / underscore,
* starts with a letter, max 64 characters.
*/
const SPACE_ID_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
function isValidSpaceId(spaceId) {
return SPACE_ID_PATTERN.test(spaceId);
}
function assertValidSpaceId(spaceId) {
if (!isValidSpaceId(spaceId)) throw errorInvalidSpaceId(spaceId);
}
/**
* Resolve the migrations subdirectory for a given contract space.
*
* Every contract space — including the app space (default `'app'`) —
* lands under `<projectMigrationsDir>/<spaceId>/`. The space id is
* validated against {@link SPACE_ID_PATTERN} because it becomes a
* filesystem directory name verbatim.
*
* `projectMigrationsDir` is the project's top-level `migrations/`
* directory; the helper does not assume anything about its absolute /
* relative shape and is symmetric with `pathe.join`.
*/
function spaceMigrationDirectory(projectMigrationsDir, spaceId) {
assertValidSpaceId(spaceId);
return join(projectMigrationsDir, spaceId);
}
/**
* Per-space subdirectory name reserved for the ref store
* (`migrations/<space>/<SPACE_REFS_DIRNAME>/*.json`). Single source of
* truth: every helper that composes a per-space refs path imports this
* constant, and the enumerator uses it (via
* {@link RESERVED_SPACE_SUBDIR_NAMES}) to exclude reserved names from
* the contract-space candidate list.
*/
const SPACE_REFS_DIRNAME = "refs";
/**
* Names reserved as per-space subdirectories of `migrations/<space>/`.
* Used by the enumerator to filter contract-space candidates so a
* reserved name (e.g. a top-level `migrations/refs/` left in the wrong
* place) is never enumerated as a phantom contract space. Currently
* holds `SPACE_REFS_DIRNAME`; extend if future per-space layouts add
* more reserved subdirectories.
*/
const RESERVED_SPACE_SUBDIR_NAMES = /* @__PURE__ */ new Set([SPACE_REFS_DIRNAME]);
/**
* Resolve the per-space refs directory for `spaceMigrationsDir`
* (typically the value returned by {@link spaceMigrationDirectory}).
* Composes the canonical {@link SPACE_REFS_DIRNAME} so callers do not
* hard-code the literal.
*/
function spaceRefsDirectory(spaceMigrationsDir) {
return join(spaceMigrationsDir, SPACE_REFS_DIRNAME);
}
//#endregion
//#region src/read-contract-space-head-ref.ts
function hasErrnoCode$2(error, code) {
return error instanceof Error && error.code === code;
}
/**
* Read the head ref (`hash` + `invariants`) for a contract space from
* `<projectMigrationsDir>/<spaceId>/refs/head.json`.
*
* Returns `null` when the file does not exist (first emit). Surfaces
* `MIGRATION.INVALID_JSON` / `MIGRATION.INVALID_REF_FILE` on a corrupt
* `refs/head.json` so callers can distinguish "no head ref on disk"
* (returns `null`) from "head ref present but unreadable" (throws).
*
* Validates the space id against `[a-z][a-z0-9_-]{0,63}` for the same
* filesystem-safety reasons as the rest of the per-space helpers. The
* helper is uniform across the app and extension spaces.
*/
async function readContractSpaceHeadRef(projectMigrationsDir, spaceId) {
assertValidSpaceId(spaceId);
const filePath = join(spaceRefsDirectory(spaceMigrationDirectory(projectMigrationsDir, spaceId)), "head.json");
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
if (hasErrnoCode$2(error, "ENOENT")) return null;
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (e) {
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
}
if (typeof parsed !== "object" || parsed === null) throw errorInvalidRefFile(filePath, "expected an object");
const obj = parsed;
if (typeof obj.hash !== "string") throw errorInvalidRefFile(filePath, "expected an object with a string `hash` field");
if (!Array.isArray(obj.invariants) || obj.invariants.some((value) => typeof value !== "string")) throw errorInvalidRefFile(filePath, "expected an object with an `invariants` array of strings");
return {
hash: obj.hash,
invariants: obj.invariants
};
}
//#endregion
//#region src/verify-contract-spaces.ts
function hasErrnoCode$1(error, code) {
return error instanceof Error && error.code === code;
}
/**
* List the per-space subdirectories under
* `<projectRoot>/migrations/`. Returns space-id directory names (sorted
* alphabetically) — i.e. any non-dot-prefixed subdirectory whose root
* does **not** contain a `migration.json` manifest. The manifest is the
* structural marker of a user-authored migration directory (see
* `readMigrationsDir` in `./io`); directory names themselves belong to
* the user and are not part of the contract.
*
* Returns `[]` if the migrations directory does not exist (greenfield
* project).
*
* Reads only the user's repo. **No descriptor import.** The caller
* (verifier) feeds the result into {@link verifyContractSpaces} alongside
* the loaded-space set and the marker rows.
*/
async function listContractSpaceDirectories(projectMigrationsDir) {
let entries;
try {
entries = (await readdir(projectMigrationsDir, { withFileTypes: true })).map((d) => ({
name: d.name,
isDirectory: d.isDirectory()
}));
} catch (error) {
if (hasErrnoCode$1(error, "ENOENT")) return [];
throw error;
}
const namedCandidates = entries.filter((e) => e.isDirectory).map((e) => e.name).filter((name) => !name.startsWith(".")).sort();
return (await Promise.all(namedCandidates.map(async (name) => {
try {
await stat(join(projectMigrationsDir, name, MANIFEST_FILE));
return {
name,
isMigrationDir: true
};
} catch (error) {
if (hasErrnoCode$1(error, "ENOENT")) return {
name,
isMigrationDir: false
};
throw error;
}
}))).filter((c) => !c.isMigrationDir).map((c) => c.name);
}
/**
* Pure structural verifier for the per-space mechanism. Aggregates the
* three orphan / missing checks plus per-space hash and invariant
* comparison.
*
* Algorithm:
*
* - For every extension space declared in `loadedSpaces` (`'app'`
* excluded — the per-space verifier is scoped to extension spaces;
* the app is verified through the aggregate path):
* - If no contract-space dir on disk → `declaredButUnmigrated`.
* - Else if `markerRowsBySpace` lacks an entry → no violation here;
* the live-DB compare done outside this helper is where the
* absence shows up.
* - Else compare marker hash / invariants vs. on-disk head hash /
* invariants → `hashMismatch` / `invariantsMismatch` on drift.
* - For every contract-space dir on disk that is not in `loadedSpaces` →
* `orphanSpaceDir`.
* - For every marker row whose `space` is not in `loadedSpaces` →
* `orphanMarker`. The app-space marker is always loaded (`'app'` is
* in `loadedSpaces` by definition).
*
* Output is deterministic: violations are sorted first by `kind`
* (`declaredButUnmigrated` → `orphanMarker` → `orphanSpaceDir` →
* `hashMismatch` → `invariantsMismatch`) then by `spaceId`. Two callers
* passing equivalent inputs see byte-identical violation lists.
*
* Synchronous, pure, no I/O. **Does not import the extension descriptor**
* (the inputs are pre-resolved by the caller); the verifier reads only
* the user repo, not `node_modules`.
*/
function verifyContractSpaces(inputs) {
const violations = [];
for (const spaceId of [...inputs.loadedSpaces].sort()) {
if (spaceId === APP_SPACE_ID) continue;
if (!inputs.spaceDirsOnDisk.includes(spaceId)) {
violations.push({
kind: "declaredButUnmigrated",
spaceId,
remediation: `Extension '${spaceId}' is declared in extensionPacks but has not been emitted; run \`prisma-next migrate\`.`
});
continue;
}
const head = inputs.headRefsBySpace.get(spaceId);
const marker = inputs.markerRowsBySpace.get(spaceId);
if (!head || !marker) continue;
if (head.hash !== marker.hash) {
violations.push({
kind: "hashMismatch",
spaceId,
priorHeadHash: head.hash,
markerHash: marker.hash,
remediation: `Marker row for space '${spaceId}' is keyed at ${marker.hash}, but the on-disk ${join("migrations", spaceId, "contract.json")} resolves to ${head.hash}. Run \`prisma-next db update\` to advance the database, or \`prisma-next migrate\` if the descriptor was bumped without re-emitting.`
});
continue;
}
const onDiskInvariants = [...head.invariants].sort();
const markerInvariants = new Set(marker.invariants);
const missing = onDiskInvariants.filter((id) => !markerInvariants.has(id));
if (missing.length > 0) violations.push({
kind: "invariantsMismatch",
spaceId,
onDiskInvariants,
markerInvariants: [...marker.invariants].sort(),
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.`
});
}
for (const dir of [...inputs.spaceDirsOnDisk].sort()) if (!inputs.loadedSpaces.has(dir)) violations.push({
kind: "orphanSpaceDir",
spaceId: dir,
remediation: `Orphan contract-space directory \`${join("migrations", dir)}/\` for an extension not in extensionPacks; remove the directory or re-add the extension.`
});
for (const space of [...inputs.markerRowsBySpace.keys()].sort()) if (!inputs.loadedSpaces.has(space)) violations.push({
kind: "orphanMarker",
spaceId: space,
remediation: `Orphan marker row for space '${space}' (no longer in extensionPacks); remediation: manually delete the row from \`prisma_contract.marker\`.`
});
if (violations.length === 0) return { ok: true };
const kindOrder = {
declaredButUnmigrated: 0,
orphanMarker: 1,
orphanSpaceDir: 2,
hashMismatch: 3,
invariantsMismatch: 4
};
violations.sort((a, b) => {
const k = kindOrder[a.kind] - kindOrder[b.kind];
if (k !== 0) return k;
if (a.spaceId < b.spaceId) return -1;
if (a.spaceId > b.spaceId) return 1;
return 0;
});
return {
ok: false,
violations
};
}
//#endregion
//#region src/read-contract-space-contract.ts
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
/**
* Read the on-disk contract value for a contract space
* (`<projectMigrationsDir>/<spaceId>/contract.json`). Returns the parsed
* JSON value as `unknown` — callers that need a typed contract validate
* via their family's `deserializeContract` to surface schema issues.
*
* Companion to {@link import('./read-contract-space-head-ref').readContractSpaceHeadRef}
* — same ENOENT-throws / corrupt-file-error semantics. Returns the
* canonical-JSON value the framework wrote during emit, so re-running
* this helper across machines / runs yields a byte-identical value.
*/
async function readContractSpaceContract(projectMigrationsDir, spaceId) {
assertValidSpaceId(spaceId);
const filePath = join(projectMigrationsDir, spaceId, "contract.json");
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile("contract.json", join(projectMigrationsDir, spaceId));
throw error;
}
try {
return JSON.parse(raw);
} catch (e) {
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
}
}
//#endregion
export { APP_SPACE_ID as a, assertValidSpaceId as c, spaceRefsDirectory as d, readContractSpaceHeadRef as i, isValidSpaceId as l, listContractSpaceDirectories as n, RESERVED_SPACE_SUBDIR_NAMES as o, verifyContractSpaces as r, SPACE_REFS_DIRNAME as s, readContractSpaceContract as t, spaceMigrationDirectory as u };
//# sourceMappingURL=read-contract-space-contract-DBW4-T5r.mjs.map
{"version":3,"file":"read-contract-space-contract-DBW4-T5r.mjs","names":["hasErrnoCode","hasErrnoCode"],"sources":["../src/space-layout.ts","../src/read-contract-space-head-ref.ts","../src/verify-contract-spaces.ts","../src/read-contract-space-contract.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 */\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 * Every contract space — including the app space (default `'app'`) —\n * lands under `<projectMigrationsDir>/<spaceId>/`. The space id is\n * validated against {@link SPACE_ID_PATTERN} because it becomes a\n * 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 assertValidSpaceId(spaceId);\n return join(projectMigrationsDir, spaceId);\n}\n\n/**\n * Per-space subdirectory name reserved for the ref store\n * (`migrations/<space>/<SPACE_REFS_DIRNAME>/*.json`). Single source of\n * truth: every helper that composes a per-space refs path imports this\n * constant, and the enumerator uses it (via\n * {@link RESERVED_SPACE_SUBDIR_NAMES}) to exclude reserved names from\n * the contract-space candidate list.\n */\nexport const SPACE_REFS_DIRNAME = 'refs';\n\n/**\n * Names reserved as per-space subdirectories of `migrations/<space>/`.\n * Used by the enumerator to filter contract-space candidates so a\n * reserved name (e.g. a top-level `migrations/refs/` left in the wrong\n * place) is never enumerated as a phantom contract space. Currently\n * holds `SPACE_REFS_DIRNAME`; extend if future per-space layouts add\n * more reserved subdirectories.\n */\nexport const RESERVED_SPACE_SUBDIR_NAMES: ReadonlySet<string> = new Set([SPACE_REFS_DIRNAME]);\n\n/**\n * Resolve the per-space refs directory for `spaceMigrationsDir`\n * (typically the value returned by {@link spaceMigrationDirectory}).\n * Composes the canonical {@link SPACE_REFS_DIRNAME} so callers do not\n * hard-code the literal.\n */\nexport function spaceRefsDirectory(spaceMigrationsDir: string): string {\n return join(spaceMigrationsDir, SPACE_REFS_DIRNAME);\n}\n","import { readFile } from 'node:fs/promises';\nimport type { ContractSpaceHeadRef } from '@prisma-next/framework-components/control';\nimport { join } from 'pathe';\nimport { errorInvalidJson, errorInvalidRefFile } from './errors';\nimport { assertValidSpaceId, spaceMigrationDirectory, spaceRefsDirectory } from './space-layout';\n\nexport type { ContractSpaceHeadRef };\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 head ref (`hash` + `invariants`) for a contract space from\n * `<projectMigrationsDir>/<spaceId>/refs/head.json`.\n *\n * Returns `null` when the file does not exist (first emit). Surfaces\n * `MIGRATION.INVALID_JSON` / `MIGRATION.INVALID_REF_FILE` on a corrupt\n * `refs/head.json` so callers can distinguish \"no head ref on disk\"\n * (returns `null`) from \"head ref present but unreadable\" (throws).\n *\n * Validates the space id against `[a-z][a-z0-9_-]{0,63}` for the same\n * filesystem-safety reasons as the rest of the per-space helpers. The\n * helper is uniform across the app and extension spaces.\n */\nexport async function readContractSpaceHeadRef(\n projectMigrationsDir: string,\n spaceId: string,\n): Promise<ContractSpaceHeadRef | null> {\n assertValidSpaceId(spaceId);\n\n const filePath = join(\n spaceRefsDirectory(spaceMigrationDirectory(projectMigrationsDir, spaceId)),\n 'head.json',\n );\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 (typeof parsed !== 'object' || parsed === null) {\n throw errorInvalidRefFile(filePath, 'expected an object');\n }\n const obj = parsed as { hash?: unknown; invariants?: unknown };\n if (typeof obj.hash !== 'string') {\n throw errorInvalidRefFile(filePath, 'expected an object with a string `hash` field');\n }\n if (!Array.isArray(obj.invariants) || obj.invariants.some((value) => typeof value !== 'string')) {\n throw errorInvalidRefFile(filePath, 'expected an object with an `invariants` array of strings');\n }\n\n return { hash: obj.hash, invariants: obj.invariants as readonly string[] };\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 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 */\nexport async function listContractSpaceDirectories(\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 * On-disk 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 ContractSpaceHeadRecord {\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 before\n * 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 * Per-space subdirectories observed under\n * `<projectRoot>/migrations/`. Resolved via\n * {@link listContractSpaceDirectories}.\n */\n readonly spaceDirsOnDisk: readonly string[];\n\n /**\n * Head ref per space, keyed by space id. Caller reads\n * `<projectRoot>/migrations/<space-id>/contract.json` and\n * `<projectRoot>/migrations/<space-id>/refs/head.json` to construct\n * this map. Spaces with no contract-space dir on disk simply omit a\n * map entry.\n */\n readonly headRefsBySpace: ReadonlyMap<string, ContractSpaceHeadRecord>;\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: 'orphanSpaceDir';\n readonly spaceId: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'hashMismatch';\n readonly spaceId: string;\n readonly priorHeadHash: string;\n readonly markerHash: string;\n readonly remediation: string;\n }\n | {\n readonly kind: 'invariantsMismatch';\n readonly spaceId: string;\n readonly onDiskInvariants: 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 plus per-space hash and invariant\n * comparison.\n *\n * Algorithm:\n *\n * - For every extension space declared in `loadedSpaces` (`'app'`\n * excluded — the per-space verifier is scoped to extension spaces;\n * the app is verified through the aggregate path):\n * - If no contract-space dir on disk → `declaredButUnmigrated`.\n * - Else if `markerRowsBySpace` lacks an entry → no violation here;\n * the live-DB compare done outside this helper is where the\n * absence shows up.\n * - Else compare marker hash / invariants vs. on-disk head hash /\n * invariants → `hashMismatch` / `invariantsMismatch` on drift.\n * - For every contract-space dir on disk that is not in `loadedSpaces` →\n * `orphanSpaceDir`.\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: violations are sorted first by `kind`\n * (`declaredButUnmigrated` → `orphanMarker` → `orphanSpaceDir` →\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); the verifier reads only\n * the user repo, not `node_modules`.\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.spaceDirsOnDisk.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 head = inputs.headRefsBySpace.get(spaceId);\n const marker = inputs.markerRowsBySpace.get(spaceId);\n if (!head || !marker) {\n continue;\n }\n\n if (head.hash !== marker.hash) {\n violations.push({\n kind: 'hashMismatch',\n spaceId,\n priorHeadHash: head.hash,\n markerHash: marker.hash,\n remediation: `Marker row for space '${spaceId}' is keyed at ${marker.hash}, but the on-disk ${join('migrations', spaceId, 'contract.json')} resolves to ${head.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 onDiskInvariants = [...head.invariants].sort();\n const markerInvariants = new Set(marker.invariants);\n const missing = onDiskInvariants.filter((id) => !markerInvariants.has(id));\n if (missing.length > 0) {\n violations.push({\n kind: 'invariantsMismatch',\n spaceId,\n onDiskInvariants,\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.spaceDirsOnDisk].sort()) {\n if (!inputs.loadedSpaces.has(dir)) {\n violations.push({\n kind: 'orphanSpaceDir',\n spaceId: dir,\n remediation: `Orphan contract-space 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 orphanSpaceDir: 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 k;\n if (a.spaceId < b.spaceId) return -1;\n if (a.spaceId > b.spaceId) return 1;\n return 0;\n });\n\n return { ok: false, violations };\n}\n","import { readFile } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { errorInvalidJson, errorMissingFile } from './errors';\nimport { 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 on-disk contract value for a contract space\n * (`<projectMigrationsDir>/<spaceId>/contract.json`). Returns the parsed\n * JSON value as `unknown` — callers that need a typed contract validate\n * via their family's `deserializeContract` to surface schema issues.\n *\n * Companion to {@link import('./read-contract-space-head-ref').readContractSpaceHeadRef}\n * — same ENOENT-throws / corrupt-file-error semantics. Returns the\n * canonical-JSON value the framework wrote during emit, so re-running\n * this helper across machines / runs yields a byte-identical value.\n */\nexport async function readContractSpaceContract(\n projectMigrationsDir: string,\n spaceId: string,\n): Promise<unknown> {\n assertValidSpaceId(spaceId);\n\n const filePath = join(projectMigrationsDir, spaceId, 'contract.json');\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorMissingFile('contract.json', join(projectMigrationsDir, spaceId));\n }\n throw error;\n }\n\n try {\n return JSON.parse(raw);\n } catch (e) {\n throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));\n }\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,mBAAmB;AAEzB,SAAgB,eAAe,SAA0C;CACvE,OAAO,iBAAiB,KAAK,OAAO;AACtC;AAEA,SAAgB,mBAAmB,SAAkD;CACnF,IAAI,CAAC,eAAe,OAAO,GACzB,MAAM,oBAAoB,OAAO;AAErC;;;;;;;;;;;;;AAcA,SAAgB,wBAAwB,sBAA8B,SAAyB;CAC7F,mBAAmB,OAAO;CAC1B,OAAO,KAAK,sBAAsB,OAAO;AAC3C;;;;;;;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,GAAG,OAAO;EACpB,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,OAAO;CACT,CAAC;CAED,OAAO;EAAE,IAAI;EAAO;CAAW;AACjC;;;AC1QA,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;;;;;;;;;;;;AAaA,eAAsB,0BACpB,sBACA,SACkB;CAClB,mBAAmB,OAAO;CAE1B,MAAM,WAAW,KAAK,sBAAsB,SAAS,eAAe;CAEpE,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,SAAS,UAAU,OAAO;CACxC,SAAS,OAAO;EACd,IAAI,aAAa,OAAO,QAAQ,GAC9B,MAAM,iBAAiB,iBAAiB,KAAK,sBAAsB,OAAO,CAAC;EAE7E,MAAM;CACR;CAEA,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,SAAS,GAAG;EACV,MAAM,iBAAiB,UAAU,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;CAC7E;AACF"}
import { _ as errorInvalidRefValue, g as errorInvalidRefName, h as errorInvalidRefFile, t as MigrationToolsError } from "./errors-DIS_dcFJ.mjs";
import { dirname, join, relative } from "pathe";
import { mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from "node:fs/promises";
import { type } from "arktype";
//#region src/refs.ts
/**
* The system head ref lives at `refs/head.json`. It is read (and its
* corruption judged) through `readContractSpaceHeadRef`, not as a
* user-authored ref, so {@link readRefsTolerant} excludes it.
*/
const HEAD_REF_NAME = "head";
const REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
const REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;
function validateRefName(name) {
if (name.length === 0) return false;
if (name.includes("..")) return false;
if (name.includes("//")) return false;
if (name.startsWith(".")) return false;
return REF_NAME_PATTERN.test(name);
}
function validateRefValue(value) {
return REF_VALUE_PATTERN.test(value);
}
const RefEntrySchema = type({
hash: "string",
invariants: "string[]"
}).narrow((entry, ctx) => {
if (!validateRefValue(entry.hash)) return ctx.mustBe(`a valid contract hash (got "${entry.hash}")`);
return true;
});
function refFilePath(refsDir, name) {
return join(refsDir, `${name}.json`);
}
function refNameFromPath(refsDir, filePath) {
return relative(refsDir, filePath).replace(/\.json$/, "");
}
async function readRef(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const filePath = refFilePath(refsDir, name);
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
why: `No ref file found at "${filePath}".`,
fix: `Create the ref with: prisma-next ref set ${name} <hash>`,
details: {
refName: name,
filePath
}
});
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
}
const result = RefEntrySchema(parsed);
if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
return result;
}
async function readRefs(refsDir) {
let entries;
try {
entries = await readdir(refsDir, {
recursive: true,
encoding: "utf-8"
});
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") return {};
throw error;
}
const jsonFiles = entries.filter((entry) => entry.endsWith(".json") && !entry.endsWith(".contract.json"));
const refs = {};
for (const jsonFile of jsonFiles) {
const filePath = join(refsDir, jsonFile);
const name = refNameFromPath(refsDir, filePath);
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
const code = error instanceof Error ? error.code : void 0;
if (code === "ENOENT" || code === "EISDIR") continue;
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
}
const result = RefEntrySchema(parsed);
if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
refs[name] = result;
}
return refs;
}
/**
* Read a space's user-authored refs without ever throwing on disk
* content. A ref whose JSON is unparseable or whose shape fails
* {@link RefEntrySchema} is omitted from `refs` and reported as a
* {@link RefLoadProblem}; the remaining well-formed refs are still
* returned. A missing `refs/` directory yields no refs and no problems.
*
* `refs/head.json` is deliberately skipped here: the system head ref is
* read through `readContractSpaceHeadRef` (which validates head-ref
* shape, distinct from the strict user-ref hash grammar), so it is judged
* there and never doubles as a user ref. Genuine I/O faults (EACCES, EIO,
* …) still propagate — only parse / schema problems are made tolerant.
*/
async function readRefsTolerant(refsDir) {
let entries;
try {
entries = await readdir(refsDir, {
recursive: true,
encoding: "utf-8"
});
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") return {
refs: {},
problems: []
};
throw error;
}
const jsonFiles = entries.filter((entry) => entry.endsWith(".json") && !entry.endsWith(".contract.json") && entry !== `head.json`);
const refs = {};
const problems = [];
for (const jsonFile of jsonFiles) {
const filePath = join(refsDir, jsonFile);
const name = refNameFromPath(refsDir, filePath);
let raw;
try {
raw = await readFile(filePath, "utf-8");
} catch (error) {
const code = error instanceof Error ? error.code : void 0;
if (code === "ENOENT" || code === "EISDIR") continue;
throw error;
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch (e) {
problems.push({
refName: name,
detail: e instanceof Error ? e.message : String(e)
});
continue;
}
const result = RefEntrySchema(parsed);
if (result instanceof type.errors) {
problems.push({
refName: name,
detail: result.summary
});
continue;
}
refs[name] = result;
}
return {
refs,
problems
};
}
async function writeRef(refsDir, name, entry) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
if (!validateRefValue(entry.hash)) throw errorInvalidRefValue(entry.hash);
const filePath = refFilePath(refsDir, name);
const dir = dirname(filePath);
await mkdir(dir, { recursive: true });
const tmpPath = join(dir, `.${name.split("/").pop()}.json.${Date.now()}.tmp`);
await writeFile(tmpPath, `${JSON.stringify({
hash: entry.hash,
invariants: [...entry.invariants]
}, null, 2)}\n`);
await rename(tmpPath, filePath);
}
async function deleteRef(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const filePath = refFilePath(refsDir, name);
try {
await unlink(filePath);
} catch (error) {
if (error instanceof Error && error.code === "ENOENT") throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
why: `No ref file found at "${filePath}".`,
fix: "Run `prisma-next ref list` to see available refs.",
details: {
refName: name,
filePath
}
});
throw error;
}
let dir = dirname(filePath);
while (dir !== refsDir && dir.startsWith(refsDir)) try {
await rmdir(dir);
dir = dirname(dir);
} catch (error) {
const code = error instanceof Error ? error.code : void 0;
if (code === "ENOTEMPTY" || code === "EEXIST" || code === "ENOENT") break;
throw error;
}
}
/**
* Index user-authored refs by the contract hash each ref points at.
* Each bucket is sorted lex-asc for deterministic output.
*/
function refsByContractHash(refs) {
const byHash = /* @__PURE__ */ new Map();
for (const [name, entry] of Object.entries(refs)) {
const bucket = byHash.get(entry.hash);
if (bucket) bucket.push(name);
else byHash.set(entry.hash, [name]);
}
for (const bucket of byHash.values()) bucket.sort();
return byHash;
}
/**
* Read `migrations/<space>/refs/*.json` and index by destination hash.
* Returns an empty map when the refs directory does not exist.
*/
async function resolveRefsByContractHash(refsDir) {
return refsByContractHash(await readRefs(refsDir));
}
function resolveRef(refs, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
if (!Object.hasOwn(refs, name)) throw new MigrationToolsError("MIGRATION.UNKNOWN_REF", `Unknown ref "${name}"`, {
why: `No ref named "${name}" exists.`,
fix: `Available refs: ${Object.keys(refs).join(", ") || "(none)"}. Create a ref with: prisma-next ref set ${name} <hash>`,
details: {
refName: name,
availableRefs: Object.keys(refs)
}
});
return refs[name];
}
//#endregion
export { readRefsTolerant as a, resolveRefsByContractHash as c, writeRef as d, readRefs as i, validateRefName as l, deleteRef as n, refsByContractHash as o, readRef as r, resolveRef as s, HEAD_REF_NAME as t, validateRefValue as u };
//# sourceMappingURL=refs-CDIHeNcC.mjs.map
{"version":3,"file":"refs-CDIHeNcC.mjs","names":[],"sources":["../src/refs.ts"],"sourcesContent":["import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from 'node:fs/promises';\nimport { type } from 'arktype';\nimport { dirname, join, relative } from 'pathe';\nimport {\n errorInvalidRefFile,\n errorInvalidRefName,\n errorInvalidRefValue,\n MigrationToolsError,\n} from './errors';\n\nexport interface RefEntry {\n readonly hash: string;\n readonly invariants: readonly string[];\n}\n\nexport type Refs = Readonly<Record<string, RefEntry>>;\n\n/**\n * The system head ref lives at `refs/head.json`. It is read (and its\n * corruption judged) through `readContractSpaceHeadRef`, not as a\n * user-authored ref, so {@link readRefsTolerant} excludes it.\n */\nexport const HEAD_REF_NAME = 'head';\n\n/**\n * A single ref file that exists on disk but cannot be turned into a\n * {@link RefEntry} (unparseable JSON or schema-invalid content). The ref\n * is omitted from the result; the problem is surfaced for the integrity\n * layer to report as `refUnreadable` rather than aborting the load.\n */\nexport interface RefLoadProblem {\n readonly refName: string;\n readonly detail: string;\n}\n\nexport interface TolerantRefsResult {\n readonly refs: Refs;\n readonly problems: readonly RefLoadProblem[];\n}\n\nconst REF_NAME_PATTERN = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\/[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\nconst REF_VALUE_PATTERN = /^sha256:(empty|[0-9a-f]{64})$/;\n\nexport function validateRefName(name: string): boolean {\n if (name.length === 0) return false;\n if (name.includes('..')) return false;\n if (name.includes('//')) return false;\n if (name.startsWith('.')) return false;\n return REF_NAME_PATTERN.test(name);\n}\n\nexport function validateRefValue(value: string): boolean {\n return REF_VALUE_PATTERN.test(value);\n}\n\nconst RefEntrySchema = type({\n hash: 'string',\n invariants: 'string[]',\n}).narrow((entry, ctx) => {\n if (!validateRefValue(entry.hash))\n return ctx.mustBe(`a valid contract hash (got \"${entry.hash}\")`);\n return true;\n});\n\nfunction refFilePath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.json`);\n}\n\nfunction refNameFromPath(refsDir: string, filePath: string): string {\n const rel = relative(refsDir, filePath);\n return rel.replace(/\\.json$/, '');\n}\n\nexport async function readRef(refsDir: string, name: string): Promise<RefEntry> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const filePath = refFilePath(refsDir, name);\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref file found at \"${filePath}\".`,\n fix: `Create the ref with: prisma-next ref set ${name} <hash>`,\n details: { refName: name, filePath },\n });\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n return result;\n}\n\nexport async function readRefs(refsDir: string): Promise<Refs> {\n let entries: string[];\n try {\n entries = await readdir(refsDir, { recursive: true, encoding: 'utf-8' });\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return {};\n }\n throw error;\n }\n\n const jsonFiles = entries.filter(\n (entry) => entry.endsWith('.json') && !entry.endsWith('.contract.json'),\n );\n const refs: Record<string, RefEntry> = {};\n\n for (const jsonFile of jsonFiles) {\n const filePath = join(refsDir, jsonFile);\n const name = refNameFromPath(refsDir, filePath);\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n // Tolerate the TOCTOU race between `readdir` and `readFile` (ENOENT) and\n // benign EISDIR if a directory happens to end in `.json`. Anything else\n // (EACCES, EIO, EMFILE, …) is a real failure and propagates so the CLI\n // surfaces it rather than silently dropping the ref.\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOENT' || code === 'EISDIR') {\n continue;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n refs[name] = result;\n }\n\n return refs;\n}\n\n/**\n * Read a space's user-authored refs without ever throwing on disk\n * content. A ref whose JSON is unparseable or whose shape fails\n * {@link RefEntrySchema} is omitted from `refs` and reported as a\n * {@link RefLoadProblem}; the remaining well-formed refs are still\n * returned. A missing `refs/` directory yields no refs and no problems.\n *\n * `refs/head.json` is deliberately skipped here: the system head ref is\n * read through `readContractSpaceHeadRef` (which validates head-ref\n * shape, distinct from the strict user-ref hash grammar), so it is judged\n * there and never doubles as a user ref. Genuine I/O faults (EACCES, EIO,\n * …) still propagate — only parse / schema problems are made tolerant.\n */\nexport async function readRefsTolerant(refsDir: string): Promise<TolerantRefsResult> {\n let entries: string[];\n try {\n entries = await readdir(refsDir, { recursive: true, encoding: 'utf-8' });\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n return { refs: {}, problems: [] };\n }\n throw error;\n }\n\n const jsonFiles = entries.filter(\n (entry) =>\n entry.endsWith('.json') &&\n !entry.endsWith('.contract.json') &&\n entry !== `${HEAD_REF_NAME}.json`,\n );\n const refs: Record<string, RefEntry> = {};\n const problems: RefLoadProblem[] = [];\n\n for (const jsonFile of jsonFiles) {\n const filePath = join(refsDir, jsonFile);\n const name = refNameFromPath(refsDir, filePath);\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n // Tolerate the TOCTOU race between `readdir` and `readFile` (ENOENT)\n // and benign EISDIR if a directory happens to end in `.json`.\n // Anything else (EACCES, EIO, …) is a real failure and propagates.\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOENT' || code === 'EISDIR') {\n continue;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n problems.push({ refName: name, detail: e instanceof Error ? e.message : String(e) });\n continue;\n }\n\n const result = RefEntrySchema(parsed);\n if (result instanceof type.errors) {\n problems.push({ refName: name, detail: result.summary });\n continue;\n }\n\n refs[name] = result;\n }\n\n return { refs, problems };\n}\n\nexport async function writeRef(refsDir: string, name: string, entry: RefEntry): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n if (!validateRefValue(entry.hash)) {\n throw errorInvalidRefValue(entry.hash);\n }\n\n const filePath = refFilePath(refsDir, name);\n const dir = dirname(filePath);\n await mkdir(dir, { recursive: true });\n\n const tmpPath = join(dir, `.${name.split('/').pop()}.json.${Date.now()}.tmp`);\n await writeFile(\n tmpPath,\n `${JSON.stringify({ hash: entry.hash, invariants: [...entry.invariants] }, null, 2)}\\n`,\n );\n await rename(tmpPath, filePath);\n}\n\nexport async function deleteRef(refsDir: string, name: string): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const filePath = refFilePath(refsDir, name);\n try {\n await unlink(filePath);\n } catch (error) {\n if (error instanceof Error && (error as { code?: string }).code === 'ENOENT') {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref file found at \"${filePath}\".`,\n fix: 'Run `prisma-next ref list` to see available refs.',\n details: { refName: name, filePath },\n });\n }\n throw error;\n }\n\n // Clean empty parent directories up to refsDir. Stop walking on the expected\n // \"directory has siblings\" signal (ENOTEMPTY on Linux, EEXIST on some BSDs)\n // and on ENOENT (concurrent removal). Anything else (EACCES, EIO, …) is a\n // real failure and propagates.\n let dir = dirname(filePath);\n while (dir !== refsDir && dir.startsWith(refsDir)) {\n try {\n await rmdir(dir);\n dir = dirname(dir);\n } catch (error) {\n const code = error instanceof Error ? (error as { code?: string }).code : undefined;\n if (code === 'ENOTEMPTY' || code === 'EEXIST' || code === 'ENOENT') {\n break;\n }\n throw error;\n }\n }\n}\n\n/**\n * Index user-authored refs by the contract hash each ref points at.\n * Each bucket is sorted lex-asc for deterministic output.\n */\nexport function refsByContractHash(refs: Refs): ReadonlyMap<string, readonly string[]> {\n const byHash = new Map<string, string[]>();\n for (const [name, entry] of Object.entries(refs)) {\n const bucket = byHash.get(entry.hash);\n if (bucket) bucket.push(name);\n else byHash.set(entry.hash, [name]);\n }\n for (const bucket of byHash.values()) {\n bucket.sort();\n }\n return byHash;\n}\n\n/**\n * Read `migrations/<space>/refs/*.json` and index by destination hash.\n * Returns an empty map when the refs directory does not exist.\n */\nexport async function resolveRefsByContractHash(\n refsDir: string,\n): Promise<ReadonlyMap<string, readonly string[]>> {\n return refsByContractHash(await readRefs(refsDir));\n}\n\nexport function resolveRef(refs: Refs, name: string): RefEntry {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n // Object.hasOwn gate: plain-object `refs` would otherwise let\n // `refs['constructor']` return Object.prototype.constructor and bypass the\n // UNKNOWN_REF throw. validateRefName accepts `\"constructor\"` as a name shape.\n if (!Object.hasOwn(refs, name)) {\n throw new MigrationToolsError('MIGRATION.UNKNOWN_REF', `Unknown ref \"${name}\"`, {\n why: `No ref named \"${name}\" exists.`,\n fix: `Available refs: ${Object.keys(refs).join(', ') || '(none)'}. Create a ref with: prisma-next ref set ${name} <hash>`,\n details: { refName: name, availableRefs: Object.keys(refs) },\n });\n }\n\n // biome-ignore lint/style/noNonNullAssertion: Object.hasOwn gate above guarantees this is defined\n return refs[name]!;\n}\n"],"mappings":";;;;;;;;;;AAsBA,MAAa,gBAAgB;AAkB7B,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAE1B,SAAgB,gBAAgB,MAAuB;CACrD,IAAI,KAAK,WAAW,GAAG,OAAO;CAC9B,IAAI,KAAK,SAAS,IAAI,GAAG,OAAO;CAChC,IAAI,KAAK,SAAS,IAAI,GAAG,OAAO;CAChC,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CACjC,OAAO,iBAAiB,KAAK,IAAI;AACnC;AAEA,SAAgB,iBAAiB,OAAwB;CACvD,OAAO,kBAAkB,KAAK,KA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,2CAA2C,KAAK;EACjH,SAAS;GAAE,SAAS;GAAM,eAAe,OAAO,KAAK,IAAI;EAAE;CAC7D,CAAC;CAIH,OAAO,KAAK;AACd"}
import { g as errorInvalidRefName, h as errorInvalidRefFile, t as MigrationToolsError } from "./errors-DIS_dcFJ.mjs";
import { d as writeRef, l as validateRefName, n as deleteRef } from "./refs-CDIHeNcC.mjs";
import { basename, dirname, join } from "pathe";
import { access, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
import { type } from "arktype";
import { randomBytes } from "node:crypto";
import { canonicalizeJson } from "@prisma-next/framework-components/utils";
//#region src/refs/snapshot.ts
const ContractIrSchema = type({
targetFamily: "string",
target: "string",
profileHash: "string",
storage: type({ storageHash: "string" }),
domain: type({ namespaces: "object" })
});
function hasErrnoCode(error, code) {
return error instanceof Error && error.code === code;
}
function snapshotJsonPath(refsDir, name) {
return join(refsDir, `${name}.contract.json`);
}
function snapshotDtsPath(refsDir, name) {
return join(refsDir, `${name}.contract.d.ts`);
}
function tmpPathFor(finalPath) {
return join(dirname(finalPath), `.${basename(finalPath)}.${Date.now()}-${randomBytes(4).toString("hex")}.tmp`);
}
async function atomicWriteFile(finalPath, content) {
await mkdir(dirname(finalPath), { recursive: true });
const tmpPath = tmpPathFor(finalPath);
await writeFile(tmpPath, content);
await rename(tmpPath, finalPath);
}
async function unlinkIfExists(filePath) {
try {
await unlink(filePath);
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return;
throw error;
}
}
function parseContractSnapshotJson(filePath, raw) {
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
throw errorInvalidRefFile(filePath, "Failed to parse as JSON");
}
const result = ContractIrSchema(parsed);
if (result instanceof type.errors) throw errorInvalidRefFile(filePath, result.summary);
return result;
}
async function writeRefSnapshot(refsDir, name, snapshot) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const jsonPath = snapshotJsonPath(refsDir, name);
const dtsPath = snapshotDtsPath(refsDir, name);
const jsonContent = `${canonicalizeJson(snapshot.contract)}\n`;
const dtsContent = snapshot.contractDts.endsWith("\n") ? snapshot.contractDts : `${snapshot.contractDts}\n`;
try {
await atomicWriteFile(jsonPath, jsonContent);
} catch (error) {
await unlinkIfExists(jsonPath);
throw error;
}
try {
await atomicWriteFile(dtsPath, dtsContent);
} catch (error) {
await unlinkIfExists(jsonPath);
await unlinkIfExists(dtsPath);
throw error;
}
}
async function readRefSnapshot(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const jsonPath = snapshotJsonPath(refsDir, name);
const dtsPath = snapshotDtsPath(refsDir, name);
let raw;
try {
raw = await readFile(jsonPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return null;
throw error;
}
const contract = parseContractSnapshotJson(jsonPath, raw);
let contractDts;
try {
contractDts = await readFile(dtsPath, "utf-8");
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw errorInvalidRefFile(dtsPath, "Missing paired contract.d.ts snapshot file");
throw error;
}
return {
contract,
contractDts
};
}
async function deleteRefSnapshot(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
await unlinkIfExists(snapshotJsonPath(refsDir, name));
await unlinkIfExists(snapshotDtsPath(refsDir, name));
}
async function writeRefPaired(refsDir, name, entry, snapshot) {
await writeRefSnapshot(refsDir, name, snapshot);
try {
await writeRef(refsDir, name, entry);
} catch (writeError) {
try {
await deleteRefSnapshot(refsDir, name);
} catch {}
throw writeError;
}
}
function isUnknownRefError(error) {
return MigrationToolsError.is(error) && error.code === "MIGRATION.UNKNOWN_REF";
}
async function snapshotFilesExist(refsDir, name) {
if (!validateRefName(name)) throw errorInvalidRefName(name);
const paths = [snapshotJsonPath(refsDir, name), snapshotDtsPath(refsDir, name)];
return (await Promise.allSettled(paths.map((filePath) => access(filePath)))).some((result) => result.status === "fulfilled");
}
async function deleteRefPaired(refsDir, name) {
if (await snapshotFilesExist(refsDir, name)) {
try {
await deleteRef(refsDir, name);
} catch (error) {
if (!isUnknownRefError(error)) throw error;
}
await deleteRefSnapshot(refsDir, name);
return;
}
await deleteRef(refsDir, name);
await deleteRefSnapshot(refsDir, name);
}
//#endregion
export { writeRefSnapshot as a, writeRefPaired as i, deleteRefSnapshot as n, readRefSnapshot as r, deleteRefPaired as t };
//# sourceMappingURL=snapshot-DiE5uFFJ.mjs.map
{"version":3,"file":"snapshot-DiE5uFFJ.mjs","names":[],"sources":["../src/refs/snapshot.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto';\nimport { access, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';\nimport { canonicalizeJson } from '@prisma-next/framework-components/utils';\nimport { type } from 'arktype';\nimport { basename, dirname, join } from 'pathe';\nimport { errorInvalidRefFile, errorInvalidRefName, MigrationToolsError } from '../errors';\nimport { deleteRef, type RefEntry, validateRefName, writeRef } from '../refs';\n\nexport interface ContractIR {\n readonly contract: unknown;\n readonly contractDts: string;\n}\n\nconst ContractIrSchema = type({\n targetFamily: 'string',\n target: 'string',\n profileHash: 'string',\n storage: type({\n storageHash: 'string',\n }),\n domain: type({\n namespaces: 'object',\n }),\n});\n\nfunction hasErrnoCode(error: unknown, code: string): boolean {\n return error instanceof Error && (error as { code?: string }).code === code;\n}\n\nfunction snapshotJsonPath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.contract.json`);\n}\n\nfunction snapshotDtsPath(refsDir: string, name: string): string {\n return join(refsDir, `${name}.contract.d.ts`);\n}\n\nfunction tmpPathFor(finalPath: string): string {\n const dir = dirname(finalPath);\n const fileName = basename(finalPath);\n return join(dir, `.${fileName}.${Date.now()}-${randomBytes(4).toString('hex')}.tmp`);\n}\n\nasync function atomicWriteFile(finalPath: string, content: string): Promise<void> {\n const dir = dirname(finalPath);\n await mkdir(dir, { recursive: true });\n const tmpPath = tmpPathFor(finalPath);\n await writeFile(tmpPath, content);\n await rename(tmpPath, finalPath);\n}\n\nasync function unlinkIfExists(filePath: string): Promise<void> {\n try {\n await unlink(filePath);\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) return;\n throw error;\n }\n}\n\nfunction parseContractSnapshotJson(filePath: string, raw: string): unknown {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw errorInvalidRefFile(filePath, 'Failed to parse as JSON');\n }\n\n const result = ContractIrSchema(parsed);\n if (result instanceof type.errors) {\n throw errorInvalidRefFile(filePath, result.summary);\n }\n\n return result;\n}\n\nexport async function writeRefSnapshot(\n refsDir: string,\n name: string,\n snapshot: ContractIR,\n): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const jsonPath = snapshotJsonPath(refsDir, name);\n const dtsPath = snapshotDtsPath(refsDir, name);\n const jsonContent = `${canonicalizeJson(snapshot.contract)}\\n`;\n const dtsContent = snapshot.contractDts.endsWith('\\n')\n ? snapshot.contractDts\n : `${snapshot.contractDts}\\n`;\n\n try {\n await atomicWriteFile(jsonPath, jsonContent);\n } catch (error) {\n await unlinkIfExists(jsonPath);\n throw error;\n }\n\n try {\n await atomicWriteFile(dtsPath, dtsContent);\n } catch (error) {\n await unlinkIfExists(jsonPath);\n await unlinkIfExists(dtsPath);\n throw error;\n }\n}\n\nexport async function readRefSnapshot(refsDir: string, name: string): Promise<ContractIR | null> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const jsonPath = snapshotJsonPath(refsDir, name);\n const dtsPath = snapshotDtsPath(refsDir, name);\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return null;\n }\n throw error;\n }\n\n const contract = parseContractSnapshotJson(jsonPath, raw);\n\n let contractDts: string;\n try {\n contractDts = await readFile(dtsPath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n throw errorInvalidRefFile(dtsPath, 'Missing paired contract.d.ts snapshot file');\n }\n throw error;\n }\n\n return { contract, contractDts };\n}\n\nexport async function deleteRefSnapshot(refsDir: string, name: string): Promise<void> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n await unlinkIfExists(snapshotJsonPath(refsDir, name));\n await unlinkIfExists(snapshotDtsPath(refsDir, name));\n}\n\nexport async function writeRefPaired(\n refsDir: string,\n name: string,\n entry: RefEntry,\n snapshot: ContractIR,\n): Promise<void> {\n await writeRefSnapshot(refsDir, name, snapshot);\n try {\n await writeRef(refsDir, name, entry);\n } catch (writeError) {\n try {\n await deleteRefSnapshot(refsDir, name);\n } catch {\n // Rollback failure is secondary; preserve the original writeRef error.\n }\n throw writeError;\n }\n}\n\nfunction isUnknownRefError(error: unknown): boolean {\n return MigrationToolsError.is(error) && error.code === 'MIGRATION.UNKNOWN_REF';\n}\n\nasync function snapshotFilesExist(refsDir: string, name: string): Promise<boolean> {\n if (!validateRefName(name)) {\n throw errorInvalidRefName(name);\n }\n\n const paths = [snapshotJsonPath(refsDir, name), snapshotDtsPath(refsDir, name)];\n const checks = await Promise.allSettled(paths.map((filePath) => access(filePath)));\n return checks.some((result) => result.status === 'fulfilled');\n}\n\nexport async function deleteRefPaired(refsDir: string, name: string): Promise<void> {\n if (await snapshotFilesExist(refsDir, name)) {\n try {\n await deleteRef(refsDir, name);\n } catch (error) {\n if (!isUnknownRefError(error)) {\n throw error;\n }\n }\n await deleteRefSnapshot(refsDir, name);\n return;\n }\n\n await deleteRef(refsDir, name);\n await deleteRefSnapshot(refsDir, name);\n}\n"],"mappings":";;;;;;;;AAaA,MAAM,mBAAmB,KAAK;CAC5B,cAAc;CACd,QAAQ;CACR,aAAa;CACb,SAAS,KAAK,EACZ,aAAa,SACf,CAAC;CACD,QAAQ,KAAK,EACX,YAAY,SACd,CAAC;AACH,CAAC;AAED,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;AAEA,SAAS,iBAAiB,SAAiB,MAAsB;CAC/D,OAAO,KAAK,SAAS,GAAG,KAAK,eAAe;AAC9C;AAEA,SAAS,gBAAgB,S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AC,gBAAgB,IAAI,GACvB,MAAM,oBAAoB,IAAI;CAGhC,MAAM,QAAQ,CAAC,iBAAiB,SAAS,IAAI,GAAG,gBAAgB,SAAS,IAAI,CAAC;CAE9E,QAAO,MADc,QAAQ,WAAW,MAAM,KAAK,aAAa,OAAO,QAAQ,CAAC,CAAC,EAAA,CACnE,MAAM,WAAW,OAAO,WAAW,WAAW;AAC9D;AAEA,eAAsB,gBAAgB,SAAiB,MAA6B;CAClF,IAAI,MAAM,mBAAmB,SAAS,IAAI,GAAG;EAC3C,IAAI;GACF,MAAM,UAAU,SAAS,IAAI;EAC/B,SAAS,OAAO;GACd,IAAI,CAAC,kBAAkB,KAAK,GAC1B,MAAM;EAEV;EACA,MAAM,kBAAkB,SAAS,IAAI;EACrC;CACF;CAEA,MAAM,UAAU,SAAS,IAAI;CAC7B,MAAM,kBAAkB,SAAS,IAAI;AACvC"}
//#region src/verify-contract-spaces.d.ts
/**
* List the per-space subdirectories under
* `<projectRoot>/migrations/`. Returns space-id directory names (sorted
* alphabetically) — i.e. any non-dot-prefixed subdirectory whose root
* does **not** contain a `migration.json` manifest. The manifest is the
* structural marker of a user-authored migration directory (see
* `readMigrationsDir` in `./io`); directory names themselves belong to
* the user and are not part of the contract.
*
* Returns `[]` if the migrations directory does not exist (greenfield
* project).
*
* Reads only the user's repo. **No descriptor import.** The caller
* (verifier) feeds the result into {@link verifyContractSpaces} alongside
* the loaded-space set and the marker rows.
*/
declare function listContractSpaceDirectories(projectMigrationsDir: string): Promise<readonly string[]>;
/**
* On-disk head value (`(hash, invariants)`) for one contract space.
* The verifier compares this against the marker row for the same space
* to detect drift between the user-emitted artefacts and the live DB
* marker.
*/
interface ContractSpaceHeadRecord {
readonly hash: string;
readonly invariants: readonly string[];
}
/**
* Marker row read from `prisma_contract.marker` (one per `space`).
* Caller resolves these via the family runtime's marker reader before
* invoking {@link verifyContractSpaces}.
*/
interface SpaceMarkerRecord {
readonly hash: string;
readonly invariants: readonly string[];
}
interface VerifyContractSpacesInputs {
/**
* Set of contract spaces the project declares: `'app'` plus each
* extension space in `extensionPacks`. The caller's discovery path
* never reads the extension descriptor module — it walks the
* `extensionPacks` configuration in `prisma-next.config.ts` for the
* space ids.
*/
readonly loadedSpaces: ReadonlySet<string>;
/**
* Per-space subdirectories observed under
* `<projectRoot>/migrations/`. Resolved via
* {@link listContractSpaceDirectories}.
*/
readonly spaceDirsOnDisk: readonly string[];
/**
* Head ref per space, keyed by space id. Caller reads
* `<projectRoot>/migrations/<space-id>/contract.json` and
* `<projectRoot>/migrations/<space-id>/refs/head.json` to construct
* this map. Spaces with no contract-space dir on disk simply omit a
* map entry.
*/
readonly headRefsBySpace: ReadonlyMap<string, ContractSpaceHeadRecord>;
/**
* Marker rows keyed by `space`. Caller reads them from the
* `prisma_contract.marker` table.
*/
readonly markerRowsBySpace: ReadonlyMap<string, SpaceMarkerRecord>;
}
type SpaceVerifierViolation = {
readonly kind: 'declaredButUnmigrated';
readonly spaceId: string;
readonly remediation: string;
} | {
readonly kind: 'orphanMarker';
readonly spaceId: string;
readonly remediation: string;
} | {
readonly kind: 'orphanSpaceDir';
readonly spaceId: string;
readonly remediation: string;
} | {
readonly kind: 'hashMismatch';
readonly spaceId: string;
readonly priorHeadHash: string;
readonly markerHash: string;
readonly remediation: string;
} | {
readonly kind: 'invariantsMismatch';
readonly spaceId: string;
readonly onDiskInvariants: readonly string[];
readonly markerInvariants: readonly string[];
readonly remediation: string;
};
type VerifyContractSpacesResult = {
readonly ok: true;
} | {
readonly ok: false;
readonly violations: readonly SpaceVerifierViolation[];
};
/**
* Pure structural verifier for the per-space mechanism. Aggregates the
* three orphan / missing checks plus per-space hash and invariant
* comparison.
*
* Algorithm:
*
* - For every extension space declared in `loadedSpaces` (`'app'`
* excluded — the per-space verifier is scoped to extension spaces;
* the app is verified through the aggregate path):
* - If no contract-space dir on disk → `declaredButUnmigrated`.
* - Else if `markerRowsBySpace` lacks an entry → no violation here;
* the live-DB compare done outside this helper is where the
* absence shows up.
* - Else compare marker hash / invariants vs. on-disk head hash /
* invariants → `hashMismatch` / `invariantsMismatch` on drift.
* - For every contract-space dir on disk that is not in `loadedSpaces` →
* `orphanSpaceDir`.
* - For every marker row whose `space` is not in `loadedSpaces` →
* `orphanMarker`. The app-space marker is always loaded (`'app'` is
* in `loadedSpaces` by definition).
*
* Output is deterministic: violations are sorted first by `kind`
* (`declaredButUnmigrated` → `orphanMarker` → `orphanSpaceDir` →
* `hashMismatch` → `invariantsMismatch`) then by `spaceId`. Two callers
* passing equivalent inputs see byte-identical violation lists.
*
* Synchronous, pure, no I/O. **Does not import the extension descriptor**
* (the inputs are pre-resolved by the caller); the verifier reads only
* the user repo, not `node_modules`.
*/
declare function verifyContractSpaces(inputs: VerifyContractSpacesInputs): VerifyContractSpacesResult;
//#endregion
export { VerifyContractSpacesResult as a, VerifyContractSpacesInputs as i, SpaceMarkerRecord as n, listContractSpaceDirectories as o, SpaceVerifierViolation as r, verifyContractSpaces as s, ContractSpaceHeadRecord as t };
//# sourceMappingURL=verify-contract-spaces-zYlAhXOK.d.mts.map
{"version":3,"file":"verify-contract-spaces-zYlAhXOK.d.mts","names":[],"sources":["../src/verify-contract-spaces.ts"],"mappings":";;;;;;;;;;;;;;;;;iBAyBsB,6BACpB,+BACC;;;;;;;UAyCc;WACN;WACA;;;;;;;UAQM;WACN;WACA;;UAGM;;;;;;;;WAQN,cAAc;;;;;;WAOd;;;;;;;;WASA,iBAAiB,oBAAoB;;;;;WAMrC,mBAAmB,oBAAoB;;KAGtC;WAEG;WACA;WACA;;WAGA;WACA;WACA;;WAGA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;WAGA;WACA;WACA;WACA;WACA;;KAGH;WACG;;WACA;WAAoB,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiCxC,qBACd,QAAQ,6BACP"}
import { mkdir, writeFile } from 'node:fs/promises';
import { canonicalizeJson } from '@prisma-next/framework-components/utils';
import { join } from 'pathe';
import type { ContractSpaceHeadRef } from './read-contract-space-head-ref';
import { assertValidSpaceId, spaceRefsDirectory } from './space-layout';
/**
* Inputs for {@link emitContractSpaceArtefacts}.
*
* - `contract` is the canonical contract value the framework just emitted
* for the space; it is serialised through {@link canonicalizeJson}, so
* it must be a JSON-compatible value (objects / arrays / primitives).
* Typed as `unknown` rather than the SQL-family `Contract<SqlStorage>`
* to keep `migration-tools` framework-neutral; SQL-family callers pass
* their typed value through unchanged.
*
* - `contractDts` is the pre-rendered `.d.ts` text. Rendering happens in
* the SQL family (which owns the codec / typemap input the renderer
* needs), so this helper accepts the text verbatim and writes it out
* without further transformation.
*
* - `headRef` is the head reference for the space.
* `invariants` are sorted alphabetically before serialisation so two
* callers passing the same set in different orders produce
* byte-identical `refs/head.json`.
*/
export interface ContractSpaceArtefactInputs {
readonly contract: unknown;
readonly contractDts: string;
readonly headRef: ContractSpaceHeadRef;
}
/**
* Emit the per-space artefacts (`contract.json`, `contract.d.ts`,
* `refs/head.json`) under `<projectMigrationsDir>/<spaceId>/`.
*
* Always-overwrite: the framework owns these files; running `migrate`
* twice with the same inputs is a no-op observably (idempotent), but the
* helper does not check pre-existing contents — re-emit always wins.
*
* Path layout matches the convention in
* [`spaceMigrationDirectory`](./space-layout.ts). The space id is
* validated against `[a-z][a-z0-9_-]{0,63}` via
* {@link assertValidSpaceId} for filesystem-safety reasons; the helper
* accepts every space uniformly (including the app space, default
* `'app'`).
*
* The migrations directory and space subdirectory are created if they
* do not yet exist (`mkdir { recursive: true }`).
*/
export async function emitContractSpaceArtefacts(
projectMigrationsDir: string,
spaceId: string,
inputs: ContractSpaceArtefactInputs,
): Promise<void> {
assertValidSpaceId(spaceId);
const dir = join(projectMigrationsDir, spaceId);
const refsDir = spaceRefsDirectory(dir);
await mkdir(refsDir, { recursive: true });
await writeFile(join(dir, 'contract.json'), `${canonicalizeJson(inputs.contract)}\n`);
await writeFile(join(dir, 'contract.d.ts'), inputs.contractDts);
const sortedInvariants = [...inputs.headRef.invariants].sort();
const headJson = canonicalizeJson({
hash: inputs.headRef.hash,
invariants: sortedInvariants,
});
await writeFile(join(refsDir, 'head.json'), `${headJson}\n`);
}
import { readFile } from 'node:fs/promises';
import { join } from 'pathe';
import { errorInvalidJson, errorMissingFile } from './errors';
import { assertValidSpaceId } from './space-layout';
function hasErrnoCode(error: unknown, code: string): boolean {
return error instanceof Error && (error as { code?: string }).code === code;
}
/**
* Read the on-disk contract value for a contract space
* (`<projectMigrationsDir>/<spaceId>/contract.json`). Returns the parsed
* JSON value as `unknown` — callers that need a typed contract validate
* via their family's `deserializeContract` to surface schema issues.
*
* Companion to {@link import('./read-contract-space-head-ref').readContractSpaceHeadRef}
* — same ENOENT-throws / corrupt-file-error semantics. Returns the
* canonical-JSON value the framework wrote during emit, so re-running
* this helper across machines / runs yields a byte-identical value.
*/
export async function readContractSpaceContract(
projectMigrationsDir: string,
spaceId: string,
): Promise<unknown> {
assertValidSpaceId(spaceId);
const filePath = join(projectMigrationsDir, spaceId, 'contract.json');
let raw: string;
try {
raw = await readFile(filePath, 'utf-8');
} catch (error) {
if (hasErrnoCode(error, 'ENOENT')) {
throw errorMissingFile('contract.json', join(projectMigrationsDir, spaceId));
}
throw error;
}
try {
return JSON.parse(raw);
} catch (e) {
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
}
}

Sorry, the diff of this file is too big to display