@prisma-next/migration-tools 0.11.0-dev.3 → 0.11.0-dev.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{errors-DGYwcwXs.mjs → errors-CoEN114u.mjs} +14 -2
- package/dist/errors-CoEN114u.mjs.map +1 -0
- package/dist/exports/aggregate.d.mts +4 -4
- package/dist/exports/aggregate.d.mts.map +1 -1
- package/dist/exports/aggregate.mjs +5 -4
- package/dist/exports/aggregate.mjs.map +1 -1
- package/dist/exports/enumerate-migration-spaces.d.mts +53 -0
- package/dist/exports/enumerate-migration-spaces.d.mts.map +1 -0
- package/dist/exports/enumerate-migration-spaces.mjs +107 -0
- package/dist/exports/enumerate-migration-spaces.mjs.map +1 -0
- package/dist/exports/errors.d.mts.map +1 -1
- package/dist/exports/errors.mjs +1 -1
- package/dist/exports/graph.d.mts +1 -1
- package/dist/exports/hash.d.mts +2 -2
- package/dist/exports/hash.d.mts.map +1 -1
- package/dist/exports/invariants.d.mts +1 -1
- package/dist/exports/invariants.d.mts.map +1 -1
- package/dist/exports/invariants.mjs +1 -1
- package/dist/exports/io.d.mts +1 -1
- package/dist/exports/io.d.mts.map +1 -1
- package/dist/exports/io.mjs +1 -1
- package/dist/exports/metadata.d.mts +1 -1
- package/dist/exports/migration-graph.d.mts +9 -2
- package/dist/exports/migration-graph.d.mts.map +1 -0
- package/dist/exports/migration-graph.mjs +16 -2
- package/dist/exports/migration-graph.mjs.map +1 -0
- package/dist/exports/migration-list-types.d.mts +2 -0
- package/dist/exports/migration-list-types.mjs +1 -0
- package/dist/exports/migration-ts.d.mts.map +1 -1
- package/dist/exports/migration-ts.mjs.map +1 -1
- package/dist/exports/migration.d.mts +1 -1
- package/dist/exports/migration.d.mts.map +1 -1
- package/dist/exports/migration.mjs +2 -2
- package/dist/exports/migration.mjs.map +1 -1
- package/dist/exports/package.d.mts +1 -1
- package/dist/exports/ref-resolution.d.mts +2 -2
- package/dist/exports/ref-resolution.d.mts.map +1 -1
- package/dist/exports/ref-resolution.mjs +1 -1
- package/dist/exports/ref-resolution.mjs.map +1 -1
- package/dist/exports/refs.d.mts +15 -2
- package/dist/exports/refs.d.mts.map +1 -0
- package/dist/exports/refs.mjs +137 -2
- package/dist/exports/refs.mjs.map +1 -0
- package/dist/exports/spaces.d.mts +27 -2
- package/dist/exports/spaces.d.mts.map +1 -1
- package/dist/exports/spaces.mjs +9 -7
- package/dist/exports/spaces.mjs.map +1 -1
- package/dist/{graph-BrLXqoUc.d.mts → graph-C7AJPGV5.d.mts} +1 -1
- package/dist/graph-C7AJPGV5.d.mts.map +1 -0
- package/dist/hash-Cr4WIr4Z.mjs.map +1 -1
- package/dist/{invariants-0daYEzyo.mjs → invariants-lbJddL-S.mjs} +2 -2
- package/dist/{invariants-0daYEzyo.mjs.map → invariants-lbJddL-S.mjs.map} +1 -1
- package/dist/{io-BPLfzvZe.mjs → io-gHmDrSjQ.mjs} +3 -3
- package/dist/{io-BPLfzvZe.mjs.map → io-gHmDrSjQ.mjs.map} +1 -1
- package/dist/{migration-graph-De0dUZoC.d.mts → migration-graph-ABYqVsmv.d.mts} +3 -3
- package/dist/migration-graph-ABYqVsmv.d.mts.map +1 -0
- package/dist/{migration-graph-nlS4TRpn.mjs → migration-graph-C2iNX8dk.mjs} +2 -2
- package/dist/{migration-graph-nlS4TRpn.mjs.map → migration-graph-C2iNX8dk.mjs.map} +1 -1
- package/dist/migration-list-types-B-qimPet.d.mts +23 -0
- package/dist/migration-list-types-B-qimPet.d.mts.map +1 -0
- package/dist/op-schema-D5qkXfEf.mjs.map +1 -1
- package/dist/{package-DZj8YvD0.d.mts → package-DIttKL7X.d.mts} +1 -1
- package/dist/package-DIttKL7X.d.mts.map +1 -0
- package/dist/read-contract-space-contract-CwwlqKl_.mjs +82 -0
- package/dist/read-contract-space-contract-CwwlqKl_.mjs.map +1 -0
- package/dist/{refs-CDaNerhT.d.mts → refs-BaygQaFD.d.mts} +1 -1
- package/dist/refs-BaygQaFD.d.mts.map +1 -0
- package/dist/{refs-BDHo5l_g.mjs → refs-HhOkD8BT.mjs} +3 -3
- package/dist/refs-HhOkD8BT.mjs.map +1 -0
- package/dist/{read-contract-space-contract-DRueB4Aa.mjs → verify-contract-spaces-DxXWxGR0.mjs} +32 -80
- package/dist/verify-contract-spaces-DxXWxGR0.mjs.map +1 -0
- package/package.json +14 -6
- package/src/emit-contract-space-artefacts.ts +4 -3
- package/src/enumerate-migration-spaces.ts +127 -0
- package/src/errors.ts +15 -0
- package/src/exports/enumerate-migration-spaces.ts +4 -0
- package/src/exports/migration-graph.ts +1 -0
- package/src/exports/migration-list-types.ts +5 -0
- package/src/exports/refs.ts +8 -0
- package/src/exports/spaces.ts +3 -0
- package/src/graph-membership.ts +17 -0
- package/src/migration-list-types.ts +21 -0
- package/src/read-contract-space-head-ref.ts +5 -2
- package/src/refs/snapshot.ts +197 -0
- package/src/refs.ts +3 -1
- package/src/space-layout.ts +30 -0
- package/dist/errors-DGYwcwXs.mjs.map +0 -1
- package/dist/graph-BrLXqoUc.d.mts.map +0 -1
- package/dist/migration-graph-De0dUZoC.d.mts.map +0 -1
- package/dist/package-DZj8YvD0.d.mts.map +0 -1
- package/dist/read-contract-space-contract-DRueB4Aa.mjs.map +0 -1
- package/dist/refs-BDHo5l_g.mjs.map +0 -1
- package/dist/refs-CDaNerhT.d.mts.map +0 -1
- /package/dist/{metadata-BFX0xdz8.d.mts → metadata-B4Wy6zor.d.mts} +0 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/migration-list-types.d.ts
|
|
2
|
+
interface MigrationListEntry {
|
|
3
|
+
readonly dirName: string;
|
|
4
|
+
readonly from: string | null;
|
|
5
|
+
readonly to: string;
|
|
6
|
+
readonly migrationHash: string;
|
|
7
|
+
readonly operationCount: number;
|
|
8
|
+
readonly createdAt: string;
|
|
9
|
+
readonly refs: readonly string[];
|
|
10
|
+
readonly providedInvariants: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
interface MigrationSpaceListEntry {
|
|
13
|
+
readonly spaceId: string;
|
|
14
|
+
readonly migrations: readonly MigrationListEntry[];
|
|
15
|
+
}
|
|
16
|
+
interface MigrationListResult {
|
|
17
|
+
readonly ok: true;
|
|
18
|
+
readonly spaces: readonly MigrationSpaceListEntry[];
|
|
19
|
+
readonly summary: string;
|
|
20
|
+
}
|
|
21
|
+
//#endregion
|
|
22
|
+
export { MigrationListResult as n, MigrationSpaceListEntry as r, MigrationListEntry as t };
|
|
23
|
+
//# sourceMappingURL=migration-list-types-B-qimPet.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migration-list-types-B-qimPet.d.mts","names":[],"sources":["../src/migration-list-types.ts"],"mappings":";UAAiB,kBAAA;EAAA,SACN,OAAA;EAAA,SACA,IAAA;EAAA,SACA,EAAA;EAAA,SACA,aAAA;EAAA,SACA,cAAA;EAAA,SACA,SAAA;EAAA,SACA,IAAA;EAAA,SACA,kBAAA;AAAA;AAAA,UAGM,uBAAA;EAAA,SACN,OAAA;EAAA,SACA,UAAA,WAAqB,kBAAkB;AAAA;AAAA,UAGjC,mBAAA;EAAA,SACN,EAAA;EAAA,SACA,MAAA,WAAiB,uBAAuB;EAAA,SACxC,OAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"op-schema-D5qkXfEf.mjs","names":[],"sources":["../src/op-schema.ts"],"sourcesContent":["import { type } from 'arktype';\n\nexport const MigrationOpSchema = type({\n id: 'string',\n label: 'string',\n operationClass: \"'additive' | 'widening' | 'destructive' | 'data'\",\n 'invariantId?': 'string',\n});\n\n// Intentionally shallow: operation-specific payload validation is owned by planner/runner layers.\nexport const MigrationOpsSchema = MigrationOpSchema.array();\n"],"mappings":";;AAEA,MAAa,oBAAoB,KAAK;CACpC,IAAI;CACJ,OAAO;CACP,gBAAgB;CAChB,gBAAgB;
|
|
1
|
+
{"version":3,"file":"op-schema-D5qkXfEf.mjs","names":[],"sources":["../src/op-schema.ts"],"sourcesContent":["import { type } from 'arktype';\n\nexport const MigrationOpSchema = type({\n id: 'string',\n label: 'string',\n operationClass: \"'additive' | 'widening' | 'destructive' | 'data'\",\n 'invariantId?': 'string',\n});\n\n// Intentionally shallow: operation-specific payload validation is owned by planner/runner layers.\nexport const MigrationOpsSchema = MigrationOpSchema.array();\n"],"mappings":";;AAEA,MAAa,oBAAoB,KAAK;CACpC,IAAI;CACJ,OAAO;CACP,gBAAgB;CAChB,gBAAgB;AAClB,CAAC;AAGD,MAAa,qBAAqB,kBAAkB,MAAM"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"package-DIttKL7X.d.mts","names":[],"sources":["../src/package.ts"],"mappings":";;;KAKY,YAAA,YAAwB,sBAAsB;;AAA1D;;;;AAA0D;AAa1D;;;;AACkB;UADD,sBAAA,SAA+B,gBAAgB;EAAA,SACrD,OAAO;AAAA"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { b as errorMissingFile, d as errorInvalidJson, m as errorInvalidRefFile } from "./errors-CoEN114u.mjs";
|
|
2
|
+
import { c as spaceMigrationDirectory, l as spaceRefsDirectory, o as assertValidSpaceId } from "./verify-contract-spaces-DxXWxGR0.mjs";
|
|
3
|
+
import { join } from "pathe";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
//#region src/read-contract-space-head-ref.ts
|
|
6
|
+
function hasErrnoCode$1(error, code) {
|
|
7
|
+
return error instanceof Error && error.code === code;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Read the head ref (`hash` + `invariants`) for a contract space from
|
|
11
|
+
* `<projectMigrationsDir>/<spaceId>/refs/head.json`.
|
|
12
|
+
*
|
|
13
|
+
* Returns `null` when the file does not exist (first emit). Surfaces
|
|
14
|
+
* `MIGRATION.INVALID_JSON` / `MIGRATION.INVALID_REF_FILE` on a corrupt
|
|
15
|
+
* `refs/head.json` so callers can distinguish "no head ref on disk"
|
|
16
|
+
* (returns `null`) from "head ref present but unreadable" (throws).
|
|
17
|
+
*
|
|
18
|
+
* Validates the space id against `[a-z][a-z0-9_-]{0,63}` for the same
|
|
19
|
+
* filesystem-safety reasons as the rest of the per-space helpers. The
|
|
20
|
+
* helper is uniform across the app and extension spaces.
|
|
21
|
+
*/
|
|
22
|
+
async function readContractSpaceHeadRef(projectMigrationsDir, spaceId) {
|
|
23
|
+
assertValidSpaceId(spaceId);
|
|
24
|
+
const filePath = join(spaceRefsDirectory(spaceMigrationDirectory(projectMigrationsDir, spaceId)), "head.json");
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = await readFile(filePath, "utf-8");
|
|
28
|
+
} catch (error) {
|
|
29
|
+
if (hasErrnoCode$1(error, "ENOENT")) return null;
|
|
30
|
+
throw error;
|
|
31
|
+
}
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(raw);
|
|
35
|
+
} catch (e) {
|
|
36
|
+
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
|
|
37
|
+
}
|
|
38
|
+
if (typeof parsed !== "object" || parsed === null) throw errorInvalidRefFile(filePath, "expected an object");
|
|
39
|
+
const obj = parsed;
|
|
40
|
+
if (typeof obj.hash !== "string") throw errorInvalidRefFile(filePath, "expected an object with a string `hash` field");
|
|
41
|
+
if (!Array.isArray(obj.invariants) || obj.invariants.some((value) => typeof value !== "string")) throw errorInvalidRefFile(filePath, "expected an object with an `invariants` array of strings");
|
|
42
|
+
return {
|
|
43
|
+
hash: obj.hash,
|
|
44
|
+
invariants: obj.invariants
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/read-contract-space-contract.ts
|
|
49
|
+
function hasErrnoCode(error, code) {
|
|
50
|
+
return error instanceof Error && error.code === code;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Read the on-disk contract value for a contract space
|
|
54
|
+
* (`<projectMigrationsDir>/<spaceId>/contract.json`). Returns the parsed
|
|
55
|
+
* JSON value as `unknown` — callers that need a typed contract validate
|
|
56
|
+
* via their family's `deserializeContract` to surface schema issues.
|
|
57
|
+
*
|
|
58
|
+
* Companion to {@link import('./read-contract-space-head-ref').readContractSpaceHeadRef}
|
|
59
|
+
* — same ENOENT-throws / corrupt-file-error semantics. Returns the
|
|
60
|
+
* canonical-JSON value the framework wrote during emit, so re-running
|
|
61
|
+
* this helper across machines / runs yields a byte-identical value.
|
|
62
|
+
*/
|
|
63
|
+
async function readContractSpaceContract(projectMigrationsDir, spaceId) {
|
|
64
|
+
assertValidSpaceId(spaceId);
|
|
65
|
+
const filePath = join(projectMigrationsDir, spaceId, "contract.json");
|
|
66
|
+
let raw;
|
|
67
|
+
try {
|
|
68
|
+
raw = await readFile(filePath, "utf-8");
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile("contract.json", join(projectMigrationsDir, spaceId));
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
return JSON.parse(raw);
|
|
75
|
+
} catch (e) {
|
|
76
|
+
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
export { readContractSpaceHeadRef as n, readContractSpaceContract as t };
|
|
81
|
+
|
|
82
|
+
//# sourceMappingURL=read-contract-space-contract-CwwlqKl_.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read-contract-space-contract-CwwlqKl_.mjs","names":["hasErrnoCode"],"sources":["../src/read-contract-space-head-ref.ts","../src/read-contract-space-contract.ts"],"sourcesContent":["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 { 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":";;;;;AAQA,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,WAAW,YAAY,WAAW,MAC3C,MAAM,oBAAoB,UAAU,oBAAoB;CAE1D,MAAM,MAAM;CACZ,IAAI,OAAO,IAAI,SAAS,UACtB,MAAM,oBAAoB,UAAU,+CAA+C;CAErF,IAAI,CAAC,MAAM,QAAQ,IAAI,UAAU,KAAK,IAAI,WAAW,MAAM,UAAU,OAAO,UAAU,QAAQ,GAC5F,MAAM,oBAAoB,UAAU,0DAA0D;CAGhG,OAAO;EAAE,MAAM,IAAI;EAAM,YAAY,IAAI;CAAgC;AAC3E;;;AC5DA,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"}
|
|
@@ -13,4 +13,4 @@ declare function deleteRef(refsDir: string, name: string): Promise<void>;
|
|
|
13
13
|
declare function resolveRef(refs: Refs, name: string): RefEntry;
|
|
14
14
|
//#endregion
|
|
15
15
|
export { readRefs as a, validateRefValue as c, readRef as i, writeRef as l, Refs as n, resolveRef as o, deleteRef as r, validateRefName as s, RefEntry as t };
|
|
16
|
-
//# sourceMappingURL=refs-
|
|
16
|
+
//# sourceMappingURL=refs-BaygQaFD.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refs-BaygQaFD.d.mts","names":[],"sources":["../src/refs.ts"],"mappings":";UAUiB,QAAA;EAAA,SACN,IAAA;EAAA,SACA,UAAU;AAAA;AAAA,KAGT,IAAA,GAAO,QAAA,CAAS,MAAA,SAAe,QAAA;AAAA,iBAK3B,eAAA,CAAgB,IAAY;AAAA,iBAQ5B,gBAAA,CAAiB,KAAa;AAAA,iBAsBxB,OAAA,CAAQ,OAAA,UAAiB,IAAA,WAAe,OAAO,CAAC,QAAA;AAAA,iBAmChD,QAAA,CAAS,OAAA,WAAkB,OAAO,CAAC,IAAA;AAAA,iBAqDnC,QAAA,CAAS,OAAA,UAAiB,IAAA,UAAc,KAAA,EAAO,QAAA,GAAW,OAAO;AAAA,iBAoBjE,SAAA,CAAU,OAAA,UAAiB,IAAA,WAAe,OAAO;AAAA,iBAsCvD,UAAA,CAAW,IAAA,EAAM,IAAA,EAAM,IAAA,WAAe,QAAQ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { g as errorInvalidRefValue, h as errorInvalidRefName, m as errorInvalidRefFile, t as MigrationToolsError } from "./errors-CoEN114u.mjs";
|
|
2
2
|
import { dirname, join, relative } from "pathe";
|
|
3
3
|
import { mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
4
4
|
import { type } from "arktype";
|
|
@@ -66,7 +66,7 @@ async function readRefs(refsDir) {
|
|
|
66
66
|
if (error instanceof Error && error.code === "ENOENT") return {};
|
|
67
67
|
throw error;
|
|
68
68
|
}
|
|
69
|
-
const jsonFiles = entries.filter((entry) => entry.endsWith(".json"));
|
|
69
|
+
const jsonFiles = entries.filter((entry) => entry.endsWith(".json") && !entry.endsWith(".contract.json"));
|
|
70
70
|
const refs = {};
|
|
71
71
|
for (const jsonFile of jsonFiles) {
|
|
72
72
|
const filePath = join(refsDir, jsonFile);
|
|
@@ -145,4 +145,4 @@ function resolveRef(refs, name) {
|
|
|
145
145
|
//#endregion
|
|
146
146
|
export { validateRefName as a, resolveRef as i, readRef as n, validateRefValue as o, readRefs as r, writeRef as s, deleteRef as t };
|
|
147
147
|
|
|
148
|
-
//# sourceMappingURL=refs-
|
|
148
|
+
//# sourceMappingURL=refs-HhOkD8BT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refs-HhOkD8BT.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\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\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\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":";;;;;AAiBA,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,EAAE,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,EAAE,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,UACl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F,MAAM;CACR;AAEJ;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,EAAE,KAAK,IAAI,KAAK,SAAS,2CAA2C,KAAK;EACjH,SAAS;GAAE,SAAS;GAAM,eAAe,OAAO,KAAK,IAAI;EAAE;CAC7D,CAAC;CAIH,OAAO,KAAK;AACd"}
|
package/dist/{read-contract-space-contract-DRueB4Aa.mjs → verify-contract-spaces-DxXWxGR0.mjs}
RENAMED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as MANIFEST_FILE } from "./io-
|
|
1
|
+
import { v as errorInvalidSpaceId } from "./errors-CoEN114u.mjs";
|
|
2
|
+
import { t as MANIFEST_FILE } from "./io-gHmDrSjQ.mjs";
|
|
3
3
|
import { join } from "pathe";
|
|
4
|
-
import {
|
|
4
|
+
import { readdir, stat } from "node:fs/promises";
|
|
5
5
|
import { APP_SPACE_ID } from "@prisma-next/framework-components/control";
|
|
6
6
|
//#region src/space-layout.ts
|
|
7
7
|
/**
|
|
@@ -32,52 +32,36 @@ function spaceMigrationDirectory(projectMigrationsDir, spaceId) {
|
|
|
32
32
|
assertValidSpaceId(spaceId);
|
|
33
33
|
return join(projectMigrationsDir, spaceId);
|
|
34
34
|
}
|
|
35
|
-
//#endregion
|
|
36
|
-
//#region src/read-contract-space-head-ref.ts
|
|
37
|
-
function hasErrnoCode$2(error, code) {
|
|
38
|
-
return error instanceof Error && error.code === code;
|
|
39
|
-
}
|
|
40
35
|
/**
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
* (returns `null`) from "head ref present but unreadable" (throws).
|
|
48
|
-
*
|
|
49
|
-
* Validates the space id against `[a-z][a-z0-9_-]{0,63}` for the same
|
|
50
|
-
* filesystem-safety reasons as the rest of the per-space helpers. The
|
|
51
|
-
* helper is uniform across the app and extension spaces.
|
|
36
|
+
* Per-space subdirectory name reserved for the ref store
|
|
37
|
+
* (`migrations/<space>/<SPACE_REFS_DIRNAME>/*.json`). Single source of
|
|
38
|
+
* truth: every helper that composes a per-space refs path imports this
|
|
39
|
+
* constant, and the enumerator uses it (via
|
|
40
|
+
* {@link RESERVED_SPACE_SUBDIR_NAMES}) to exclude reserved names from
|
|
41
|
+
* the contract-space candidate list.
|
|
52
42
|
*/
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (typeof obj.hash !== "string") throw errorInvalidRefFile(filePath, "expected an object with a string `hash` field");
|
|
72
|
-
if (!Array.isArray(obj.invariants) || obj.invariants.some((value) => typeof value !== "string")) throw errorInvalidRefFile(filePath, "expected an object with an `invariants` array of strings");
|
|
73
|
-
return {
|
|
74
|
-
hash: obj.hash,
|
|
75
|
-
invariants: obj.invariants
|
|
76
|
-
};
|
|
43
|
+
const SPACE_REFS_DIRNAME = "refs";
|
|
44
|
+
/**
|
|
45
|
+
* Names reserved as per-space subdirectories of `migrations/<space>/`.
|
|
46
|
+
* Used by the enumerator to filter contract-space candidates so a
|
|
47
|
+
* reserved name (e.g. a top-level `migrations/refs/` left in the wrong
|
|
48
|
+
* place) is never enumerated as a phantom contract space. Currently
|
|
49
|
+
* holds `SPACE_REFS_DIRNAME`; extend if future per-space layouts add
|
|
50
|
+
* more reserved subdirectories.
|
|
51
|
+
*/
|
|
52
|
+
const RESERVED_SPACE_SUBDIR_NAMES = new Set([SPACE_REFS_DIRNAME]);
|
|
53
|
+
/**
|
|
54
|
+
* Resolve the per-space refs directory for `spaceMigrationsDir`
|
|
55
|
+
* (typically the value returned by {@link spaceMigrationDirectory}).
|
|
56
|
+
* Composes the canonical {@link SPACE_REFS_DIRNAME} so callers do not
|
|
57
|
+
* hard-code the literal.
|
|
58
|
+
*/
|
|
59
|
+
function spaceRefsDirectory(spaceMigrationsDir) {
|
|
60
|
+
return join(spaceMigrationsDir, SPACE_REFS_DIRNAME);
|
|
77
61
|
}
|
|
78
62
|
//#endregion
|
|
79
63
|
//#region src/verify-contract-spaces.ts
|
|
80
|
-
function hasErrnoCode
|
|
64
|
+
function hasErrnoCode(error, code) {
|
|
81
65
|
return error instanceof Error && error.code === code;
|
|
82
66
|
}
|
|
83
67
|
/**
|
|
@@ -104,7 +88,7 @@ async function listContractSpaceDirectories(projectMigrationsDir) {
|
|
|
104
88
|
isDirectory: d.isDirectory()
|
|
105
89
|
}));
|
|
106
90
|
} catch (error) {
|
|
107
|
-
if (hasErrnoCode
|
|
91
|
+
if (hasErrnoCode(error, "ENOENT")) return [];
|
|
108
92
|
throw error;
|
|
109
93
|
}
|
|
110
94
|
const namedCandidates = entries.filter((e) => e.isDirectory).map((e) => e.name).filter((name) => !name.startsWith(".")).sort();
|
|
@@ -116,7 +100,7 @@ async function listContractSpaceDirectories(projectMigrationsDir) {
|
|
|
116
100
|
isMigrationDir: true
|
|
117
101
|
};
|
|
118
102
|
} catch (error) {
|
|
119
|
-
if (hasErrnoCode
|
|
103
|
+
if (hasErrnoCode(error, "ENOENT")) return {
|
|
120
104
|
name,
|
|
121
105
|
isMigrationDir: false
|
|
122
106
|
};
|
|
@@ -222,38 +206,6 @@ function verifyContractSpaces(inputs) {
|
|
|
222
206
|
};
|
|
223
207
|
}
|
|
224
208
|
//#endregion
|
|
225
|
-
|
|
226
|
-
function hasErrnoCode(error, code) {
|
|
227
|
-
return error instanceof Error && error.code === code;
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Read the on-disk contract value for a contract space
|
|
231
|
-
* (`<projectMigrationsDir>/<spaceId>/contract.json`). Returns the parsed
|
|
232
|
-
* JSON value as `unknown` — callers that need a typed contract validate
|
|
233
|
-
* via their family's `deserializeContract` to surface schema issues.
|
|
234
|
-
*
|
|
235
|
-
* Companion to {@link import('./read-contract-space-head-ref').readContractSpaceHeadRef}
|
|
236
|
-
* — same ENOENT-throws / corrupt-file-error semantics. Returns the
|
|
237
|
-
* canonical-JSON value the framework wrote during emit, so re-running
|
|
238
|
-
* this helper across machines / runs yields a byte-identical value.
|
|
239
|
-
*/
|
|
240
|
-
async function readContractSpaceContract(projectMigrationsDir, spaceId) {
|
|
241
|
-
assertValidSpaceId(spaceId);
|
|
242
|
-
const filePath = join(projectMigrationsDir, spaceId, "contract.json");
|
|
243
|
-
let raw;
|
|
244
|
-
try {
|
|
245
|
-
raw = await readFile(filePath, "utf-8");
|
|
246
|
-
} catch (error) {
|
|
247
|
-
if (hasErrnoCode(error, "ENOENT")) throw errorMissingFile("contract.json", join(projectMigrationsDir, spaceId));
|
|
248
|
-
throw error;
|
|
249
|
-
}
|
|
250
|
-
try {
|
|
251
|
-
return JSON.parse(raw);
|
|
252
|
-
} catch (e) {
|
|
253
|
-
throw errorInvalidJson(filePath, e instanceof Error ? e.message : String(e));
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
//#endregion
|
|
257
|
-
export { APP_SPACE_ID as a, spaceMigrationDirectory as c, readContractSpaceHeadRef as i, listContractSpaceDirectories as n, assertValidSpaceId as o, verifyContractSpaces as r, isValidSpaceId as s, readContractSpaceContract as t };
|
|
209
|
+
export { SPACE_REFS_DIRNAME as a, spaceMigrationDirectory as c, RESERVED_SPACE_SUBDIR_NAMES as i, spaceRefsDirectory as l, verifyContractSpaces as n, assertValidSpaceId as o, APP_SPACE_ID as r, isValidSpaceId as s, listContractSpaceDirectories as t };
|
|
258
210
|
|
|
259
|
-
//# sourceMappingURL=
|
|
211
|
+
//# sourceMappingURL=verify-contract-spaces-DxXWxGR0.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"verify-contract-spaces-DxXWxGR0.mjs","names":[],"sources":["../src/space-layout.ts","../src/verify-contract-spaces.ts"],"sourcesContent":["import { APP_SPACE_ID } from '@prisma-next/framework-components/control';\nimport { join } from 'pathe';\nimport { errorInvalidSpaceId } from './errors';\n\nexport { APP_SPACE_ID };\n\n/**\n * Branded string carrying a compile-time guarantee that the value has\n * been validated by {@link assertValidSpaceId}. Downstream filesystem\n * helpers (e.g. {@link spaceMigrationDirectory}) accept this type to\n * make \"validated\" tracking visible at the type level rather than\n * relying purely on a runtime check.\n */\nexport type ValidSpaceId = string & { readonly __brand: 'ValidSpaceId' };\n\n/**\n * Pattern a contract-space identifier must match. The constraint is\n * filesystem-friendly: lowercase letters / digits / hyphen / underscore,\n * starts with a letter, max 64 characters.\n */\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 { 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"],"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;;;;;;;;;AAUA,MAAa,qBAAqB;;;;;;;;;AAUlC,MAAa,8BAAmD,IAAI,IAAI,CAAC,kBAAkB,CAAC;;;;;;;AAQ5F,SAAgB,mBAAmB,oBAAoC;CACrE,OAAO,KAAK,oBAAoB,kBAAkB;AACpD;;;ACxEA,SAAS,aAAa,OAAgB,MAAuB;CAC3D,OAAO,iBAAiB,SAAU,MAA4B,SAAS;AACzE;;;;;;;;;;;;;;;;;AAkBA,eAAsB,6BACpB,sBAC4B;CAC5B,IAAI;CACJ,IAAI;E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EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,IAAI,EAAE,UAAU,EAAE,SAAS,OAAO;EAClC,OAAO;CACT,CAAC;CAED,OAAO;EAAE,IAAI;EAAO;CAAW;AACjC"}
|
package/package.json
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma-next/migration-tools",
|
|
3
|
-
"version": "0.11.0-dev.
|
|
3
|
+
"version": "0.11.0-dev.30",
|
|
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.
|
|
10
|
-
"@prisma-next/framework-components": "0.11.0-dev.
|
|
11
|
-
"@prisma-next/utils": "0.11.0-dev.
|
|
9
|
+
"@prisma-next/contract": "0.11.0-dev.30",
|
|
10
|
+
"@prisma-next/framework-components": "0.11.0-dev.30",
|
|
11
|
+
"@prisma-next/utils": "0.11.0-dev.30",
|
|
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.
|
|
18
|
-
"@prisma-next/tsdown": "0.11.0-dev.
|
|
17
|
+
"@prisma-next/tsconfig": "0.11.0-dev.30",
|
|
18
|
+
"@prisma-next/tsdown": "0.11.0-dev.30",
|
|
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
|
-
|
|
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(
|
|
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
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ifDefined } from '@prisma-next/utils/defined';
|
|
2
2
|
import { basename, dirname, relative } from 'pathe';
|
|
3
|
+
import type { MigrationGraph } from './graph';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Build the canonical "re-emit this package" remediation hint.
|
|
@@ -399,3 +400,17 @@ export function errorMigrationHashMismatch(
|
|
|
399
400
|
details: { dir, storedHash, computedHash },
|
|
400
401
|
});
|
|
401
402
|
}
|
|
403
|
+
|
|
404
|
+
export function errorHashNotInGraph(hash: string, graph: MigrationGraph): MigrationToolsError {
|
|
405
|
+
const reachableHashes = [...graph.nodes].sort();
|
|
406
|
+
const reachableList = reachableHashes.length > 0 ? reachableHashes.join(', ') : '(none)';
|
|
407
|
+
return new MigrationToolsError(
|
|
408
|
+
'MIGRATION.HASH_NOT_IN_GRAPH',
|
|
409
|
+
`Hash "${hash}" is not a node in the migration graph`,
|
|
410
|
+
{
|
|
411
|
+
why: `The migration graph contains nodes ${reachableList}; "${hash}" isn't one of them.`,
|
|
412
|
+
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.`,
|
|
413
|
+
details: { hash, reachableHashes },
|
|
414
|
+
},
|
|
415
|
+
);
|
|
416
|
+
}
|