@prisma-next/migration-tools 0.11.0-dev.24 → 0.11.0-dev.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/exports/aggregate.d.mts +4 -4
  2. package/dist/exports/aggregate.mjs +2 -1
  3. package/dist/exports/aggregate.mjs.map +1 -1
  4. package/dist/exports/enumerate-migration-spaces.d.mts +53 -0
  5. package/dist/exports/enumerate-migration-spaces.d.mts.map +1 -0
  6. package/dist/exports/enumerate-migration-spaces.mjs +107 -0
  7. package/dist/exports/enumerate-migration-spaces.mjs.map +1 -0
  8. package/dist/exports/graph.d.mts +1 -1
  9. package/dist/exports/hash.d.mts +2 -2
  10. package/dist/exports/invariants.d.mts +1 -1
  11. package/dist/exports/io.d.mts +1 -1
  12. package/dist/exports/metadata.d.mts +1 -1
  13. package/dist/exports/migration-graph.d.mts +2 -2
  14. package/dist/exports/migration-list-types.d.mts +2 -0
  15. package/dist/exports/migration-list-types.mjs +1 -0
  16. package/dist/exports/migration.d.mts +1 -1
  17. package/dist/exports/package.d.mts +1 -1
  18. package/dist/exports/ref-resolution.d.mts +2 -2
  19. package/dist/exports/refs.d.mts +1 -1
  20. package/dist/exports/spaces.d.mts +27 -2
  21. package/dist/exports/spaces.d.mts.map +1 -1
  22. package/dist/exports/spaces.mjs +6 -4
  23. package/dist/exports/spaces.mjs.map +1 -1
  24. package/dist/{graph-BrLXqoUc.d.mts → graph-C7AJPGV5.d.mts} +1 -1
  25. package/dist/{graph-BrLXqoUc.d.mts.map → graph-C7AJPGV5.d.mts.map} +1 -1
  26. package/dist/{migration-graph-De0dUZoC.d.mts → migration-graph-ABYqVsmv.d.mts} +3 -3
  27. package/dist/{migration-graph-De0dUZoC.d.mts.map → migration-graph-ABYqVsmv.d.mts.map} +1 -1
  28. package/dist/migration-list-types-B-qimPet.d.mts +23 -0
  29. package/dist/migration-list-types-B-qimPet.d.mts.map +1 -0
  30. package/dist/{package-DZj8YvD0.d.mts → package-DIttKL7X.d.mts} +1 -1
  31. package/dist/{package-DZj8YvD0.d.mts.map → package-DIttKL7X.d.mts.map} +1 -1
  32. package/dist/read-contract-space-contract-CwwlqKl_.mjs +82 -0
  33. package/dist/read-contract-space-contract-CwwlqKl_.mjs.map +1 -0
  34. package/dist/{refs-CDaNerhT.d.mts → refs-BaygQaFD.d.mts} +1 -1
  35. package/dist/{refs-CDaNerhT.d.mts.map → refs-BaygQaFD.d.mts.map} +1 -1
  36. package/dist/{read-contract-space-contract-Cglige7P.mjs → verify-contract-spaces-DxXWxGR0.mjs} +31 -79
  37. package/dist/verify-contract-spaces-DxXWxGR0.mjs.map +1 -0
  38. package/package.json +14 -6
  39. package/src/emit-contract-space-artefacts.ts +4 -3
  40. package/src/enumerate-migration-spaces.ts +127 -0
  41. package/src/exports/enumerate-migration-spaces.ts +4 -0
  42. package/src/exports/migration-list-types.ts +5 -0
  43. package/src/exports/spaces.ts +3 -0
  44. package/src/migration-list-types.ts +21 -0
  45. package/src/read-contract-space-head-ref.ts +5 -2
  46. package/src/space-layout.ts +30 -0
  47. package/dist/read-contract-space-contract-Cglige7P.mjs.map +0 -1
  48. /package/dist/{metadata-BFX0xdz8.d.mts → metadata-B4Wy6zor.d.mts} +0 -0
package/package.json CHANGED
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "name": "@prisma-next/migration-tools",
3
- "version": "0.11.0-dev.24",
3
+ "version": "0.11.0-dev.25",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "On-disk migration persistence, hash verification, and chain reconstruction for Prisma Next",
8
8
  "dependencies": {
9
- "@prisma-next/contract": "0.11.0-dev.24",
10
- "@prisma-next/framework-components": "0.11.0-dev.24",
11
- "@prisma-next/utils": "0.11.0-dev.24",
9
+ "@prisma-next/contract": "0.11.0-dev.25",
10
+ "@prisma-next/framework-components": "0.11.0-dev.25",
11
+ "@prisma-next/utils": "0.11.0-dev.25",
12
12
  "arktype": "^2.2.0",
13
13
  "pathe": "^2.0.3",
14
14
  "prettier": "^3.8.3"
15
15
  },
16
16
  "devDependencies": {
17
- "@prisma-next/tsconfig": "0.11.0-dev.24",
18
- "@prisma-next/tsdown": "0.11.0-dev.24",
17
+ "@prisma-next/tsconfig": "0.11.0-dev.25",
18
+ "@prisma-next/tsdown": "0.11.0-dev.25",
19
19
  "tsdown": "0.22.0",
20
20
  "typescript": "5.9.3",
21
21
  "vitest": "4.1.6"
@@ -60,6 +60,14 @@
60
60
  "types": "./dist/exports/migration-graph.d.mts",
61
61
  "import": "./dist/exports/migration-graph.mjs"
62
62
  },
63
+ "./migration-list-types": {
64
+ "types": "./dist/exports/migration-list-types.d.mts",
65
+ "import": "./dist/exports/migration-list-types.mjs"
66
+ },
67
+ "./enumerate-migration-spaces": {
68
+ "types": "./dist/exports/enumerate-migration-spaces.d.mts",
69
+ "import": "./dist/exports/enumerate-migration-spaces.mjs"
70
+ },
63
71
  "./refs": {
64
72
  "types": "./dist/exports/refs.d.mts",
65
73
  "import": "./dist/exports/refs.mjs"
@@ -2,7 +2,7 @@ import { mkdir, writeFile } from 'node:fs/promises';
2
2
  import { canonicalizeJson } from '@prisma-next/framework-components/utils';
3
3
  import { join } from 'pathe';
4
4
  import type { ContractSpaceHeadRef } from './read-contract-space-head-ref';
5
- import { assertValidSpaceId } from './space-layout';
5
+ import { assertValidSpaceId, spaceRefsDirectory } from './space-layout';
6
6
 
7
7
  /**
8
8
  * Inputs for {@link emitContractSpaceArtefacts}.
@@ -56,7 +56,8 @@ export async function emitContractSpaceArtefacts(
56
56
  assertValidSpaceId(spaceId);
57
57
 
58
58
  const dir = join(projectMigrationsDir, spaceId);
59
- await mkdir(join(dir, 'refs'), { recursive: true });
59
+ const refsDir = spaceRefsDirectory(dir);
60
+ await mkdir(refsDir, { recursive: true });
60
61
 
61
62
  await writeFile(join(dir, 'contract.json'), `${canonicalizeJson(inputs.contract)}\n`);
62
63
  await writeFile(join(dir, 'contract.d.ts'), inputs.contractDts);
@@ -66,5 +67,5 @@ export async function emitContractSpaceArtefacts(
66
67
  hash: inputs.headRef.hash,
67
68
  invariants: sortedInvariants,
68
69
  });
69
- await writeFile(join(dir, 'refs', 'head.json'), `${headJson}\n`);
70
+ await writeFile(join(refsDir, 'head.json'), `${headJson}\n`);
70
71
  }
@@ -0,0 +1,127 @@
1
+ import { readMigrationsDir } from './io';
2
+ import type { MigrationListEntry, MigrationSpaceListEntry } from './migration-list-types';
3
+ import { readRefs } from './refs';
4
+ import {
5
+ APP_SPACE_ID,
6
+ isValidSpaceId,
7
+ RESERVED_SPACE_SUBDIR_NAMES,
8
+ spaceMigrationDirectory,
9
+ spaceRefsDirectory,
10
+ } from './space-layout';
11
+ import { listContractSpaceDirectories } from './verify-contract-spaces';
12
+
13
+ /**
14
+ * Index `migrations/<space>/refs/*.json` by the contract hash each ref
15
+ * points at, so callers can attach `(ref names)` decorations to every
16
+ * row whose destination contract hash matches.
17
+ *
18
+ * Each bucket is sorted lex-asc to keep rendered output deterministic
19
+ * (adjacent rows pointing at the same hash render their ref decorations
20
+ * in the same order).
21
+ *
22
+ * Refs whose hash matches no migration on disk are still indexed; the
23
+ * caller decides whether to surface them. Migration rows only carry
24
+ * `(refs)` decorations when a matching destination contract hash exists
25
+ * on disk — orphan refs are not rendered on any row.
26
+ *
27
+ * Returns an empty map when the refs directory does not exist
28
+ * ({@link readRefs} treats `ENOENT` as "no refs").
29
+ */
30
+ export async function resolveRefsByContractHash(
31
+ refsDir: string,
32
+ ): Promise<ReadonlyMap<string, readonly string[]>> {
33
+ const refs = await readRefs(refsDir);
34
+ const byHash = new Map<string, string[]>();
35
+ for (const [name, entry] of Object.entries(refs)) {
36
+ const bucket = byHash.get(entry.hash);
37
+ if (bucket) bucket.push(name);
38
+ else byHash.set(entry.hash, [name]);
39
+ }
40
+ for (const bucket of byHash.values()) {
41
+ bucket.sort();
42
+ }
43
+ return byHash;
44
+ }
45
+
46
+ /**
47
+ * Compare two contract-space IDs for the inter-space ordering rule:
48
+ * {@link APP_SPACE_ID} first if present, then lex-asc on the rest.
49
+ */
50
+ function compareSpaceIds(a: string, b: string): number {
51
+ if (a === APP_SPACE_ID) return b === APP_SPACE_ID ? 0 : -1;
52
+ if (b === APP_SPACE_ID) return 1;
53
+ if (a < b) return -1;
54
+ if (a > b) return 1;
55
+ return 0;
56
+ }
57
+
58
+ /**
59
+ * Sort `dirName` descending so the rendered output reads latest-first,
60
+ * matching the `git log` latest-first convention.
61
+ */
62
+ function compareDirNamesDescending(a: MigrationListEntry, b: MigrationListEntry): number {
63
+ if (a.dirName < b.dirName) return 1;
64
+ if (a.dirName > b.dirName) return -1;
65
+ return 0;
66
+ }
67
+
68
+ /**
69
+ * Enumerate every contract space's on-disk migrations under
70
+ * `<projectMigrationsDir>/`. For each valid space directory:
71
+ *
72
+ * - Loads on-disk packages via {@link readMigrationsDir}.
73
+ * - Attaches ref decorations: each migration's `refs[]` lists every ref
74
+ * name from `migrations/<spaceId>/refs/*.json` whose hash equals the
75
+ * migration's destination contract hash.
76
+ * - Sorts migrations within the space by `dirName` descending
77
+ * (reverse-filename, latest first).
78
+ *
79
+ * Contract spaces are returned with {@link APP_SPACE_ID} first when
80
+ * present, then the remaining ids lex-asc. A contract-space directory
81
+ * that contains no migrations becomes `{ spaceId, migrations: [] }` so
82
+ * the renderer's empty-state path can surface it.
83
+ *
84
+ * Directory entries that are not valid {@link isValidSpaceId} names are
85
+ * skipped (a stray non-space directory under `migrations/` does not
86
+ * spawn a phantom space entry). Entries whose name appears in
87
+ * {@link RESERVED_SPACE_SUBDIR_NAMES} are also skipped — the per-space
88
+ * `refs/` subdirectory name shape would otherwise satisfy
89
+ * {@link isValidSpaceId} and surface as a phantom contract space.
90
+ *
91
+ * Returns `[]` when `<projectMigrationsDir>` does not exist — a fresh
92
+ * project that has not authored any migration yet.
93
+ */
94
+ export async function enumerateMigrationSpaces(args: {
95
+ readonly projectMigrationsDir: string;
96
+ }): Promise<readonly MigrationSpaceListEntry[]> {
97
+ const { projectMigrationsDir } = args;
98
+ const candidateDirs = await listContractSpaceDirectories(projectMigrationsDir);
99
+ const spaceIds = candidateDirs
100
+ .filter((name) => !RESERVED_SPACE_SUBDIR_NAMES.has(name))
101
+ .filter(isValidSpaceId)
102
+ .sort(compareSpaceIds);
103
+
104
+ const spaces: MigrationSpaceListEntry[] = [];
105
+ for (const spaceId of spaceIds) {
106
+ const spaceDir = spaceMigrationDirectory(projectMigrationsDir, spaceId);
107
+ const packages = await readMigrationsDir(spaceDir);
108
+ const refsByHash = await resolveRefsByContractHash(spaceRefsDirectory(spaceDir));
109
+
110
+ const migrations: MigrationListEntry[] = packages
111
+ .map((pkg) => ({
112
+ dirName: pkg.dirName,
113
+ from: pkg.metadata.from,
114
+ to: pkg.metadata.to,
115
+ migrationHash: pkg.metadata.migrationHash,
116
+ operationCount: pkg.ops.length,
117
+ createdAt: pkg.metadata.createdAt,
118
+ refs: refsByHash.get(pkg.metadata.to) ?? [],
119
+ providedInvariants: pkg.metadata.providedInvariants,
120
+ }))
121
+ .sort(compareDirNamesDescending);
122
+
123
+ spaces.push({ spaceId, migrations });
124
+ }
125
+
126
+ return spaces;
127
+ }
@@ -0,0 +1,4 @@
1
+ export {
2
+ enumerateMigrationSpaces,
3
+ resolveRefsByContractHash,
4
+ } from '../enumerate-migration-spaces';
@@ -0,0 +1,5 @@
1
+ export type {
2
+ MigrationListEntry,
3
+ MigrationListResult,
4
+ MigrationSpaceListEntry,
5
+ } from '../migration-list-types';
@@ -31,7 +31,10 @@ export {
31
31
  APP_SPACE_ID,
32
32
  assertValidSpaceId,
33
33
  isValidSpaceId,
34
+ RESERVED_SPACE_SUBDIR_NAMES,
35
+ SPACE_REFS_DIRNAME,
34
36
  spaceMigrationDirectory,
37
+ spaceRefsDirectory,
35
38
  type ValidSpaceId,
36
39
  } from '../space-layout';
37
40
  export {
@@ -0,0 +1,21 @@
1
+ export interface MigrationListEntry {
2
+ readonly dirName: string;
3
+ readonly from: string | null;
4
+ readonly to: string;
5
+ readonly migrationHash: string;
6
+ readonly operationCount: number;
7
+ readonly createdAt: string;
8
+ readonly refs: readonly string[];
9
+ readonly providedInvariants: readonly string[];
10
+ }
11
+
12
+ export interface MigrationSpaceListEntry {
13
+ readonly spaceId: string;
14
+ readonly migrations: readonly MigrationListEntry[];
15
+ }
16
+
17
+ export interface MigrationListResult {
18
+ readonly ok: true;
19
+ readonly spaces: readonly MigrationSpaceListEntry[];
20
+ readonly summary: string;
21
+ }
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import type { ContractSpaceHeadRef } from '@prisma-next/framework-components/control';
3
3
  import { join } from 'pathe';
4
4
  import { errorInvalidJson, errorInvalidRefFile } from './errors';
5
- import { assertValidSpaceId } from './space-layout';
5
+ import { assertValidSpaceId, spaceMigrationDirectory, spaceRefsDirectory } from './space-layout';
6
6
 
7
7
  export type { ContractSpaceHeadRef };
8
8
 
@@ -29,7 +29,10 @@ export async function readContractSpaceHeadRef(
29
29
  ): Promise<ContractSpaceHeadRef | null> {
30
30
  assertValidSpaceId(spaceId);
31
31
 
32
- const filePath = join(projectMigrationsDir, spaceId, 'refs', 'head.json');
32
+ const filePath = join(
33
+ spaceRefsDirectory(spaceMigrationDirectory(projectMigrationsDir, spaceId)),
34
+ 'head.json',
35
+ );
33
36
 
34
37
  let raw: string;
35
38
  try {
@@ -46,3 +46,33 @@ export function spaceMigrationDirectory(projectMigrationsDir: string, spaceId: s
46
46
  assertValidSpaceId(spaceId);
47
47
  return join(projectMigrationsDir, spaceId);
48
48
  }
49
+
50
+ /**
51
+ * Per-space subdirectory name reserved for the ref store
52
+ * (`migrations/<space>/<SPACE_REFS_DIRNAME>/*.json`). Single source of
53
+ * truth: every helper that composes a per-space refs path imports this
54
+ * constant, and the enumerator uses it (via
55
+ * {@link RESERVED_SPACE_SUBDIR_NAMES}) to exclude reserved names from
56
+ * the contract-space candidate list.
57
+ */
58
+ export const SPACE_REFS_DIRNAME = 'refs';
59
+
60
+ /**
61
+ * Names reserved as per-space subdirectories of `migrations/<space>/`.
62
+ * Used by the enumerator to filter contract-space candidates so a
63
+ * reserved name (e.g. a top-level `migrations/refs/` left in the wrong
64
+ * place) is never enumerated as a phantom contract space. Currently
65
+ * holds `SPACE_REFS_DIRNAME`; extend if future per-space layouts add
66
+ * more reserved subdirectories.
67
+ */
68
+ export const RESERVED_SPACE_SUBDIR_NAMES: ReadonlySet<string> = new Set([SPACE_REFS_DIRNAME]);
69
+
70
+ /**
71
+ * Resolve the per-space refs directory for `spaceMigrationsDir`
72
+ * (typically the value returned by {@link spaceMigrationDirectory}).
73
+ * Composes the canonical {@link SPACE_REFS_DIRNAME} so callers do not
74
+ * hard-code the literal.
75
+ */
76
+ export function spaceRefsDirectory(spaceMigrationsDir: string): string {
77
+ return join(spaceMigrationsDir, SPACE_REFS_DIRNAME);
78
+ }
@@ -1 +0,0 @@
1
- {"version":3,"file":"read-contract-space-contract-Cglige7P.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","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 } 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(projectMigrationsDir, spaceId, 'refs', 'head.json');\n\n let raw: string;\n try {\n raw = await readFile(filePath, 'utf-8');\n } catch (error) {\n if (hasErrnoCode(error, 'ENOENT')) {\n return null;\n }\n throw error;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));\n }\n\n if (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 members;\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,e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