prisma-next 0.12.0-dev.3 → 0.12.0-dev.31

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 (113) hide show
  1. package/dist/cli.mjs +180 -163
  2. package/dist/cli.mjs.map +1 -1
  3. package/dist/{client-KgJorIvG.mjs → client-xeWpMlq1.mjs} +39 -15
  4. package/dist/client-xeWpMlq1.mjs.map +1 -0
  5. package/dist/{command-helpers-Bbw1GbwL.mjs → command-helpers-DK_5ItoJ.mjs} +284 -24
  6. package/dist/command-helpers-DK_5ItoJ.mjs.map +1 -0
  7. package/dist/commands/contract-emit.mjs +1 -1
  8. package/dist/commands/contract-infer.mjs +1 -1
  9. package/dist/commands/db-init.mjs +4 -5
  10. package/dist/commands/db-init.mjs.map +1 -1
  11. package/dist/commands/db-schema.mjs +3 -3
  12. package/dist/commands/db-sign.mjs +4 -4
  13. package/dist/commands/db-update.d.mts.map +1 -1
  14. package/dist/commands/db-update.mjs +10 -7
  15. package/dist/commands/db-update.mjs.map +1 -1
  16. package/dist/commands/db-verify.mjs +1 -1
  17. package/dist/commands/migrate.d.mts +1 -1
  18. package/dist/commands/migrate.mjs +5 -6
  19. package/dist/commands/migrate.mjs.map +1 -1
  20. package/dist/commands/migration-check.mjs +1 -1
  21. package/dist/commands/migration-graph.d.mts +13 -7
  22. package/dist/commands/migration-graph.d.mts.map +1 -1
  23. package/dist/commands/migration-graph.mjs +171 -2
  24. package/dist/commands/migration-graph.mjs.map +1 -0
  25. package/dist/commands/migration-list.d.mts +24 -26
  26. package/dist/commands/migration-list.d.mts.map +1 -1
  27. package/dist/commands/migration-list.mjs +2 -190
  28. package/dist/commands/migration-log.d.mts +6 -18
  29. package/dist/commands/migration-log.d.mts.map +1 -1
  30. package/dist/commands/migration-log.mjs +1 -137
  31. package/dist/commands/migration-new.mjs +3 -3
  32. package/dist/commands/migration-plan.d.mts +1 -1
  33. package/dist/commands/migration-plan.mjs +1 -1
  34. package/dist/commands/migration-show.d.mts +1 -1
  35. package/dist/commands/migration-show.mjs +3 -4
  36. package/dist/commands/migration-show.mjs.map +1 -1
  37. package/dist/commands/migration-status.d.mts +41 -141
  38. package/dist/commands/migration-status.d.mts.map +1 -1
  39. package/dist/commands/migration-status.mjs +2 -759
  40. package/dist/commands/ref.d.mts +1 -1
  41. package/dist/commands/ref.mjs +3 -3
  42. package/dist/commands/telemetry/index.d.mts +7 -0
  43. package/dist/commands/telemetry/index.d.mts.map +1 -0
  44. package/dist/commands/telemetry/index.mjs +2 -0
  45. package/dist/{contract-at-errors-BxP-TOMl.mjs → contract-at-errors-DG3kjgoz.mjs} +2 -2
  46. package/dist/{contract-at-errors-BxP-TOMl.mjs.map → contract-at-errors-DG3kjgoz.mjs.map} +1 -1
  47. package/dist/{contract-emit-D-4jrNve.mjs → contract-emit-BO0l6fnT.mjs} +3 -3
  48. package/dist/{contract-emit-D-4jrNve.mjs.map → contract-emit-BO0l6fnT.mjs.map} +1 -1
  49. package/dist/{contract-emit-DxcGl4Uq.mjs → contract-emit-C0Bs0VRj.mjs} +3 -3
  50. package/dist/{contract-emit-DxcGl4Uq.mjs.map → contract-emit-C0Bs0VRj.mjs.map} +1 -1
  51. package/dist/{contract-infer-D8uEbJuu.mjs → contract-infer-2wtPflGH.mjs} +3 -3
  52. package/dist/{contract-infer-D8uEbJuu.mjs.map → contract-infer-2wtPflGH.mjs.map} +1 -1
  53. package/dist/{contract-space-aggregate-loader-DvZwdkrr.mjs → contract-space-aggregate-loader-Dbr3-jHF.mjs} +4 -4
  54. package/dist/{contract-space-aggregate-loader-DvZwdkrr.mjs.map → contract-space-aggregate-loader-Dbr3-jHF.mjs.map} +1 -1
  55. package/dist/{db-verify-v_vUKXTU.mjs → db-verify-CxHiSiTG.mjs} +4 -4
  56. package/dist/{db-verify-v_vUKXTU.mjs.map → db-verify-CxHiSiTG.mjs.map} +1 -1
  57. package/dist/exports/control-api.d.mts +1 -1
  58. package/dist/exports/control-api.d.mts.map +1 -1
  59. package/dist/exports/control-api.mjs +2 -2
  60. package/dist/exports/index.mjs +1 -1
  61. package/dist/exports/init-output.mjs +1 -1
  62. package/dist/{framework-components-fYXjz_in.mjs → framework-components-CxOVKAAh.mjs} +2 -2
  63. package/dist/{framework-components-fYXjz_in.mjs.map → framework-components-CxOVKAAh.mjs.map} +1 -1
  64. package/dist/{global-flags-DEHjV8_s.d.mts → global-flags-DG4uY5tV.d.mts} +1 -1
  65. package/dist/{global-flags-DEHjV8_s.d.mts.map → global-flags-DG4uY5tV.d.mts.map} +1 -1
  66. package/dist/{init-Cv9UzWL5.mjs → init-R272pxux.mjs} +5 -58
  67. package/dist/init-R272pxux.mjs.map +1 -0
  68. package/dist/{inspect-live-schema-C6ohV_oQ.mjs → inspect-live-schema-RekOwfi5.mjs} +3 -3
  69. package/dist/{inspect-live-schema-C6ohV_oQ.mjs.map → inspect-live-schema-RekOwfi5.mjs.map} +1 -1
  70. package/dist/{migration-check-BiBJoYYW.mjs → migration-check-Dc0cOhKH.mjs} +2 -2
  71. package/dist/{migration-check-BiBJoYYW.mjs.map → migration-check-Dc0cOhKH.mjs.map} +1 -1
  72. package/dist/{migration-command-scaffold-CjvwO6at.mjs → migration-command-scaffold-ApB3NxWY.mjs} +3 -3
  73. package/dist/{migration-command-scaffold-CjvwO6at.mjs.map → migration-command-scaffold-ApB3NxWY.mjs.map} +1 -1
  74. package/dist/migration-graph-space-render-dmLLWift.mjs +1966 -0
  75. package/dist/migration-graph-space-render-dmLLWift.mjs.map +1 -0
  76. package/dist/migration-list-C5sXrl0U.mjs +228 -0
  77. package/dist/migration-list-C5sXrl0U.mjs.map +1 -0
  78. package/dist/migration-list-types-DS63IdFd.d.mts +23 -0
  79. package/dist/migration-list-types-DS63IdFd.d.mts.map +1 -0
  80. package/dist/migration-log-DD_vCbYW.mjs +203 -0
  81. package/dist/migration-log-DD_vCbYW.mjs.map +1 -0
  82. package/dist/{migration-plan-9DJ7q7_z.mjs → migration-plan-CeTjQOIG.mjs} +5 -5
  83. package/dist/{migration-plan-9DJ7q7_z.mjs.map → migration-plan-CeTjQOIG.mjs.map} +1 -1
  84. package/dist/migration-status-qV8ctwPy.mjs +432 -0
  85. package/dist/migration-status-qV8ctwPy.mjs.map +1 -0
  86. package/dist/{output-B60Gw5fu.mjs → output-CF_hqzI-.mjs} +1 -1
  87. package/dist/{output-B60Gw5fu.mjs.map → output-CF_hqzI-.mjs.map} +1 -1
  88. package/dist/{ref-advancement-DUZqsue6.mjs → ref-advancement-V1o-9LVK.mjs} +1 -1
  89. package/dist/{ref-advancement-DUZqsue6.mjs.map → ref-advancement-V1o-9LVK.mjs.map} +1 -1
  90. package/dist/telemetry-S-NGi9U6.mjs +122 -0
  91. package/dist/telemetry-S-NGi9U6.mjs.map +1 -0
  92. package/dist/{types-Dt_SfqFm.d.mts → types-Mh7mdPHM.d.mts} +13 -2
  93. package/dist/types-Mh7mdPHM.d.mts.map +1 -0
  94. package/dist/{verify-DCA9Sldu.mjs → verify-BdI-BgYi.mjs} +2 -2
  95. package/dist/{verify-DCA9Sldu.mjs.map → verify-BdI-BgYi.mjs.map} +1 -1
  96. package/package.json +11 -12
  97. package/dist/client-KgJorIvG.mjs.map +0 -1
  98. package/dist/command-helpers-Bbw1GbwL.mjs.map +0 -1
  99. package/dist/commands/migration-list.mjs.map +0 -1
  100. package/dist/commands/migration-log.mjs.map +0 -1
  101. package/dist/commands/migration-status.mjs.map +0 -1
  102. package/dist/graph-render-rFAqZujX.mjs +0 -1081
  103. package/dist/graph-render-rFAqZujX.mjs.map +0 -1
  104. package/dist/init-Cv9UzWL5.mjs.map +0 -1
  105. package/dist/migration-graph-D7DVUElV.mjs +0 -1232
  106. package/dist/migration-graph-D7DVUElV.mjs.map +0 -1
  107. package/dist/migration-list-styler-BRwF4-gy.mjs +0 -399
  108. package/dist/migration-list-styler-BRwF4-gy.mjs.map +0 -1
  109. package/dist/migration-types-D2FW63pr.d.mts +0 -15
  110. package/dist/migration-types-D2FW63pr.d.mts.map +0 -1
  111. package/dist/migrations-Cv2jxNNK.mjs +0 -228
  112. package/dist/migrations-Cv2jxNNK.mjs.map +0 -1
  113. package/dist/types-Dt_SfqFm.d.mts.map +0 -1
@@ -0,0 +1,1966 @@
1
+ import { bold, createColors, cyan, cyanBright, dim, green, yellow } from "colorette";
2
+ import stringWidth from "string-width";
3
+ import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
4
+ //#region src/utils/formatters/migration-graph-layout.ts
5
+ function forwardEdges(edges) {
6
+ return edges.filter((e) => e.kind === "forward");
7
+ }
8
+ function buildForwardProducersByTo(edges) {
9
+ const byTo = /* @__PURE__ */ new Map();
10
+ for (const edge of edges) {
11
+ if (edge.kind !== "forward") continue;
12
+ const bucket = byTo.get(edge.to);
13
+ if (bucket) bucket.push(edge);
14
+ else byTo.set(edge.to, [edge]);
15
+ }
16
+ return byTo;
17
+ }
18
+ function buildForwardOutDegree(edges) {
19
+ const out = /* @__PURE__ */ new Map();
20
+ for (const edge of edges) {
21
+ if (edge.kind !== "forward" || edge.from === edge.to) continue;
22
+ out.set(edge.from, (out.get(edge.from) ?? 0) + 1);
23
+ }
24
+ return out;
25
+ }
26
+ function buildForwardInDegree(edges) {
27
+ const indeg = /* @__PURE__ */ new Map();
28
+ for (const edge of forwardEdges(edges)) {
29
+ if (edge.from === edge.to) continue;
30
+ indeg.set(edge.to, (indeg.get(edge.to) ?? 0) + 1);
31
+ }
32
+ return indeg;
33
+ }
34
+ /**
35
+ * Distinct source contracts among a contract's forward producers. A contract is
36
+ * a *convergence* when this count is >= 2. Multiple migrations sharing one
37
+ * source (a multi-edge) count once — they stack in a single lane rather than
38
+ * fanning into a convergence.
39
+ */
40
+ function buildDistinctSourceCountByTo(edges) {
41
+ const sources = /* @__PURE__ */ new Map();
42
+ for (const edge of edges) {
43
+ if (edge.kind !== "forward" || edge.from === edge.to) continue;
44
+ const set = sources.get(edge.to);
45
+ if (set) set.add(edge.from);
46
+ else sources.set(edge.to, new Set([edge.from]));
47
+ }
48
+ const counts = /* @__PURE__ */ new Map();
49
+ for (const [to, set] of sources) counts.set(to, set.size);
50
+ return counts;
51
+ }
52
+ function splitComponents(nodes) {
53
+ const components = [];
54
+ let current = [];
55
+ for (const node of nodes) {
56
+ if (node === null) {
57
+ if (current.length > 0) {
58
+ components.push(current);
59
+ current = [];
60
+ }
61
+ continue;
62
+ }
63
+ current.push(node);
64
+ }
65
+ if (current.length > 0) components.push(current);
66
+ return components;
67
+ }
68
+ function classifyForwardShortConvergenceAdjacency(rows, edgeRowIndex, edge, laneIndex) {
69
+ for (let index = edgeRowIndex + 1; index < rows.length; index++) {
70
+ const row = rows[index];
71
+ if (row === void 0) break;
72
+ if (row.kind === "component-separator" || row.kind === "branch-connector") continue;
73
+ if (row.kind === "merge-connector") continue;
74
+ if (row.kind === "edge") {
75
+ if (row.laneIndex === laneIndex) return "node-skipping-forward";
76
+ continue;
77
+ }
78
+ if (row.kind === "node" && row.contractHash === edge.from) return "adjacent";
79
+ }
80
+ return "node-skipping-forward";
81
+ }
82
+ function convergenceProducerUsesShortAdjacency(edge, laneIndex, forwardProducersByTo, producerLaneByHash) {
83
+ const producers = (forwardProducersByTo.get(edge.to) ?? []).filter((candidate) => candidate.kind === "forward");
84
+ if (producers.length < 2) return false;
85
+ const fanStart = [...new Set(producers.map((producer) => producerLaneByHash.get(producer.migrationHash)).filter((candidate) => candidate !== void 0))].sort((a, b) => a - b)[0];
86
+ if (fanStart === void 0) return false;
87
+ return laneIndex === fanStart;
88
+ }
89
+ function classifyForwardLayoutAdjacency(rows, edgeRowIndex, edge, laneIndex, passThroughLanes, nodeColumn, convergenceProducer, divergenceBranchEdge) {
90
+ let sawObstruction = false;
91
+ const passThroughLaneSet = new Set(passThroughLanes);
92
+ for (let index = edgeRowIndex + 1; index < rows.length; index++) {
93
+ const row = rows[index];
94
+ if (row === void 0) break;
95
+ if (row.kind === "component-separator") continue;
96
+ if (row.kind === "merge-connector") {
97
+ if (convergenceProducer) {
98
+ if (row.contractHash === edge.from) sawObstruction = true;
99
+ } else if (!divergenceBranchEdge && row.contractHash !== edge.from) sawObstruction = true;
100
+ continue;
101
+ }
102
+ if (row.kind === "branch-connector") continue;
103
+ if (row.kind === "edge") {
104
+ if (row.laneIndex === laneIndex) return "node-skipping-forward";
105
+ if (!divergenceBranchEdge && row.edge !== void 0 && row.edge.to !== edge.to) sawObstruction = true;
106
+ continue;
107
+ }
108
+ if (row.kind === "node" && row.contractHash !== void 0) {
109
+ if (row.contractHash === edge.from) return sawObstruction ? "node-skipping-forward" : "adjacent";
110
+ const nodeCol = nodeColumn.get(row.contractHash) ?? 0;
111
+ if (!divergenceBranchEdge && !passThroughLaneSet.has(nodeCol)) sawObstruction = true;
112
+ }
113
+ }
114
+ return "node-skipping-forward";
115
+ }
116
+ function classifyLayoutAdjacency(rows, edgeRowIndex, edge, laneIndex, passThroughLanes, nodeColumn, position, forwardInDegree, convergenceProducer, divergenceBranchEdge) {
117
+ if (edge.kind === "self") return "adjacent";
118
+ const fromPos = position.get(edge.from);
119
+ const toPos = position.get(edge.to);
120
+ if (edge.kind === "forward") {
121
+ if ((forwardInDegree.get(edge.to) ?? 0) <= 1 && fromPos !== void 0 && toPos !== void 0 && fromPos === toPos + 1) return "adjacent";
122
+ return classifyForwardLayoutAdjacency(rows, edgeRowIndex, edge, laneIndex, passThroughLanes, nodeColumn, convergenceProducer, divergenceBranchEdge);
123
+ }
124
+ if (fromPos !== void 0 && toPos !== void 0 && toPos === fromPos + 1) return "adjacent";
125
+ for (let index = edgeRowIndex + 1; index < rows.length; index++) {
126
+ const row = rows[index];
127
+ if (row === void 0) break;
128
+ if (row.kind === "component-separator" || row.kind === "branch-connector" || row.kind === "merge-connector") continue;
129
+ if (row.kind === "edge") continue;
130
+ if (row.kind === "node") return row.contractHash === edge.to ? "adjacent" : "node-skipping-rollback";
131
+ }
132
+ return "node-skipping-rollback";
133
+ }
134
+ function refineAdjacency(rows, nodeColumn, position, forwardInDegree, forwardOutDegree, edges, producerLaneByHash) {
135
+ const forwardProducersByTo = buildForwardProducersByTo(edges);
136
+ function branchLaneForEdge(producer) {
137
+ const children = edges.filter((edge) => edge.from === producer.from && edge.kind === "forward" && edge.from !== edge.to);
138
+ if (children.length < 2) return void 0;
139
+ const index = children.findIndex((child) => child.migrationHash === producer.migrationHash);
140
+ return index >= 0 ? index : void 0;
141
+ }
142
+ return rows.map((row, rowIndex) => {
143
+ if (row.kind !== "edge" || row.edge === void 0 || row.laneIndex === void 0) return row;
144
+ const divergenceBranchEdge = row.edge.kind === "forward" && !(row.convergenceProducer ?? false) && (forwardOutDegree.get(row.edge.from) ?? 0) >= 2 && branchLaneForEdge(row.edge) !== void 0;
145
+ const adjacency = row.convergenceProducer === true && convergenceProducerUsesShortAdjacency(row.edge, row.laneIndex, forwardProducersByTo, producerLaneByHash) ? classifyForwardShortConvergenceAdjacency(rows, rowIndex, row.edge, row.laneIndex) : classifyLayoutAdjacency(rows, rowIndex, row.edge, row.laneIndex, row.passThroughLanes ?? [], nodeColumn, position, forwardInDegree, row.convergenceProducer ?? false, divergenceBranchEdge);
146
+ return {
147
+ ...row,
148
+ cells: buildEdgeCells(row.edge, row.laneIndex, row.passThroughLanes ?? [], adjacency, row.cells.length)
149
+ };
150
+ });
151
+ }
152
+ function classifyEdgeAdjacency(edge, position) {
153
+ if (edge.kind === "self") return "adjacent";
154
+ const fromPos = position.get(edge.from);
155
+ const toPos = position.get(edge.to);
156
+ if (fromPos === void 0 || toPos === void 0) return "adjacent";
157
+ if (edge.kind === "forward") {
158
+ if (toPos >= fromPos) return "adjacent";
159
+ return fromPos === toPos + 1 ? "adjacent" : "node-skipping-forward";
160
+ }
161
+ if (toPos <= fromPos) return "adjacent";
162
+ return toPos === fromPos + 1 ? "adjacent" : "node-skipping-rollback";
163
+ }
164
+ function emptyCells(width) {
165
+ return Array.from({ length: width }, () => ({ kind: "empty" }));
166
+ }
167
+ function buildBranchConnectorCells(startLane, endLane, fanTargetLanes, activeLanes, gridWidth) {
168
+ const cells = emptyCells(gridWidth);
169
+ for (let lane = 0; lane < gridWidth; lane++) {
170
+ if (activeLanes.has(lane) && (lane < startLane || lane > endLane)) {
171
+ cells[lane] = { kind: "vertical-pass" };
172
+ continue;
173
+ }
174
+ if (lane === startLane) cells[lane] = { kind: "branch-tee" };
175
+ else if (lane === endLane) cells[lane] = { kind: "branch-corner" };
176
+ else if (lane > startLane && lane < endLane) if (fanTargetLanes.has(lane)) cells[lane] = { kind: "branch-tee" };
177
+ else if (activeLanes.has(lane)) cells[lane] = { kind: "arc-crossing" };
178
+ else cells[lane] = { kind: "branch-tee" };
179
+ }
180
+ return cells;
181
+ }
182
+ function buildMergeConnectorCells(startLane, endLane, fanTargetLanes, activeLanes, gridWidth) {
183
+ const cells = emptyCells(gridWidth);
184
+ for (let lane = 0; lane < gridWidth; lane++) {
185
+ if (activeLanes.has(lane) && (lane < startLane || lane > endLane)) {
186
+ cells[lane] = { kind: "vertical-pass" };
187
+ continue;
188
+ }
189
+ if (lane === startLane) cells[lane] = { kind: "merge-tee" };
190
+ else if (lane === endLane) cells[lane] = { kind: "merge-corner" };
191
+ else if (lane > startLane && lane < endLane) if (fanTargetLanes.has(lane)) cells[lane] = { kind: "merge-tee" };
192
+ else if (activeLanes.has(lane)) cells[lane] = { kind: "arc-crossing" };
193
+ else cells[lane] = { kind: "horizontal-pass" };
194
+ }
195
+ return cells;
196
+ }
197
+ function buildNodeCells(contractHash, nodeColumn, activeLanes, gridWidth) {
198
+ const cells = emptyCells(gridWidth);
199
+ for (const lane of activeLanes) if (lane !== nodeColumn && lane < gridWidth) cells[lane] = { kind: "vertical-pass" };
200
+ if (nodeColumn < gridWidth) cells[nodeColumn] = {
201
+ kind: "node",
202
+ contractHash
203
+ };
204
+ return cells;
205
+ }
206
+ function buildEdgeCells(edge, laneIndex, passThroughLanes, adjacency, gridWidth) {
207
+ const cells = emptyCells(gridWidth);
208
+ for (const lane of passThroughLanes) if (lane < gridWidth) cells[lane] = { kind: "vertical-pass" };
209
+ if (laneIndex < gridWidth) cells[laneIndex] = {
210
+ kind: "edge-lane",
211
+ migrationHash: edge.migrationHash,
212
+ edgeKind: edge.kind,
213
+ ownsLabel: true,
214
+ adjacency
215
+ };
216
+ return cells;
217
+ }
218
+ /**
219
+ * Compute the vertical node order for a component: tips at the top (index 0),
220
+ * roots at the bottom. This is a DFS post-order over forward edges starting
221
+ * from forward roots, visiting children in their input (insertion) order. A
222
+ * node is emitted only after all of its forward children, so convergence nodes
223
+ * sit below every branch that feeds them and the longest contiguous chain reads
224
+ * top-to-bottom without braiding.
225
+ */
226
+ function computeVerticalOrder(componentNodes, forwardChildren, forwardInDegree) {
227
+ const WHITE = 0;
228
+ const GRAY = 1;
229
+ const BLACK = 2;
230
+ const color = /* @__PURE__ */ new Map();
231
+ for (const node of componentNodes) color.set(node, WHITE);
232
+ const sortRoots = (roots) => [...roots].sort((a, b) => {
233
+ if (a === EMPTY_CONTRACT_HASH) return -1;
234
+ if (b === EMPTY_CONTRACT_HASH) return 1;
235
+ return a.localeCompare(b);
236
+ });
237
+ let roots = sortRoots(componentNodes.filter((n) => (forwardInDegree.get(n) ?? 0) === 0));
238
+ if (roots.length === 0) roots = sortRoots(componentNodes);
239
+ const result = [];
240
+ function runDfs(root) {
241
+ if (color.get(root) !== WHITE) return;
242
+ const stack = [{
243
+ node: root,
244
+ children: forwardChildren.get(root) ?? [],
245
+ index: 0
246
+ }];
247
+ color.set(root, GRAY);
248
+ while (stack.length > 0) {
249
+ const frame = stack[stack.length - 1];
250
+ if (frame === void 0) break;
251
+ if (frame.index >= frame.children.length) {
252
+ color.set(frame.node, BLACK);
253
+ result.push(frame.node);
254
+ stack.pop();
255
+ continue;
256
+ }
257
+ const child = frame.children[frame.index];
258
+ frame.index += 1;
259
+ if (child === void 0) continue;
260
+ if (color.get(child.to) === WHITE) {
261
+ color.set(child.to, GRAY);
262
+ stack.push({
263
+ node: child.to,
264
+ children: forwardChildren.get(child.to) ?? [],
265
+ index: 0
266
+ });
267
+ }
268
+ }
269
+ }
270
+ for (const root of roots) runDfs(root);
271
+ for (const node of componentNodes) if (color.get(node) === WHITE) runDfs(node);
272
+ return result;
273
+ }
274
+ function rollbackSpan(edge, position) {
275
+ const top = position.get(edge.from) ?? 0;
276
+ return {
277
+ top,
278
+ bottom: position.get(edge.to) ?? top
279
+ };
280
+ }
281
+ function spansOverlap(a, b) {
282
+ return a.top <= b.bottom && b.top <= a.bottom;
283
+ }
284
+ function forwardMaxLane(rows, skipMigrationHashes) {
285
+ let max = 0;
286
+ for (const row of rows) {
287
+ if (row.kind === "edge" && row.edge !== void 0 && skipMigrationHashes.has(row.edge.migrationHash)) continue;
288
+ max = Math.max(max, row.laneIndex ?? 0);
289
+ for (const lane of row.passThroughLanes ?? []) max = Math.max(max, lane);
290
+ if (row.startLane !== void 0) max = Math.max(max, row.startLane, row.endLane ?? row.startLane);
291
+ }
292
+ return max;
293
+ }
294
+ function allocateSkipRollbackBackLanes(skipRollbacks, position, forwardMax) {
295
+ const sorted = [...skipRollbacks].sort((a, b) => {
296
+ const aTop = position.get(a.from) ?? 0;
297
+ const bTop = position.get(b.from) ?? 0;
298
+ if (aTop !== bTop) return aTop - bTop;
299
+ return b.dirName.localeCompare(a.dirName);
300
+ });
301
+ const occupied = [];
302
+ const lanes = /* @__PURE__ */ new Map();
303
+ let nextLane = forwardMax + 1;
304
+ for (const edge of sorted) {
305
+ const span = rollbackSpan(edge, position);
306
+ let lane = nextLane;
307
+ while (occupied.some((entry) => entry.lane === lane && spansOverlap(entry, span))) lane += 1;
308
+ occupied.push({
309
+ ...span,
310
+ lane
311
+ });
312
+ lanes.set(edge.migrationHash, lane);
313
+ nextLane = Math.max(nextLane, lane + 1);
314
+ }
315
+ return lanes;
316
+ }
317
+ function findNodeRowIndex(rows, contractHash) {
318
+ return rows.findIndex((row) => row.kind === "node" && row.contractHash === contractHash);
319
+ }
320
+ function findEdgeRowIndex(rows, migrationHash) {
321
+ return rows.findIndex((row) => row.kind === "edge" && row.edge?.migrationHash === migrationHash);
322
+ }
323
+ function ensureCellWidth(cells, width) {
324
+ while (cells.length < width) cells.push({ kind: "empty" });
325
+ }
326
+ function cloneRow(row) {
327
+ return {
328
+ ...row,
329
+ cells: [...row.cells]
330
+ };
331
+ }
332
+ function routeCrossesRow(route, rowIndex, rows) {
333
+ const sourceRow = findNodeRowIndex(rows, route.edge.from);
334
+ const targetRow = findNodeRowIndex(rows, route.edge.to);
335
+ if (sourceRow < 0 || targetRow < 0) return false;
336
+ return rowIndex > sourceRow && rowIndex <= targetRow;
337
+ }
338
+ function applySkipRollbackRouting(rows, skipRollbacks, position, nodeColumn, edgeColumn) {
339
+ if (skipRollbacks.length === 0) return [...rows];
340
+ const forwardMax = forwardMaxLane(rows, new Set(skipRollbacks.map((edge) => edge.migrationHash)));
341
+ const backLaneByHash = allocateSkipRollbackBackLanes(skipRollbacks, position, forwardMax);
342
+ const routes = skipRollbacks.map((edge) => ({
343
+ edge,
344
+ backLane: backLaneByHash.get(edge.migrationHash) ?? forwardMax + 1
345
+ }));
346
+ const result = rows.map(cloneRow);
347
+ for (const route of routes) {
348
+ const { edge, backLane } = route;
349
+ const nodeCol = nodeColumn.get(edge.from) ?? 0;
350
+ const targetCol = nodeColumn.get(edge.to) ?? 0;
351
+ const sourceRowIndex = findNodeRowIndex(result, edge.from);
352
+ const targetRowIndex = findNodeRowIndex(result, edge.to);
353
+ const edgeRowIndex = findEdgeRowIndex(result, edge.migrationHash);
354
+ if (sourceRowIndex < 0 || targetRowIndex < 0 || edgeRowIndex < 0) continue;
355
+ edgeColumn.set(edge.migrationHash, backLane);
356
+ const coSourcedLanes = routes.filter((other) => other.edge.from === edge.from).map((other) => other.backLane);
357
+ const maxCoSourcedLane = Math.max(...coSourcedLanes);
358
+ const coLandingLanes = routes.filter((other) => other.edge.to === edge.to).map((other) => other.backLane);
359
+ const maxCoLandingLane = Math.max(...coLandingLanes);
360
+ const sourceRow = result[sourceRowIndex];
361
+ if (sourceRow !== void 0) {
362
+ const cells = sourceRow.cells;
363
+ ensureCellWidth(cells, backLane + 1);
364
+ cells[nodeCol] = {
365
+ kind: "node",
366
+ contractHash: sourceRow.contractHash ?? EMPTY_CONTRACT_HASH,
367
+ arcTee: true
368
+ };
369
+ for (let lane = nodeCol + 1; lane < backLane; lane += 1) {
370
+ if (coSourcedLanes.includes(lane)) {
371
+ cells[lane] = { kind: "arc-branch-tee" };
372
+ continue;
373
+ }
374
+ const existing = cells[lane];
375
+ cells[lane] = existing !== void 0 && existing.kind !== "empty" && existing.kind !== "horizontal-pass" && existing.kind !== "arc-land-bridge" || routes.some((other) => other.edge.migrationHash !== edge.migrationHash && other.backLane === lane && routeCrossesRow(other, sourceRowIndex, result)) ? { kind: "arc-crossing" } : { kind: "horizontal-pass" };
376
+ }
377
+ cells[backLane] = backLane < maxCoSourcedLane ? { kind: "arc-branch-tee" } : { kind: "arc-branch-corner" };
378
+ }
379
+ const edgeRow = result[edgeRowIndex];
380
+ if (edgeRow !== void 0) {
381
+ const cells = edgeRow.cells;
382
+ ensureCellWidth(cells, backLane + 1);
383
+ cells[nodeCol] = { kind: "vertical-pass" };
384
+ cells[backLane] = {
385
+ kind: "edge-lane",
386
+ migrationHash: edge.migrationHash,
387
+ edgeKind: edge.kind,
388
+ ownsLabel: true,
389
+ adjacency: "node-skipping-rollback"
390
+ };
391
+ result[edgeRowIndex] = {
392
+ ...edgeRow,
393
+ laneIndex: backLane,
394
+ passThroughLanes: [nodeCol]
395
+ };
396
+ }
397
+ for (let index = sourceRowIndex + 1; index < targetRowIndex; index += 1) {
398
+ if (index === edgeRowIndex) continue;
399
+ const row = result[index];
400
+ if (row === void 0) continue;
401
+ const cells = row.cells;
402
+ ensureCellWidth(cells, backLane + 1);
403
+ const existing = cells[backLane];
404
+ if (existing?.kind !== "arc-land-corner" && existing?.kind !== "arc-land-tee" && existing?.kind !== "arc-land-bridge" && existing?.kind !== "arc-branch-corner" && existing?.kind !== "arc-branch-tee" && existing?.kind !== "arc-crossing") cells[backLane] = { kind: "vertical-pass" };
405
+ }
406
+ const targetRow = result[targetRowIndex];
407
+ if (targetRow !== void 0) {
408
+ const cells = targetRow.cells;
409
+ ensureCellWidth(cells, backLane + 1);
410
+ cells[targetCol] = {
411
+ kind: "node",
412
+ contractHash: targetRow.contractHash ?? EMPTY_CONTRACT_HASH,
413
+ arcLand: true
414
+ };
415
+ for (let lane = targetCol + 1; lane < backLane; lane += 1) {
416
+ if (coLandingLanes.includes(lane)) {
417
+ cells[lane] = { kind: "arc-land-tee" };
418
+ continue;
419
+ }
420
+ const existing = cells[lane];
421
+ cells[lane] = existing !== void 0 && existing.kind !== "empty" && existing.kind !== "horizontal-pass" && existing.kind !== "arc-land-bridge" && existing.kind !== "arc-land-tee" || routes.some((other) => other.edge.migrationHash !== edge.migrationHash && other.backLane === lane && routeCrossesRow(other, targetRowIndex, result)) ? { kind: "arc-crossing" } : { kind: "arc-land-bridge" };
422
+ }
423
+ cells[backLane] = backLane < maxCoLandingLane ? { kind: "arc-land-tee" } : { kind: "arc-land-corner" };
424
+ for (const other of routes) {
425
+ if (other.backLane <= backLane) continue;
426
+ if (!routeCrossesRow(other, targetRowIndex, result)) continue;
427
+ ensureCellWidth(cells, other.backLane + 1);
428
+ const existing = cells[other.backLane];
429
+ if (existing?.kind !== "arc-land-corner" && existing?.kind !== "arc-land-tee" && existing?.kind !== "arc-land-bridge" && existing?.kind !== "node") cells[other.backLane] = { kind: "vertical-pass" };
430
+ }
431
+ }
432
+ }
433
+ return result;
434
+ }
435
+ function collectNodeSkippingRollbacks(edges, position) {
436
+ return edges.filter((edge) => edge.kind === "rollback" && classifyEdgeAdjacency(edge, position) === "node-skipping-rollback");
437
+ }
438
+ function layoutComponent(componentNodes, allEdges) {
439
+ const componentSet = new Set(componentNodes);
440
+ const edges = allEdges.filter((e) => componentSet.has(e.from) && componentSet.has(e.to));
441
+ const forwardChildren = /* @__PURE__ */ new Map();
442
+ const producersByTo = /* @__PURE__ */ new Map();
443
+ const rollbacksByFrom = /* @__PURE__ */ new Map();
444
+ const selfByFrom = /* @__PURE__ */ new Map();
445
+ for (const edge of edges) {
446
+ if (edge.kind === "self" || edge.from === edge.to) {
447
+ const bucket = selfByFrom.get(edge.from);
448
+ if (bucket) bucket.push(edge);
449
+ else selfByFrom.set(edge.from, [edge]);
450
+ continue;
451
+ }
452
+ if (edge.kind === "forward") {
453
+ const children = forwardChildren.get(edge.from);
454
+ if (children) children.push(edge);
455
+ else forwardChildren.set(edge.from, [edge]);
456
+ const producers = producersByTo.get(edge.to);
457
+ if (producers) producers.push(edge);
458
+ else producersByTo.set(edge.to, [edge]);
459
+ continue;
460
+ }
461
+ const bucket = rollbacksByFrom.get(edge.from);
462
+ if (bucket) bucket.push(edge);
463
+ else rollbacksByFrom.set(edge.from, [edge]);
464
+ }
465
+ const forwardInDegree = buildForwardInDegree(edges);
466
+ const forwardOutDegree = buildForwardOutDegree(edges);
467
+ const distinctSourceCountByTo = buildDistinctSourceCountByTo(edges);
468
+ const order = computeVerticalOrder(componentNodes, forwardChildren, forwardInDegree);
469
+ const position = /* @__PURE__ */ new Map();
470
+ for (let index = 0; index < order.length; index++) {
471
+ const node = order[index];
472
+ if (node !== void 0) position.set(node, index);
473
+ }
474
+ const lanes = [];
475
+ const rows = [];
476
+ const nodeColumn = /* @__PURE__ */ new Map();
477
+ const edgeColumn = /* @__PURE__ */ new Map();
478
+ const producerLaneByHash = /* @__PURE__ */ new Map();
479
+ let gridWidth = 1;
480
+ function ensureGridWidth(minWidth) {
481
+ if (minWidth > gridWidth) gridWidth = minWidth;
482
+ }
483
+ function setLane(index, want) {
484
+ while (lanes.length <= index) lanes.push(null);
485
+ lanes[index] = want;
486
+ if (want !== null) ensureGridWidth(index + 1);
487
+ }
488
+ function activeLaneIndices() {
489
+ const indices = [];
490
+ for (let index = 0; index < lanes.length; index++) if (lanes[index] !== null) indices.push(index);
491
+ return indices;
492
+ }
493
+ function passThroughExcept(lane) {
494
+ return activeLaneIndices().filter((index) => index !== lane);
495
+ }
496
+ function leftmostFreeLane() {
497
+ for (let index = 0; index < lanes.length; index++) if (lanes[index] === null) return index;
498
+ return lanes.length;
499
+ }
500
+ function lanesWanting(contract) {
501
+ const indices = [];
502
+ for (let index = 0; index < lanes.length; index++) if (lanes[index] === contract) indices.push(index);
503
+ return indices;
504
+ }
505
+ function emitMergeConnector(contractHash, laneIndices) {
506
+ const startLane = Math.min(...laneIndices);
507
+ const endLane = Math.max(...laneIndices);
508
+ ensureGridWidth(endLane + 1);
509
+ const activeLanes = new Set(activeLaneIndices());
510
+ const fanTargetLanes = new Set(laneIndices);
511
+ rows.push({
512
+ kind: "merge-connector",
513
+ contractHash,
514
+ startLane,
515
+ endLane,
516
+ branchCount: laneIndices.length,
517
+ cells: buildMergeConnectorCells(startLane, endLane, fanTargetLanes, activeLanes, gridWidth)
518
+ });
519
+ for (const index of laneIndices) if (index !== startLane) setLane(index, null);
520
+ return startLane;
521
+ }
522
+ function emitBranchConnector(contractHash, startLane, endLane, branchCount, fanTargetLanes) {
523
+ ensureGridWidth(endLane + 1);
524
+ const activeLanes = new Set(activeLaneIndices());
525
+ rows.push({
526
+ kind: "branch-connector",
527
+ contractHash,
528
+ startLane,
529
+ endLane,
530
+ branchCount,
531
+ cells: buildBranchConnectorCells(startLane, endLane, new Set(fanTargetLanes), activeLanes, gridWidth)
532
+ });
533
+ }
534
+ function emitEdgeRow(edge, lane, convergenceProducer) {
535
+ const passThrough = passThroughExcept(lane);
536
+ const adjacency = classifyEdgeAdjacency(edge, position);
537
+ ensureGridWidth(Math.max(lane, ...passThrough, 0) + 1);
538
+ const row = {
539
+ kind: "edge",
540
+ edge,
541
+ laneIndex: lane,
542
+ passThroughLanes: passThrough,
543
+ cells: buildEdgeCells(edge, lane, passThrough, adjacency, gridWidth)
544
+ };
545
+ rows.push(convergenceProducer ? {
546
+ ...row,
547
+ convergenceProducer: true
548
+ } : row);
549
+ edgeColumn.set(edge.migrationHash, lane);
550
+ if (convergenceProducer) producerLaneByHash.set(edge.migrationHash, lane);
551
+ }
552
+ function emitNodeRow(contractHash, column) {
553
+ ensureGridWidth(column + 1);
554
+ const passThrough = activeLaneIndices().filter((index) => index !== column);
555
+ rows.push({
556
+ kind: "node",
557
+ contractHash,
558
+ cells: buildNodeCells(contractHash, column, passThrough, gridWidth)
559
+ });
560
+ nodeColumn.set(contractHash, column);
561
+ }
562
+ function producerGroups(node) {
563
+ const byTarget = /* @__PURE__ */ new Map();
564
+ for (const producer of producersByTo.get(node) ?? []) {
565
+ const group = byTarget.get(producer.from);
566
+ if (group) group.edges.push(producer);
567
+ else byTarget.set(producer.from, {
568
+ target: producer.from,
569
+ edges: [producer]
570
+ });
571
+ }
572
+ const groups = [...byTarget.values()];
573
+ groups.sort((a, b) => (position.get(a.target) ?? 0) - (position.get(b.target) ?? 0));
574
+ for (const group of groups) group.edges.sort((a, b) => b.dirName.localeCompare(a.dirName));
575
+ return groups;
576
+ }
577
+ function processNode(node) {
578
+ const wanting = lanesWanting(node);
579
+ let column;
580
+ if (wanting.length >= 2) column = emitMergeConnector(node, wanting);
581
+ else if (wanting.length === 1) column = wanting[0] ?? 0;
582
+ else column = leftmostFreeLane();
583
+ const selfEdges = [...selfByFrom.get(node) ?? []].sort((a, b) => b.dirName.localeCompare(a.dirName));
584
+ for (const selfEdge of selfEdges) emitEdgeRow(selfEdge, column, false);
585
+ emitNodeRow(node, column);
586
+ const rollbacks = [...rollbacksByFrom.get(node) ?? []].sort((a, b) => b.dirName.localeCompare(a.dirName));
587
+ const skipRollbacks = [];
588
+ const adjacentRollbacks = [];
589
+ for (const rollback of rollbacks) if (classifyEdgeAdjacency(rollback, position) === "node-skipping-rollback") skipRollbacks.push(rollback);
590
+ else adjacentRollbacks.push(rollback);
591
+ for (const rollback of skipRollbacks) emitEdgeRow(rollback, column, false);
592
+ const groups = producerGroups(node);
593
+ const isConvergence = (distinctSourceCountByTo.get(node) ?? 0) >= 2;
594
+ const laneForGroup = [];
595
+ for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
596
+ const group = groups[groupIndex];
597
+ if (group === void 0) continue;
598
+ const lane = groupIndex === 0 ? column : leftmostFreeLane();
599
+ laneForGroup[groupIndex] = lane;
600
+ setLane(lane, group.target);
601
+ }
602
+ if (groups.length >= 2) {
603
+ const endLane = Math.max(...laneForGroup);
604
+ emitBranchConnector(node, column, endLane, groups.length, laneForGroup);
605
+ }
606
+ for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
607
+ const group = groups[groupIndex];
608
+ const lane = laneForGroup[groupIndex];
609
+ if (group === void 0 || lane === void 0) continue;
610
+ for (const edge of group.edges) emitEdgeRow(edge, lane, isConvergence);
611
+ }
612
+ for (const rollback of adjacentRollbacks) emitEdgeRow(rollback, column, false);
613
+ if (groups.length === 0) setLane(column, null);
614
+ }
615
+ for (const node of order) processNode(node);
616
+ return {
617
+ rows: applySkipRollbackRouting(refineAdjacency(rows, nodeColumn, position, forwardInDegree, forwardOutDegree, edges, producerLaneByHash), collectNodeSkippingRollbacks(edges, position), position, nodeColumn, edgeColumn),
618
+ nodeColumn,
619
+ edgeColumn
620
+ };
621
+ }
622
+ function buildMigrationGraphLayout(rowModel) {
623
+ if (rowModel.nodes.length === 0) return {
624
+ rows: [],
625
+ nodeColumn: /* @__PURE__ */ new Map(),
626
+ edgeColumn: /* @__PURE__ */ new Map()
627
+ };
628
+ const components = splitComponents(rowModel.nodes);
629
+ const allRows = [];
630
+ const nodeColumn = /* @__PURE__ */ new Map();
631
+ const edgeColumn = /* @__PURE__ */ new Map();
632
+ for (let componentIndex = 0; componentIndex < components.length; componentIndex++) {
633
+ if (componentIndex > 0) allRows.push({
634
+ kind: "component-separator",
635
+ cells: []
636
+ });
637
+ const component = components[componentIndex];
638
+ if (component === void 0 || component.length === 0) continue;
639
+ const result = layoutComponent(component, rowModel.edges);
640
+ allRows.push(...result.rows);
641
+ for (const [hash, column] of result.nodeColumn) nodeColumn.set(hash, column);
642
+ for (const [hash, column] of result.edgeColumn) edgeColumn.set(hash, column);
643
+ }
644
+ return {
645
+ rows: allRows,
646
+ nodeColumn,
647
+ edgeColumn
648
+ };
649
+ }
650
+ //#endregion
651
+ //#region src/utils/formatters/migration-list-graph-topology.ts
652
+ function compareDirNameDesc(a, b) {
653
+ return b.dirName.localeCompare(a.dirName);
654
+ }
655
+ function bumpDegree(map, key) {
656
+ map.set(key, (map.get(key) ?? 0) + 1);
657
+ }
658
+ function compareNodesRootFirst(a, b) {
659
+ if (a === EMPTY_CONTRACT_HASH) return -1;
660
+ if (b === EMPTY_CONTRACT_HASH) return 1;
661
+ return a.localeCompare(b);
662
+ }
663
+ /**
664
+ * Shortest-path distance of each node from the forward roots, over the given
665
+ * candidate edges. Roots are the in-degree-0 nodes (baseline first, then lex);
666
+ * a rooted component therefore distances every node by how many forward steps
667
+ * it sits from a root. A component with no root (a pure cycle) is seeded from
668
+ * its single lexically-smallest node so the cycle still gets a stable layering.
669
+ *
670
+ * Crucially this is *shortest* path, not longest: a backward (rollback) edge
671
+ * `deep → shallow` never offers a shorter route to the already-shallower
672
+ * target, so it is inert here. Distances are thus stable whether or not the
673
+ * rollbacks are still in the candidate set — which is what lets the peel below
674
+ * tell a genuine back-edge (target strictly shallower than source) apart from a
675
+ * forward edge that merely happens to share the back-edge's cycle.
676
+ */
677
+ function forwardDistances(nodes, candidates) {
678
+ const inDegree = /* @__PURE__ */ new Map();
679
+ for (const node of nodes) inDegree.set(node, 0);
680
+ for (const edge of candidates) bumpDegree(inDegree, edge.to);
681
+ const roots = [...nodes].filter((node) => (inDegree.get(node) ?? 0) === 0);
682
+ roots.sort(compareNodesRootFirst);
683
+ const seeds = roots.length > 0 ? roots : [...nodes].sort(compareNodesRootFirst).slice(0, 1);
684
+ const dist = /* @__PURE__ */ new Map();
685
+ for (const seed of seeds) dist.set(seed, 0);
686
+ const maxPasses = nodes.size;
687
+ for (let pass = 0; pass < maxPasses; pass++) {
688
+ let changed = false;
689
+ for (const edge of candidates) {
690
+ const base = dist.get(edge.from);
691
+ if (base === void 0) continue;
692
+ const next = base + 1;
693
+ if (next < (dist.get(edge.to) ?? Number.POSITIVE_INFINITY)) {
694
+ dist.set(edge.to, next);
695
+ changed = true;
696
+ }
697
+ }
698
+ if (!changed) break;
699
+ }
700
+ for (const node of nodes) if (!dist.has(node)) dist.set(node, 0);
701
+ return dist;
702
+ }
703
+ function canReachForward(start, goal, candidates) {
704
+ if (start === goal) return true;
705
+ const outgoing = /* @__PURE__ */ new Map();
706
+ for (const edge of candidates) {
707
+ const bucket = outgoing.get(edge.from);
708
+ if (bucket) bucket.push(edge.to);
709
+ else outgoing.set(edge.from, [edge.to]);
710
+ }
711
+ const visited = new Set([start]);
712
+ const queue = [start];
713
+ while (queue.length > 0) {
714
+ const node = queue.shift();
715
+ if (node === void 0) continue;
716
+ for (const next of outgoing.get(node) ?? []) {
717
+ if (next === goal) return true;
718
+ if (!visited.has(next)) {
719
+ visited.add(next);
720
+ queue.push(next);
721
+ }
722
+ }
723
+ }
724
+ return false;
725
+ }
726
+ /**
727
+ * Demote node-skipping rollbacks left forward by the DFS. An edge `from → to`
728
+ * is a rollback exactly when both hold:
729
+ * 1. `to` is a forward-ancestor of `from` — `to` can still reach `from` over
730
+ * the other forward edges, so the edge closes a cycle; and
731
+ * 2. `to` is strictly shallower than `from` (smaller forward distance) — the
732
+ * edge points back toward the root rather than advancing history.
733
+ *
734
+ * Condition 2 is the discriminator: in a cycle created by a rollback every edge
735
+ * satisfies condition 1, but only the rollback itself runs deep → shallow. The
736
+ * forward chain edges run shallow → deep and are never peeled, however many
737
+ * rollbacks converge on the same target. Tight back-edges whose source and
738
+ * target sit at the same distance (mutual two-node cycles) are already resolved
739
+ * by the DFS immediate-parent rule, so they never reach this pass. One edge is
740
+ * peeled per iteration (dirName-descending tie-break) and distances/reachability
741
+ * are recomputed, making the outcome independent of edge input order.
742
+ */
743
+ function peelNodeSkippingRollbacks(nodes, kindByMigrationHash, nonSelf) {
744
+ let candidates = nonSelf.filter((edge) => kindByMigrationHash.get(edge.hash) === "forward");
745
+ while (candidates.length > 0) {
746
+ const dist = forwardDistances(nodes, candidates);
747
+ const backEdges = candidates.filter((edge) => {
748
+ if ((dist.get(edge.to) ?? 0) >= (dist.get(edge.from) ?? 0)) return false;
749
+ const without = candidates.filter((candidate) => candidate !== edge);
750
+ return canReachForward(edge.to, edge.from, without);
751
+ });
752
+ if (backEdges.length === 0) break;
753
+ backEdges.sort(compareDirNameDesc);
754
+ const rollback = backEdges[0];
755
+ if (rollback === void 0) break;
756
+ kindByMigrationHash.set(rollback.hash, "rollback");
757
+ candidates = candidates.filter((edge) => edge !== rollback);
758
+ }
759
+ }
760
+ /**
761
+ * DFS with dirName-descending traversal. A GRAY target is a rollback only when it
762
+ * is the immediate DFS parent of the source — cross-links to other GRAY nodes
763
+ * stay forward. A follow-up peel pass demotes node-skipping rollbacks (target is
764
+ * a forward-ancestor of the source and sits strictly shallower than it).
765
+ */
766
+ function classifyNormalizedEdges(edges) {
767
+ const nodes = /* @__PURE__ */ new Set();
768
+ const kindByMigrationHash = /* @__PURE__ */ new Map();
769
+ const outgoingByFrom = /* @__PURE__ */ new Map();
770
+ const nonSelf = [];
771
+ for (const edge of edges) {
772
+ nodes.add(edge.from);
773
+ nodes.add(edge.to);
774
+ if (edge.from === edge.to) {
775
+ kindByMigrationHash.set(edge.hash, "self");
776
+ continue;
777
+ }
778
+ nonSelf.push(edge);
779
+ const bucket = outgoingByFrom.get(edge.from);
780
+ if (bucket) bucket.push(edge);
781
+ else outgoingByFrom.set(edge.from, [edge]);
782
+ }
783
+ for (const bucket of outgoingByFrom.values()) bucket.sort(compareDirNameDesc);
784
+ const nonSelfInDegree = /* @__PURE__ */ new Map();
785
+ for (const node of nodes) nonSelfInDegree.set(node, 0);
786
+ for (const bucket of outgoingByFrom.values()) for (const edge of bucket) bumpDegree(nonSelfInDegree, edge.to);
787
+ const dfsRoots = [];
788
+ for (const node of nodes) if ((nonSelfInDegree.get(node) ?? 0) === 0) dfsRoots.push(node);
789
+ dfsRoots.sort((a, b) => {
790
+ if (a === EMPTY_CONTRACT_HASH) return -1;
791
+ if (b === EMPTY_CONTRACT_HASH) return 1;
792
+ return a.localeCompare(b);
793
+ });
794
+ if (dfsRoots.length === 0) dfsRoots.push(...[...nodes].sort((a, b) => a.localeCompare(b)));
795
+ const WHITE = 0;
796
+ const GRAY = 1;
797
+ const BLACK = 2;
798
+ const color = /* @__PURE__ */ new Map();
799
+ const dfsParent = /* @__PURE__ */ new Map();
800
+ for (const node of nodes) color.set(node, WHITE);
801
+ const stack = [];
802
+ function isImmediateDfsParent(ancestor, node) {
803
+ return dfsParent.get(node) === ancestor;
804
+ }
805
+ function pushFrame(node, parent) {
806
+ color.set(node, GRAY);
807
+ dfsParent.set(node, parent);
808
+ stack.push({
809
+ node,
810
+ outgoing: outgoingByFrom.get(node) ?? [],
811
+ index: 0
812
+ });
813
+ }
814
+ function runDfsFrom(root) {
815
+ if (color.get(root) !== WHITE) return;
816
+ pushFrame(root, void 0);
817
+ while (stack.length > 0) {
818
+ const frame = stack[stack.length - 1];
819
+ if (frame === void 0) break;
820
+ if (frame.index >= frame.outgoing.length) {
821
+ color.set(frame.node, BLACK);
822
+ stack.pop();
823
+ continue;
824
+ }
825
+ const edge = frame.outgoing[frame.index];
826
+ frame.index += 1;
827
+ if (edge === void 0) continue;
828
+ const v = edge.to;
829
+ const vColor = color.get(v);
830
+ if (vColor === GRAY && isImmediateDfsParent(v, frame.node)) kindByMigrationHash.set(edge.hash, "rollback");
831
+ else {
832
+ kindByMigrationHash.set(edge.hash, "forward");
833
+ if (vColor === WHITE) pushFrame(v, frame.node);
834
+ }
835
+ }
836
+ }
837
+ for (const root of dfsRoots) runDfsFrom(root);
838
+ const remainingWhite = [...nodes].filter((node) => color.get(node) === WHITE);
839
+ remainingWhite.sort((a, b) => a.localeCompare(b));
840
+ for (const root of remainingWhite) runDfsFrom(root);
841
+ peelNodeSkippingRollbacks(nodes, kindByMigrationHash, nonSelf);
842
+ const forwardInDegree = /* @__PURE__ */ new Map();
843
+ const forwardOutDegree = /* @__PURE__ */ new Map();
844
+ for (const edge of edges) {
845
+ if (kindByMigrationHash.get(edge.hash) !== "forward") continue;
846
+ bumpDegree(forwardOutDegree, edge.from);
847
+ bumpDegree(forwardInDegree, edge.to);
848
+ }
849
+ return {
850
+ kindByMigrationHash,
851
+ forwardInDegree,
852
+ forwardOutDegree
853
+ };
854
+ }
855
+ /**
856
+ * Classify forward/rollback/self for a `MigrationGraph` edge set (Tier-3).
857
+ */
858
+ function classifyMigrationGraphTopology(graph) {
859
+ const normalized = [];
860
+ for (const edges of graph.forwardChain.values()) for (const edge of edges) normalized.push({
861
+ hash: edge.migrationHash,
862
+ from: edge.from,
863
+ to: edge.to,
864
+ dirName: edge.dirName
865
+ });
866
+ return classifyNormalizedEdges(normalized);
867
+ }
868
+ //#endregion
869
+ //#region src/utils/formatters/migration-graph-rows.ts
870
+ /**
871
+ * Return the weakly-connected components of `graph` as an array of node sets,
872
+ * ordered so the component containing EMPTY_CONTRACT_HASH comes first (if
873
+ * present), with remaining components sorted by their lex-smallest node hash.
874
+ */
875
+ function weaklyConnectedComponents(graph) {
876
+ const visited = /* @__PURE__ */ new Set();
877
+ const adjacency = /* @__PURE__ */ new Map();
878
+ function addAdjacent(a, b) {
879
+ const aList = adjacency.get(a);
880
+ if (aList) aList.push(b);
881
+ else adjacency.set(a, [b]);
882
+ const bList = adjacency.get(b);
883
+ if (bList) bList.push(a);
884
+ else adjacency.set(b, [a]);
885
+ }
886
+ for (const edges of graph.forwardChain.values()) for (const edge of edges) if (edge.from !== edge.to) addAdjacent(edge.from, edge.to);
887
+ for (const node of graph.nodes) if (!adjacency.has(node)) adjacency.set(node, []);
888
+ const components = [];
889
+ function bfsComponent(start) {
890
+ const component = /* @__PURE__ */ new Set();
891
+ const queue = [start];
892
+ while (queue.length > 0) {
893
+ const node = queue.shift();
894
+ if (node === void 0 || visited.has(node)) continue;
895
+ visited.add(node);
896
+ component.add(node);
897
+ for (const neighbor of adjacency.get(node) ?? []) if (!visited.has(neighbor)) queue.push(neighbor);
898
+ }
899
+ return component;
900
+ }
901
+ const allNodes = [...graph.nodes].sort((a, b) => {
902
+ if (a === EMPTY_CONTRACT_HASH) return -1;
903
+ if (b === EMPTY_CONTRACT_HASH) return 1;
904
+ return a.localeCompare(b);
905
+ });
906
+ for (const node of allNodes) if (!visited.has(node)) components.push(bfsComponent(node));
907
+ components.sort((a, b) => {
908
+ const aHasEmpty = a.has(EMPTY_CONTRACT_HASH);
909
+ const bHasEmpty = b.has(EMPTY_CONTRACT_HASH);
910
+ if (aHasEmpty && !bHasEmpty) return -1;
911
+ if (!aHasEmpty && bHasEmpty) return 1;
912
+ const aMin = [...a].sort((x, y) => x.localeCompare(y))[0] ?? "";
913
+ const bMin = [...b].sort((x, y) => x.localeCompare(y))[0] ?? "";
914
+ return aMin.localeCompare(bMin);
915
+ });
916
+ return components;
917
+ }
918
+ function forwardRootsInComponent(componentNodes, topology) {
919
+ const roots = [];
920
+ for (const node of componentNodes) if ((topology.forwardInDegree.get(node) ?? 0) === 0) roots.push(node);
921
+ roots.sort((a, b) => {
922
+ if (a === EMPTY_CONTRACT_HASH) return -1;
923
+ if (b === EMPTY_CONTRACT_HASH) return 1;
924
+ return a.localeCompare(b);
925
+ });
926
+ if (roots.length > 0) return roots;
927
+ return [...componentNodes].sort((a, b) => {
928
+ if (a === EMPTY_CONTRACT_HASH) return -1;
929
+ if (b === EMPTY_CONTRACT_HASH) return 1;
930
+ return a.localeCompare(b);
931
+ });
932
+ }
933
+ function compareNodesTipsFirst(a, b, rank) {
934
+ const rankA = rank.get(a) ?? 0;
935
+ const rankB = rank.get(b) ?? 0;
936
+ if (rankA !== rankB) return rankB - rankA;
937
+ if (a === EMPTY_CONTRACT_HASH) return 1;
938
+ if (b === EMPTY_CONTRACT_HASH) return -1;
939
+ return a.localeCompare(b);
940
+ }
941
+ /**
942
+ * Layer nodes by longest forward-path rank from forward roots within the
943
+ * component. Rank 0 is the root (bottom row); the maximum rank is the tip
944
+ * (top row). Emits rank-descending with lex-ascending tie-break among siblings
945
+ * at the same rank — stable across edge-insertion order and correct under
946
+ * diamonds, cross-links, and rollbacks.
947
+ */
948
+ function maxRank(rank) {
949
+ let max = 0;
950
+ for (const value of rank.values()) if (value > max) max = value;
951
+ return max;
952
+ }
953
+ function layerNodesByLongestForwardPath(componentNodes, topology, graph, contractHash) {
954
+ const forwardOut = /* @__PURE__ */ new Map();
955
+ for (const node of componentNodes) forwardOut.set(node, []);
956
+ for (const edges of graph.forwardChain.values()) for (const edge of edges) {
957
+ if (!componentNodes.has(edge.from) || !componentNodes.has(edge.to)) continue;
958
+ if (edge.from === edge.to) continue;
959
+ if (topology.kindByMigrationHash.get(edge.migrationHash) !== "forward") continue;
960
+ const bucket = forwardOut.get(edge.from);
961
+ if (bucket) bucket.push(edge.to);
962
+ }
963
+ const roots = forwardRootsInComponent(componentNodes, topology);
964
+ const rank = /* @__PURE__ */ new Map();
965
+ for (const root of roots) rank.set(root, 0);
966
+ const maxPasses = componentNodes.size;
967
+ for (let pass = 0; pass < maxPasses; pass++) {
968
+ let changed = false;
969
+ for (const node of componentNodes) {
970
+ const base = rank.get(node);
971
+ if (base === void 0) continue;
972
+ for (const to of forwardOut.get(node) ?? []) {
973
+ const next = base + 1;
974
+ if (next > (rank.get(to) ?? -1)) {
975
+ rank.set(to, next);
976
+ changed = true;
977
+ }
978
+ }
979
+ }
980
+ if (!changed) break;
981
+ }
982
+ for (const node of componentNodes) if (!rank.has(node)) rank.set(node, 0);
983
+ if (contractHash !== void 0 && contractHash !== EMPTY_CONTRACT_HASH && componentNodes.has(contractHash) && (forwardOut.get(contractHash) ?? []).length === 0) rank.set(contractHash, maxRank(rank) + 1);
984
+ return [...componentNodes].sort((a, b) => compareNodesTipsFirst(a, b, rank));
985
+ }
986
+ /**
987
+ * Build the row model from a tolerant `MigrationGraph`.
988
+ *
989
+ * The row model is the first pure-data stage of the `migration graph` render
990
+ * pipeline. It:
991
+ * - classifies every edge as `forward`, `rollback`, or `self`;
992
+ * - produces a deterministic vertical node ordering (tips at index 0, roots
993
+ * at the end) within each weakly-connected component;
994
+ * - separates disjoint components with `null` sentinels;
995
+ * - optionally prepends a detached current contract as its own single-node
996
+ * component when `contractHash` is not already in the graph.
997
+ *
998
+ * No columns, no lane allocation, no glyphs, no rendering.
999
+ */
1000
+ /**
1001
+ * Resolve the detached current contract, if any: a real contract (not the
1002
+ * empty baseline) that no migration on disk produces, so it is absent from
1003
+ * the graph. Such a contract renders as a floating node rather than
1004
+ * decorating an existing one. Returns the hash when detached, else undefined.
1005
+ */
1006
+ function detachedContractHash(graph, contractHash) {
1007
+ return contractHash !== void 0 && contractHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(contractHash) ? contractHash : void 0;
1008
+ }
1009
+ function isForwardLeaf(node, edges) {
1010
+ return !edges.some((e) => e.kind === "forward" && e.from === node && e.from !== e.to);
1011
+ }
1012
+ function forwardReachableFrom(start, forwardTo) {
1013
+ const reachable = new Set([start]);
1014
+ const queue = [start];
1015
+ while (queue.length > 0) {
1016
+ const node = queue.shift();
1017
+ if (node === void 0) continue;
1018
+ for (const next of forwardTo.get(node) ?? []) if (!reachable.has(next)) {
1019
+ reachable.add(next);
1020
+ queue.push(next);
1021
+ }
1022
+ }
1023
+ return reachable;
1024
+ }
1025
+ function buildForwardToMap(edges) {
1026
+ const forwardTo = /* @__PURE__ */ new Map();
1027
+ for (const edge of edges) {
1028
+ if (edge.kind !== "forward" || edge.from === edge.to) continue;
1029
+ const bucket = forwardTo.get(edge.from);
1030
+ if (bucket) bucket.push(edge.to);
1031
+ else forwardTo.set(edge.from, [edge.to]);
1032
+ }
1033
+ return forwardTo;
1034
+ }
1035
+ function sortEdgesForContractHashTrunk(edges, contractHash) {
1036
+ if (contractHash === void 0 || contractHash === EMPTY_CONTRACT_HASH || !isForwardLeaf(contractHash, edges)) return edges;
1037
+ const preferredLeaf = contractHash;
1038
+ const forwardTo = buildForwardToMap(edges);
1039
+ const reachability = /* @__PURE__ */ new Map();
1040
+ function canReachContractHash(from) {
1041
+ let cached = reachability.get(from);
1042
+ if (cached === void 0) {
1043
+ cached = forwardReachableFrom(from, forwardTo);
1044
+ reachability.set(from, cached);
1045
+ }
1046
+ return cached.has(preferredLeaf);
1047
+ }
1048
+ function trunkBias(edge) {
1049
+ if (edge.kind !== "forward" || edge.from === edge.to) return 0;
1050
+ if (edge.to === preferredLeaf) return 2;
1051
+ if (canReachContractHash(edge.to)) return 1;
1052
+ return 0;
1053
+ }
1054
+ return edges.map((edge, index) => ({
1055
+ edge,
1056
+ index,
1057
+ bias: trunkBias(edge)
1058
+ })).sort((a, b) => {
1059
+ if (a.edge.from !== b.edge.from) return a.index - b.index;
1060
+ if (a.bias !== b.bias) return b.bias - a.bias;
1061
+ return a.index - b.index;
1062
+ }).map(({ edge }) => edge);
1063
+ }
1064
+ function rebuildEdgeLookupMaps(edges) {
1065
+ const edgesByFrom = /* @__PURE__ */ new Map();
1066
+ const edgesByTo = /* @__PURE__ */ new Map();
1067
+ for (const classified of edges) {
1068
+ const fromBucket = edgesByFrom.get(classified.from);
1069
+ if (fromBucket) fromBucket.push(classified);
1070
+ else edgesByFrom.set(classified.from, [classified]);
1071
+ const toBucket = edgesByTo.get(classified.to);
1072
+ if (toBucket) toBucket.push(classified);
1073
+ else edgesByTo.set(classified.to, [classified]);
1074
+ }
1075
+ return {
1076
+ edgesByFrom,
1077
+ edgesByTo
1078
+ };
1079
+ }
1080
+ function buildMigrationGraphRows(graph, options = {}) {
1081
+ const emptyModel = {
1082
+ nodes: [],
1083
+ edges: [],
1084
+ edgesByFrom: /* @__PURE__ */ new Map(),
1085
+ edgesByTo: /* @__PURE__ */ new Map()
1086
+ };
1087
+ if (graph.nodes.size === 0) {
1088
+ const detached = detachedContractHash(graph, options.contractHash);
1089
+ return detached !== void 0 ? {
1090
+ ...emptyModel,
1091
+ nodes: [detached]
1092
+ } : emptyModel;
1093
+ }
1094
+ const topology = classifyMigrationGraphTopology(graph);
1095
+ const edges = [];
1096
+ for (const edgeList of graph.forwardChain.values()) for (const edge of edgeList) {
1097
+ const kind = topology.kindByMigrationHash.get(edge.migrationHash) ?? "forward";
1098
+ edges.push({
1099
+ migrationHash: edge.migrationHash,
1100
+ from: edge.from,
1101
+ to: edge.to,
1102
+ dirName: edge.dirName,
1103
+ kind
1104
+ });
1105
+ }
1106
+ const sortedEdges = sortEdgesForContractHashTrunk(edges, options.contractHash);
1107
+ const { edgesByFrom, edgesByTo } = rebuildEdgeLookupMaps(sortedEdges);
1108
+ const components = weaklyConnectedComponents(graph);
1109
+ const nodes = [];
1110
+ for (let i = 0; i < components.length; i++) {
1111
+ if (i > 0) nodes.push(null);
1112
+ const component = components[i];
1113
+ if (component === void 0) continue;
1114
+ const ordered = layerNodesByLongestForwardPath(component, topology, graph, options.contractHash);
1115
+ for (const node of ordered) nodes.push(node);
1116
+ }
1117
+ const detached = detachedContractHash(graph, options.contractHash);
1118
+ if (detached !== void 0) {
1119
+ if (nodes.length > 0) nodes.unshift(null);
1120
+ nodes.unshift(detached);
1121
+ }
1122
+ return {
1123
+ nodes,
1124
+ edges: sortedEdges,
1125
+ edgesByFrom,
1126
+ edgesByTo
1127
+ };
1128
+ }
1129
+ //#endregion
1130
+ //#region src/utils/formatters/migration-graph-lane-colors.ts
1131
+ const { magenta: magenta$1, cyan: cyan$1, green: green$1, yellow: yellow$1, blueBright, red: red$1 } = createColors({ useColor: true });
1132
+ const LANE_COLOR_CYCLE = [
1133
+ magenta$1,
1134
+ cyan$1,
1135
+ green$1,
1136
+ yellow$1,
1137
+ blueBright,
1138
+ red$1
1139
+ ];
1140
+ /**
1141
+ * The hue for a gutter column. The leftmost lane (column 0) is **neutral** — it
1142
+ * has nothing to be told apart from in the common single-lane linear case, so
1143
+ * the renderer dims it rather than tinting it; the rotating palette is reserved
1144
+ * for columns ≥ 1 (where a second lane exists to distinguish). Callers must dim
1145
+ * column 0 themselves; this returns identity for it as a guard. A lane freed and
1146
+ * reused by a later branch keeps its column's hue — coloring is by position, not
1147
+ * branch identity, exactly like `git log --graph`.
1148
+ */
1149
+ function laneColorForColumn(column) {
1150
+ if (column <= 0) return (text) => text;
1151
+ return LANE_COLOR_CYCLE[(column - 1) % LANE_COLOR_CYCLE.length] ?? ((text) => text);
1152
+ }
1153
+ /**
1154
+ * Style a structural glyph by its resolved colour column. Column 0 and the
1155
+ * neutral sentinel render dim (`dimLane`); columns ≥ 1 take a palette hue.
1156
+ */
1157
+ function stylerForLaneColumn(colorColumn, colorize, dimLane) {
1158
+ if (!colorize || colorColumn <= 0) return dimLane;
1159
+ return laneColorForColumn(colorColumn);
1160
+ }
1161
+ /**
1162
+ * Resolve per-cell colour columns for a node/arc row. Scanning right-to-left
1163
+ * lets each arc segment inherit the hue of the arc it leads into.
1164
+ */
1165
+ function resolveRowArcLaneColors(cells) {
1166
+ const lane = new Array(cells.length);
1167
+ const connector = new Array(cells.length);
1168
+ const dash = new Array(cells.length);
1169
+ let arcCorner = 0;
1170
+ let landingAnchor = 0;
1171
+ for (let column = cells.length - 1; column >= 0; column--) {
1172
+ const cell = cells[column];
1173
+ connector[column] = landingAnchor !== 0 ? landingAnchor : arcCorner;
1174
+ switch (cell?.kind) {
1175
+ case "arc-branch-corner":
1176
+ arcCorner = column;
1177
+ lane[column] = column;
1178
+ dash[column] = column;
1179
+ break;
1180
+ case "arc-land-corner":
1181
+ arcCorner = column;
1182
+ landingAnchor = column;
1183
+ lane[column] = column;
1184
+ dash[column] = column;
1185
+ break;
1186
+ case "arc-branch-tee":
1187
+ lane[column] = column;
1188
+ dash[column] = column;
1189
+ break;
1190
+ case "arc-land-tee":
1191
+ lane[column] = column;
1192
+ dash[column] = landingAnchor === 0 ? column : landingAnchor;
1193
+ landingAnchor = column;
1194
+ break;
1195
+ case "arc-crossing":
1196
+ case "arc-land-bridge": {
1197
+ const served = landingAnchor !== 0 ? landingAnchor : arcCorner;
1198
+ lane[column] = served;
1199
+ dash[column] = served;
1200
+ break;
1201
+ }
1202
+ case "horizontal-pass":
1203
+ lane[column] = arcCorner === 0 ? column : arcCorner;
1204
+ dash[column] = lane[column] ?? column;
1205
+ break;
1206
+ case "node":
1207
+ lane[column] = column;
1208
+ dash[column] = column;
1209
+ arcCorner = 0;
1210
+ landingAnchor = 0;
1211
+ break;
1212
+ default:
1213
+ lane[column] = column;
1214
+ dash[column] = column;
1215
+ arcCorner = 0;
1216
+ landingAnchor = 0;
1217
+ }
1218
+ }
1219
+ return {
1220
+ lane,
1221
+ connector,
1222
+ dash
1223
+ };
1224
+ }
1225
+ /**
1226
+ * Resolve per-cell connector colours. Scanning right-to-left, a corner or an
1227
+ * intermediate tee anchors its own lane, but a tee's trailing dash leads into
1228
+ * the branch on its right.
1229
+ */
1230
+ function resolveConnectorLaneColors(cells, startLane) {
1231
+ const glyph = new Array(cells.length);
1232
+ const dash = new Array(cells.length);
1233
+ let owner = 0;
1234
+ for (let column = cells.length - 1; column >= 0; column--) switch (cells[column]?.kind) {
1235
+ case "branch-corner":
1236
+ case "merge-corner":
1237
+ owner = column;
1238
+ glyph[column] = column;
1239
+ dash[column] = column;
1240
+ break;
1241
+ case "branch-tee":
1242
+ case "merge-tee":
1243
+ if (column === startLane) {
1244
+ const served = owner === 0 ? column : owner;
1245
+ glyph[column] = column;
1246
+ dash[column] = served;
1247
+ } else {
1248
+ dash[column] = owner === 0 ? column : owner;
1249
+ glyph[column] = column;
1250
+ owner = column;
1251
+ }
1252
+ break;
1253
+ case "arc-crossing":
1254
+ glyph[column] = column;
1255
+ dash[column] = owner === 0 ? column : owner;
1256
+ owner = column;
1257
+ break;
1258
+ case "horizontal-pass": {
1259
+ const served = owner === 0 ? column : owner;
1260
+ glyph[column] = served;
1261
+ dash[column] = served;
1262
+ break;
1263
+ }
1264
+ default:
1265
+ glyph[column] = column;
1266
+ dash[column] = column;
1267
+ }
1268
+ return {
1269
+ glyph,
1270
+ dash
1271
+ };
1272
+ }
1273
+ function migrationListForwardArrow(glyphMode) {
1274
+ return glyphMode === "ascii" ? "->" : "→";
1275
+ }
1276
+ function migrationListEmptySource(glyphMode) {
1277
+ return glyphMode === "ascii" ? "-" : "∅";
1278
+ }
1279
+ function abbreviateContractHash(hash) {
1280
+ return (hash.startsWith("sha256:") ? hash.slice(7) : hash).slice(0, 7);
1281
+ }
1282
+ function padFromHashColumn(text, width) {
1283
+ const padding = Math.max(0, width - stringWidth(text));
1284
+ return `${" ".repeat(padding)}${text}`;
1285
+ }
1286
+ //#endregion
1287
+ //#region src/utils/formatters/migration-list-render.ts
1288
+ const IDENTITY_MIGRATION_LIST_STYLER = {
1289
+ kind: (text) => text,
1290
+ dirName: (text) => text,
1291
+ sourceHash: (text) => text,
1292
+ destHash: (text) => text,
1293
+ glyph: (text) => text,
1294
+ lane: (text) => text,
1295
+ invariants: (ids) => `{${ids.join(", ")}}`,
1296
+ refs: (names) => `(${names.join(", ")})`,
1297
+ spaceHeading: (text) => text,
1298
+ summary: (text) => text,
1299
+ emptyState: (text) => text
1300
+ };
1301
+ function canonicalFrom(from) {
1302
+ return from ?? EMPTY_CONTRACT_HASH;
1303
+ }
1304
+ function migrationGraphFromListEntries(entries) {
1305
+ const nodes = /* @__PURE__ */ new Set();
1306
+ const forwardChain = /* @__PURE__ */ new Map();
1307
+ const reverseChain = /* @__PURE__ */ new Map();
1308
+ const migrationByHash = /* @__PURE__ */ new Map();
1309
+ for (const entry of entries) {
1310
+ const from = canonicalFrom(entry.from);
1311
+ const edge = {
1312
+ from,
1313
+ to: entry.to,
1314
+ migrationHash: entry.migrationHash,
1315
+ dirName: entry.dirName,
1316
+ createdAt: entry.createdAt,
1317
+ invariants: entry.providedInvariants
1318
+ };
1319
+ nodes.add(from);
1320
+ nodes.add(entry.to);
1321
+ const forward = forwardChain.get(from);
1322
+ if (forward) forward.push(edge);
1323
+ else forwardChain.set(from, [edge]);
1324
+ const reverse = reverseChain.get(entry.to);
1325
+ if (reverse) reverse.push(edge);
1326
+ else reverseChain.set(entry.to, [edge]);
1327
+ migrationByHash.set(entry.migrationHash, edge);
1328
+ }
1329
+ return {
1330
+ nodes,
1331
+ forwardChain,
1332
+ reverseChain,
1333
+ migrationByHash
1334
+ };
1335
+ }
1336
+ function buildEdgeAnnotationsByHashFromListEntries(entries) {
1337
+ const annotations = /* @__PURE__ */ new Map();
1338
+ for (const entry of entries) annotations.set(entry.migrationHash, {
1339
+ operationCount: entry.operationCount,
1340
+ invariants: entry.providedInvariants
1341
+ });
1342
+ return annotations;
1343
+ }
1344
+ function buildRefsByHashFromListEntries(entries) {
1345
+ const refsByHash = /* @__PURE__ */ new Map();
1346
+ for (const entry of entries) if (entry.refs.length > 0) refsByHash.set(entry.to, entry.refs);
1347
+ return refsByHash;
1348
+ }
1349
+ function formatEmptyStateLine(spaceId, style) {
1350
+ return style.emptyState(`There are no migrations in migrations/${spaceId}/ yet`);
1351
+ }
1352
+ function renderSpaceTreeBlock(spaceId, migrations, multiSpace, glyphMode, style, colorize, liveContractHash, graphForSpace, globalMaxEdgeTreePrefixWidth, globalMaxDirNameWidth) {
1353
+ if (migrations.length === 0) {
1354
+ const emptyLine = formatEmptyStateLine(spaceId, style);
1355
+ if (!multiSpace) return [emptyLine];
1356
+ return [style.spaceHeading(`${spaceId}:`), ` ${emptyLine}`];
1357
+ }
1358
+ const treeOutput = renderMigrationGraphSpaceTree({
1359
+ graph: graphForSpace(spaceId) ?? migrationGraphFromListEntries(migrations),
1360
+ migrations,
1361
+ liveContractHash,
1362
+ glyphMode,
1363
+ colorize,
1364
+ refsByHash: buildRefsByHashFromListEntries(migrations),
1365
+ styler: style,
1366
+ ...globalMaxEdgeTreePrefixWidth !== void 0 ? { globalMaxEdgeTreePrefixWidth } : {},
1367
+ ...globalMaxDirNameWidth !== void 0 ? { globalMaxDirNameWidth } : {}
1368
+ });
1369
+ if (!multiSpace) return treeOutput.length === 0 ? [] : [treeOutput];
1370
+ const indented = indentMigrationGraphTreeBlock(treeOutput, " ");
1371
+ return [style.spaceHeading(`${spaceId}:`), indented];
1372
+ }
1373
+ /**
1374
+ * Compose the styled `migration list` human output via the shared tree
1375
+ * renderer. Each on-disk migration is one edge row with package-fact
1376
+ * annotations; refs decorate destination contract nodes.
1377
+ *
1378
+ * `options.colorize` must match whether `style` emits ANSI (e.g. both true for
1379
+ * `createAnsiMigrationListStyler({ useColor: true })`).
1380
+ */
1381
+ function renderMigrationListWithStyle(result, style, glyphMode = "unicode", options = {}) {
1382
+ const multiSpace = result.spaces.length > 1;
1383
+ const colorize = options.colorize ?? false;
1384
+ const liveContractHash = options.liveContractHash ?? EMPTY_CONTRACT_HASH;
1385
+ const graphForSpace = options.graphForSpace ?? (() => void 0);
1386
+ const globalLayoutInputs = multiSpace ? result.spaces.filter((space) => space.migrations.length > 0).map((space) => ({
1387
+ graph: graphForSpace(space.spaceId) ?? migrationGraphFromListEntries(space.migrations),
1388
+ liveContractHash
1389
+ })) : [];
1390
+ const globalMaxEdgeTreePrefixWidth = globalLayoutInputs.length > 0 ? computeGlobalMaxEdgeTreePrefixWidth(globalLayoutInputs) : void 0;
1391
+ const globalMaxDirNameWidth = globalLayoutInputs.length > 0 ? computeGlobalMaxDirNameWidth(globalLayoutInputs) : void 0;
1392
+ const lines = [];
1393
+ for (let index = 0; index < result.spaces.length; index++) {
1394
+ const space = result.spaces[index];
1395
+ if (index > 0) lines.push("");
1396
+ lines.push(...renderSpaceTreeBlock(space.spaceId, space.migrations, multiSpace, glyphMode, style, colorize, liveContractHash, graphForSpace, globalMaxEdgeTreePrefixWidth, globalMaxDirNameWidth));
1397
+ }
1398
+ if (result.spaces.reduce((count, space) => count + space.migrations.length, 0) > 0) {
1399
+ lines.push("");
1400
+ lines.push(style.summary(result.summary));
1401
+ }
1402
+ return lines.join("\n");
1403
+ }
1404
+ //#endregion
1405
+ //#region src/utils/formatters/migration-list-styler.ts
1406
+ function hasMarkersFormatter(styler) {
1407
+ return "markers" in styler && typeof styler.markers === "function";
1408
+ }
1409
+ function styleMarkerName(name) {
1410
+ return name === "contract" ? bold(green(name)) : green(name);
1411
+ }
1412
+ function plainMarkers(names) {
1413
+ return `<${names.join(", ")}>`;
1414
+ }
1415
+ function formatContractNodeOverlays(styler, markers, refs) {
1416
+ const parts = [];
1417
+ if (markers.length > 0) parts.push(hasMarkersFormatter(styler) ? styler.markers(markers) : plainMarkers(markers));
1418
+ if (refs.length > 0) parts.push(styler.refs(refs));
1419
+ return parts.join(" ");
1420
+ }
1421
+ /**
1422
+ * The current contract overlay marker. Unlike user refs, this names the user's
1423
+ * declared desired state — the implicit base/target for `plan` / `migrate` —
1424
+ * not a stored label. It is emphasized (bold) so it stands out from plain refs
1425
+ * (including the live-database `db` marker, which is just another ref).
1426
+ */
1427
+ const CONTRACT_MARKER_NAME = "contract";
1428
+ function styleRefName(name) {
1429
+ return green(name);
1430
+ }
1431
+ /**
1432
+ * Build a {@link MigrationListStyler} that decorates `migration list`
1433
+ * tokens with ANSI SGR codes. When `useColor` is `false` (non-TTY,
1434
+ * `--no-color`, `NO_COLOR=1`, piped output) the function returns the
1435
+ * shared identity styler so callers get plain text with zero ANSI
1436
+ * bytes — pipe-friendly by construction.
1437
+ *
1438
+ * Palette:
1439
+ *
1440
+ * - `dirName`: bold
1441
+ * - `sourceHash`: dim cyan
1442
+ * - `destHash`: bright cyan
1443
+ * - `kind` (`*` / `↩` / `⟲`): bright — the signal; lanes and arrows dim
1444
+ * - `glyph` (`→` / `⟲` / `∅`): dim
1445
+ * - `lane` (graph gutter lines `│` and fan/join connectors `├─┐` / `├─┘`): dim
1446
+ * - `invariants` (`{...}`): yellow
1447
+ * - `markers` (`<...>`): green; the `contract` desired-state marker inside is
1448
+ * green-bold (`db` is plain green)
1449
+ * - `refs` (`(...)`): green (the active ref is bolded separately by the tree styler)
1450
+ * - `spaceHeading` (`<spaceId>:`): bold
1451
+ * - `summary`: dim
1452
+ * - `emptyState`: dim
1453
+ */
1454
+ function createAnsiMigrationListStyler(opts) {
1455
+ if (!opts.useColor) return {
1456
+ ...IDENTITY_MIGRATION_LIST_STYLER,
1457
+ markers: plainMarkers
1458
+ };
1459
+ return {
1460
+ kind: (text) => text,
1461
+ dirName: (text) => bold(text),
1462
+ sourceHash: (text) => dim(cyan(text)),
1463
+ destHash: (text) => cyanBright(text),
1464
+ glyph: (text) => dim(text),
1465
+ lane: (text) => dim(text),
1466
+ invariants: (ids) => yellow(`{${ids.join(", ")}}`),
1467
+ markers: (names) => {
1468
+ const open = green("<");
1469
+ const close = green(">");
1470
+ const separator = green(", ");
1471
+ return open + names.map(styleMarkerName).join(separator) + close;
1472
+ },
1473
+ refs: (names) => {
1474
+ const open = green("(");
1475
+ const close = green(")");
1476
+ const separator = green(", ");
1477
+ return open + names.map(styleRefName).join(separator) + close;
1478
+ },
1479
+ spaceHeading: (text) => bold(text),
1480
+ summary: (text) => dim(text),
1481
+ emptyState: (text) => dim(text)
1482
+ };
1483
+ }
1484
+ //#endregion
1485
+ //#region src/utils/formatters/migration-graph-tree-render.ts
1486
+ const LABEL_GAP = 2;
1487
+ /**
1488
+ * The live-database overlay marker. Just another ref as far as styling goes —
1489
+ * the only emphasized markers are the active ref and the `contract`
1490
+ * desired-state marker (see {@link CONTRACT_MARKER_NAME}).
1491
+ */
1492
+ const DB_MARKER_NAME = "db";
1493
+ const UNICODE_PALETTE = {
1494
+ node: "○ ",
1495
+ arcLand: "○◂",
1496
+ arcTee: "○─",
1497
+ verticalPass: "│ ",
1498
+ branchTee: "├─",
1499
+ mergeTee: "├─",
1500
+ branchCorner: "╮ ",
1501
+ mergeCorner: "╯ ",
1502
+ arcBranchCorner: "╮ ",
1503
+ arcBranchTee: "┬─",
1504
+ arcLandCorner: "╯ ",
1505
+ arcLandTee: "┴─",
1506
+ arcCrossing: "┼─",
1507
+ arcLandBridge: "──",
1508
+ horizontalPass: "──",
1509
+ connectorBranchTee: "├─",
1510
+ connectorBranchTeeCo: "┬─",
1511
+ connectorMergeTeeCo: "┴─",
1512
+ edgeArrow: {
1513
+ forward: "↑",
1514
+ rollback: "↓",
1515
+ self: "⟲"
1516
+ },
1517
+ forwardArrow: migrationListForwardArrow("unicode"),
1518
+ emptySource: migrationListEmptySource("unicode")
1519
+ };
1520
+ const ASCII_PALETTE = {
1521
+ node: "* ",
1522
+ arcLand: "*<",
1523
+ arcTee: "*-",
1524
+ verticalPass: "| ",
1525
+ branchTee: "+-",
1526
+ mergeTee: "+-",
1527
+ branchCorner: "\\ ",
1528
+ mergeCorner: "/ ",
1529
+ arcBranchCorner: "\\ ",
1530
+ arcBranchTee: "+-",
1531
+ arcLandCorner: "/ ",
1532
+ arcLandTee: "+-",
1533
+ arcCrossing: "+-",
1534
+ arcLandBridge: "--",
1535
+ horizontalPass: "--",
1536
+ connectorBranchTee: "+-",
1537
+ connectorBranchTeeCo: "+-",
1538
+ connectorMergeTeeCo: "+-",
1539
+ edgeArrow: {
1540
+ forward: "^",
1541
+ rollback: "v",
1542
+ self: "@"
1543
+ },
1544
+ forwardArrow: migrationListForwardArrow("ascii"),
1545
+ emptySource: migrationListEmptySource("ascii")
1546
+ };
1547
+ function paletteFor(mode) {
1548
+ return mode === "ascii" ? ASCII_PALETTE : UNICODE_PALETTE;
1549
+ }
1550
+ function overlayStatusGlyphs(mode) {
1551
+ return mode === "ascii" ? {
1552
+ applied: "+",
1553
+ pending: ">"
1554
+ } : {
1555
+ applied: "✓",
1556
+ pending: "⧗"
1557
+ };
1558
+ }
1559
+ function arrowForEdgeKind(kind, palette) {
1560
+ return palette.edgeArrow[kind];
1561
+ }
1562
+ /**
1563
+ * Forced bold for branch-coloured names. A branched name pairs its lane hue
1564
+ * (also forced, via {@link laneColorForColumn}) with bold; both must emit even
1565
+ * when colorette's ambient TTY detection is off, so the colorized branch name
1566
+ * is deterministically bold + hue rather than hue-only.
1567
+ */
1568
+ const { bold: forcedBold } = createColors({ useColor: true });
1569
+ function laneStylerForColumn(colorColumn, colorize, style) {
1570
+ return stylerForLaneColumn(colorColumn, colorize, style.lane);
1571
+ }
1572
+ /**
1573
+ * Tint a branch-owned token (direction arrow, migration name) by its edge's
1574
+ * lane so the whole branch row reads in one colour. Column 0 has nothing to be
1575
+ * told apart from in the common linear chain, so it keeps the token's existing
1576
+ * default styling (`fallback`) rather than a palette hue; only lanes ≥ 1 take a
1577
+ * colour. With colour off, the fallback (also colourless) is used unchanged.
1578
+ */
1579
+ function branchStylerOrDefault(column, colorize, fallback) {
1580
+ if (!colorize || column <= 0) return fallback;
1581
+ return laneColorForColumn(column);
1582
+ }
1583
+ /**
1584
+ * Render a crossing tee (`┼─`): the junction stays dim/neutral so neither arc
1585
+ * steals the cell; the trailing dash takes the served lane hue.
1586
+ */
1587
+ function renderArcCrossing(pair, dashColumn, colorize, style) {
1588
+ const junction = colorize ? style.lane : (text) => text;
1589
+ const dash = laneStylerForColumn(dashColumn, colorize, style);
1590
+ return junction(pair.slice(0, 1)) + dash(pair.slice(1));
1591
+ }
1592
+ /**
1593
+ * Render a connector tee (`├─` / `┬─` / `┴─`) with its junction glyph and its
1594
+ * trailing dash coloured independently: the junction anchors its own lane while
1595
+ * the dash leads into the branch on its right.
1596
+ */
1597
+ function renderConnectorTee(pair, glyphColumn, dashColumn, colorize, style) {
1598
+ const glyph = laneStylerForColumn(glyphColumn, colorize, style);
1599
+ if (glyphColumn === dashColumn) return glyph(pair);
1600
+ return glyph(pair.slice(0, 1)) + laneStylerForColumn(dashColumn, colorize, style)(pair.slice(1));
1601
+ }
1602
+ /**
1603
+ * A node-marker glyph pair (`○◂`, `○─`, `*<`, `*-`) is the contract node
1604
+ * marker (`○` / `*`) followed by an arc connector (`◂` / `─` / `<` / `-`). The
1605
+ * marker takes its own lane's hue (so each node visibly belongs to its branch);
1606
+ * the connector follows the arc it belongs to (its owning back-lane hue).
1607
+ * Direction arrows are handled elsewhere — they take their edge's lane hue too.
1608
+ */
1609
+ function renderNodeMarkerPair(pair, nodeColumn, arcColumn, colorize, style) {
1610
+ const marker = laneStylerForColumn(nodeColumn, colorize, style);
1611
+ const connector = laneStylerForColumn(arcColumn, colorize, style);
1612
+ return marker(pair.slice(0, 1)) + connector(pair.slice(1));
1613
+ }
1614
+ function renderCellPair(cell, column, colors, colorize, style, palette) {
1615
+ const laneColumn = colors.lane[column] ?? column;
1616
+ const lane = laneStylerForColumn(laneColumn, colorize, style);
1617
+ switch (cell.kind) {
1618
+ case "node": {
1619
+ const arcColumn = colors.connector[column] ?? 0;
1620
+ if (cell.arcLand === true) return renderNodeMarkerPair(palette.arcLand, column, arcColumn, colorize, style);
1621
+ if (cell.arcTee === true) return renderNodeMarkerPair(palette.arcTee, column, arcColumn, colorize, style);
1622
+ return lane(palette.node);
1623
+ }
1624
+ case "vertical-pass": return lane(palette.verticalPass);
1625
+ case "edge-lane": return cell.ownsLabel ? lane(palette.verticalPass.trimEnd()) + branchStylerOrDefault(column, colorize, style.kind)(arrowForEdgeKind(cell.edgeKind, palette)) : lane(palette.verticalPass);
1626
+ case "branch-tee": return lane(palette.branchTee);
1627
+ case "merge-tee": return lane(palette.mergeTee);
1628
+ case "branch-corner": return lane(palette.branchCorner);
1629
+ case "merge-corner": return lane(palette.mergeCorner);
1630
+ case "arc-branch-corner": return lane(palette.arcBranchCorner);
1631
+ case "arc-branch-tee": return lane(palette.arcBranchTee);
1632
+ case "arc-land-corner": return lane(palette.arcLandCorner);
1633
+ case "arc-land-tee": return renderConnectorTee(palette.arcLandTee, laneColumn, colors.dash[column] ?? laneColumn, colorize, style);
1634
+ case "arc-crossing": return lane(palette.arcLandBridge);
1635
+ case "arc-land-bridge": return lane(palette.arcLandBridge);
1636
+ case "horizontal-pass": return lane(palette.horizontalPass);
1637
+ case "empty": return " ";
1638
+ }
1639
+ }
1640
+ function renderConnectorRow(row, gridWidth, colorize, style, palette) {
1641
+ const isMerge = row.kind === "merge-connector";
1642
+ if (row.cells.length > 0) {
1643
+ const colors = resolveConnectorLaneColors(row.cells, row.startLane ?? 0);
1644
+ let seenTee = false;
1645
+ let out = "";
1646
+ for (let column = 0; column < row.cells.length; column++) {
1647
+ const cell = row.cells[column];
1648
+ if (cell === void 0) continue;
1649
+ const glyphColumn = colors.glyph[column] ?? column;
1650
+ const dashColumn = colors.dash[column] ?? glyphColumn;
1651
+ const lane = laneStylerForColumn(glyphColumn, colorize, style);
1652
+ switch (cell.kind) {
1653
+ case "branch-tee":
1654
+ out += renderConnectorTee(seenTee ? palette.connectorBranchTeeCo : palette.connectorBranchTee, glyphColumn, dashColumn, colorize, style);
1655
+ seenTee = true;
1656
+ break;
1657
+ case "merge-tee":
1658
+ out += renderConnectorTee(seenTee ? palette.connectorMergeTeeCo : palette.connectorBranchTee, glyphColumn, dashColumn, colorize, style);
1659
+ seenTee = true;
1660
+ break;
1661
+ case "branch-corner":
1662
+ out += lane(palette.branchCorner);
1663
+ break;
1664
+ case "merge-corner":
1665
+ out += lane(palette.mergeCorner);
1666
+ break;
1667
+ case "vertical-pass":
1668
+ out += lane(palette.verticalPass);
1669
+ break;
1670
+ case "horizontal-pass":
1671
+ out += lane(palette.horizontalPass);
1672
+ break;
1673
+ case "arc-crossing":
1674
+ out += renderArcCrossing(palette.arcCrossing, dashColumn, colorize, style);
1675
+ break;
1676
+ default: out += " ";
1677
+ }
1678
+ }
1679
+ for (let column = row.cells.length; column < gridWidth; column++) out += " ";
1680
+ return out;
1681
+ }
1682
+ const start = row.startLane ?? 0;
1683
+ const end = row.endLane ?? start;
1684
+ const runLane = laneStylerForColumn(end, colorize, style);
1685
+ let out = "";
1686
+ for (let column = 0; column < gridWidth; column++) if (column < start || column > end) out += " ";
1687
+ else if (column === start) out += runLane(palette.connectorBranchTee);
1688
+ else if (column === end) out += runLane(isMerge ? palette.mergeCorner : palette.branchCorner);
1689
+ else out += runLane(isMerge ? palette.connectorMergeTeeCo : palette.connectorBranchTeeCo);
1690
+ return out;
1691
+ }
1692
+ function abbreviateHash(hash, hashLength, emptySource) {
1693
+ if (hash === EMPTY_CONTRACT_HASH) return emptySource;
1694
+ return (hash.startsWith("sha256:") ? hash.slice(7) : hash).slice(0, hashLength);
1695
+ }
1696
+ const MIN_HASH_DATA_COLUMN = 25;
1697
+ function overlayNamesForContract(contractHash, opts) {
1698
+ const markers = [];
1699
+ const refs = [];
1700
+ const userRefs = opts.refsByHash?.get(contractHash);
1701
+ if (userRefs) refs.push(...[...userRefs].sort((a, b) => a.localeCompare(b)));
1702
+ if (opts.contractHash === contractHash && contractHash !== EMPTY_CONTRACT_HASH) markers.push(CONTRACT_MARKER_NAME);
1703
+ if (opts.dbHash === contractHash) markers.push(DB_MARKER_NAME);
1704
+ markers.sort((a, b) => {
1705
+ if (a === "contract") return -1;
1706
+ if (b === "contract") return 1;
1707
+ return a.localeCompare(b);
1708
+ });
1709
+ return {
1710
+ markers,
1711
+ refs
1712
+ };
1713
+ }
1714
+ function createTreeStyler(opts) {
1715
+ const base = opts.styler ?? createAnsiMigrationListStyler({ useColor: opts.colorize });
1716
+ const activeRefName = opts.activeRefName;
1717
+ if (!opts.colorize || activeRefName === void 0) return base;
1718
+ return {
1719
+ ...base,
1720
+ refs: (names) => {
1721
+ const styledNames = names.map((name) => name === activeRefName ? bold(name) : name);
1722
+ return base.refs(styledNames);
1723
+ }
1724
+ };
1725
+ }
1726
+ function formatEdgeAnnotationSuffix(migrationHash, opts, style) {
1727
+ const annotation = opts.edgeAnnotationsByHash?.get(migrationHash);
1728
+ if (annotation === void 0) return "";
1729
+ const segments = [];
1730
+ if (annotation.operationCount !== void 0) segments.push(`${annotation.operationCount} ops`);
1731
+ if (annotation.invariants !== void 0 && annotation.invariants.length > 0) segments.push(style.invariants(annotation.invariants));
1732
+ const status = annotation.status;
1733
+ if (status !== void 0) {
1734
+ const glyphs = overlayStatusGlyphs(opts.glyphMode ?? "unicode");
1735
+ const glyph = status === "applied" ? glyphs.applied : glyphs.pending;
1736
+ const label = status === "applied" ? "applied" : "pending";
1737
+ if (!opts.colorize) segments.push(`${glyph} ${label}`);
1738
+ else {
1739
+ const styler = status === "applied" ? green : yellow;
1740
+ segments.push(styler(`${glyph} ${label}`));
1741
+ }
1742
+ }
1743
+ if (segments.length === 0) return "";
1744
+ return ` ${segments.join(" ")}`;
1745
+ }
1746
+ function formatEdgeHashColumn(edge, style, hashLength, palette) {
1747
+ if (edge.kind === "self") {
1748
+ const hash = abbreviateHash(edge.from, hashLength, palette.emptySource);
1749
+ return `${padFromHashColumn(style.sourceHash(hash), hashLength)} ${style.glyph(palette.forwardArrow)} ${style.destHash(hash)}`;
1750
+ }
1751
+ return `${edge.from === EMPTY_CONTRACT_HASH ? padFromHashColumn(style.glyph(palette.emptySource), hashLength) : padFromHashColumn(style.sourceHash(abbreviateHash(edge.from, hashLength, palette.emptySource)), hashLength)} ${style.glyph(palette.forwardArrow)} ${style.destHash(abbreviateHash(edge.to, hashLength, palette.emptySource))}`;
1752
+ }
1753
+ function padVisible(text, targetWidth) {
1754
+ const padding = Math.max(0, targetWidth - stringWidth(text));
1755
+ return text + " ".repeat(padding);
1756
+ }
1757
+ const ANSI_ESCAPE = "\x1B";
1758
+ function trimTrailingWhitespace(line) {
1759
+ const trailingSpaceBeforeReset = new RegExp(`[\\t ]+((?:${ANSI_ESCAPE}\\[[0-9;]*m)+)$`);
1760
+ return line.replace(trailingSpaceBeforeReset, "$1").replace(/\s+$/, "");
1761
+ }
1762
+ function gridWidthForModel(rows) {
1763
+ return rows.reduce((max, row) => row.kind === "node" || row.kind === "edge" ? Math.max(max, row.cells.length) : max, 1);
1764
+ }
1765
+ function maxDirNameLength(edges) {
1766
+ if (edges.length === 0) return 0;
1767
+ return Math.max(...edges.map((edge) => edge.dirName.length));
1768
+ }
1769
+ function rowDirNameWidth(labelColumn, maxDirNameLen, dirNameGap) {
1770
+ return Math.max(maxDirNameLen + dirNameGap, MIN_HASH_DATA_COLUMN - labelColumn);
1771
+ }
1772
+ function gridUsesSkipRollbackArcs(rows) {
1773
+ return rows.some((row) => row.cells.some((cell) => cell.kind === "edge-lane" && cell.adjacency === "node-skipping-rollback"));
1774
+ }
1775
+ function edgeLabelColumn(row, wideLabelColumn) {
1776
+ if (wideLabelColumn !== void 0) return wideLabelColumn;
1777
+ const laneIndex = row.laneIndex ?? 0;
1778
+ if (row.edge?.from === EMPTY_CONTRACT_HASH && laneIndex === 0) return (laneIndex + 1) * 2 + LABEL_GAP;
1779
+ return row.cells.some((cell, index) => index > laneIndex && cell.kind === "vertical-pass") ? row.cells.length * 2 + LABEL_GAP : (laneIndex + 1) * 2 + LABEL_GAP;
1780
+ }
1781
+ function maxEdgeTreePrefixWidth(rows, wideLabelColumn) {
1782
+ let max = 0;
1783
+ for (const row of rows) {
1784
+ if (row.kind !== "edge" || row.edge === void 0) continue;
1785
+ max = Math.max(max, edgeLabelColumn(row, wideLabelColumn));
1786
+ }
1787
+ return max;
1788
+ }
1789
+ function computeMaxEdgeTreePrefixWidthForLayout(model) {
1790
+ const wideLabelColumn = gridUsesSkipRollbackArcs(model.rows) ? gridWidthForModel(model.rows) * 2 + 4 : void 0;
1791
+ return maxEdgeTreePrefixWidth(model.rows, wideLabelColumn);
1792
+ }
1793
+ function computeMaxDirNameLengthForLayout(model) {
1794
+ return maxDirNameLength(model.rows.filter((row) => row.kind === "edge" && row.edge !== void 0).map((row) => row.edge));
1795
+ }
1796
+ function nodeHasArcDecoration(row) {
1797
+ return row.cells.some((cell) => cell.kind === "node" && (cell.arcTee === true || cell.arcLand === true));
1798
+ }
1799
+ function renderMigrationGraphTree(model, opts) {
1800
+ const palette = paletteFor(opts.glyphMode ?? "unicode");
1801
+ const style = createTreeStyler(opts);
1802
+ const hashLength = opts.hashLength ?? 7;
1803
+ const gridWidth = gridWidthForModel(model.rows);
1804
+ const wideLabelColumn = gridUsesSkipRollbackArcs(model.rows) ? gridWidth * 2 + 4 : void 0;
1805
+ const dirNameGap = wideLabelColumn !== void 0 ? 3 : LABEL_GAP;
1806
+ const maxDirNameLen = maxDirNameLength(model.rows.filter((row) => row.kind === "edge" && row.edge !== void 0).map((row) => row.edge));
1807
+ const effectiveMaxDirNameLen = opts.globalMaxDirNameWidth ?? maxDirNameLen;
1808
+ const maxEdgePrefixWidth = opts.globalMaxEdgeTreePrefixWidth ?? maxEdgeTreePrefixWidth(model.rows, wideLabelColumn);
1809
+ const edgeDirNameWidth = rowDirNameWidth(maxEdgePrefixWidth, effectiveMaxDirNameLen, dirNameGap);
1810
+ const lines = [];
1811
+ for (let rowIndex = 0; rowIndex < model.rows.length; rowIndex++) {
1812
+ const row = model.rows[rowIndex];
1813
+ if (row === void 0) continue;
1814
+ if (row.kind === "component-separator") {
1815
+ lines.push("");
1816
+ continue;
1817
+ }
1818
+ if (row.kind === "branch-connector" || row.kind === "merge-connector") {
1819
+ lines.push(trimTrailingWhitespace(renderConnectorRow(row, gridWidth, opts.colorize, style, palette)));
1820
+ continue;
1821
+ }
1822
+ const cellColors = resolveRowArcLaneColors(row.cells);
1823
+ let gutter = row.cells.map((cell, column) => renderCellPair(cell, column, cellColors, opts.colorize, style, palette)).join("");
1824
+ let laneSpan = row.cells.length;
1825
+ if (row.kind === "node") if ((row.contractHash ?? EMPTY_CONTRACT_HASH) === EMPTY_CONTRACT_HASH) laneSpan = 1;
1826
+ else {
1827
+ let lastActiveColumn = -1;
1828
+ for (let column = row.cells.length - 1; column >= 0; column--) if (row.cells[column]?.kind !== "empty") {
1829
+ lastActiveColumn = column;
1830
+ break;
1831
+ }
1832
+ laneSpan = lastActiveColumn >= 0 ? lastActiveColumn + 1 : 1;
1833
+ }
1834
+ const labelColumn = row.kind === "edge" ? maxEdgePrefixWidth : wideLabelColumn !== void 0 && (nodeHasArcDecoration(row) || row.contractHash !== void 0) ? wideLabelColumn : laneSpan * 2 + LABEL_GAP;
1835
+ if (row.kind === "edge" && row.edge?.from === EMPTY_CONTRACT_HASH && (row.laneIndex ?? 0) === 0) gutter = row.cells.slice(0, 1).map((cell, column) => renderCellPair(cell, column, cellColors, opts.colorize, style, palette)).join("");
1836
+ else if (row.kind === "node" && laneSpan < row.cells.length && !nodeHasArcDecoration(row)) gutter = row.cells.slice(0, laneSpan).map((cell, column) => renderCellPair(cell, column, cellColors, opts.colorize, style, palette)).join("");
1837
+ else if (gutter.length < laneSpan * 2) gutter = gutter.padEnd(laneSpan * 2, " ");
1838
+ const dirNameWidth = row.kind === "edge" ? edgeDirNameWidth : rowDirNameWidth(labelColumn, maxDirNameLen, dirNameGap);
1839
+ const gutterPad = padVisible(gutter, labelColumn);
1840
+ if (row.kind === "node") {
1841
+ const contractHash = row.contractHash ?? EMPTY_CONTRACT_HASH;
1842
+ if (contractHash === EMPTY_CONTRACT_HASH) {
1843
+ const trailingLanes = row.cells.slice(1).map((cell, offset) => renderCellPair(cell, offset + 1, cellColors, opts.colorize, style, palette)).join("");
1844
+ const emptyGutter = palette.emptySource.padEnd(2, " ") + trailingLanes;
1845
+ const overlays = overlayNamesForContract(contractHash, opts);
1846
+ if (overlays.markers.length === 0 && overlays.refs.length === 0) {
1847
+ lines.push(trimTrailingWhitespace(emptyGutter));
1848
+ continue;
1849
+ }
1850
+ const overlay = formatContractNodeOverlays(style, overlays.markers, overlays.refs);
1851
+ lines.push(trimTrailingWhitespace(`${emptyGutter}${" ".repeat(LABEL_GAP)}${overlay}`));
1852
+ continue;
1853
+ }
1854
+ const hashText = style.sourceHash(abbreviateHash(contractHash, hashLength, palette.emptySource));
1855
+ const overlays = overlayNamesForContract(contractHash, opts);
1856
+ const hasOverlays = overlays.markers.length > 0 || overlays.refs.length > 0;
1857
+ const overlayPad = hasOverlays ? " ".repeat(LABEL_GAP) : "";
1858
+ const overlay = hasOverlays ? formatContractNodeOverlays(style, overlays.markers, overlays.refs) : "";
1859
+ lines.push(trimTrailingWhitespace(`${gutterPad}${hashText}${overlayPad}${overlay}`));
1860
+ continue;
1861
+ }
1862
+ const edge = row.edge;
1863
+ if (edge === void 0) continue;
1864
+ const dirNamePadding = " ".repeat(Math.max(0, dirNameWidth - edge.dirName.length));
1865
+ const laneIndex = row.laneIndex ?? 0;
1866
+ const dirName = `${(opts.colorize && laneIndex > 0 ? (text) => forcedBold(laneColorForColumn(laneIndex)(text)) : style.dirName)(edge.dirName)}${dirNamePadding}`;
1867
+ const hashColumn = formatEdgeHashColumn(edge, style, hashLength, palette);
1868
+ const annotationSuffix = formatEdgeAnnotationSuffix(edge.migrationHash, opts, style);
1869
+ lines.push(trimTrailingWhitespace(`${gutterPad}${dirName}${hashColumn}${annotationSuffix}`));
1870
+ }
1871
+ return lines.join("\n");
1872
+ }
1873
+ function formatLegendExampleMarkers(colorize) {
1874
+ if (!colorize) return "<contract, db>";
1875
+ const open = green("<");
1876
+ const close = green(">");
1877
+ const separator = green(", ");
1878
+ return open + green("contract") + separator + green("db") + close;
1879
+ }
1880
+ /**
1881
+ * A compact key for the tree visual language: the contract node glyph, the
1882
+ * in-lane direction arrows, the empty baseline, the system-marker `<…>` and
1883
+ * user-ref `(…)` bracket conventions (two illustrative example lines), and a
1884
+ * worked sample of the data-column `from → to` migration hash arrow.
1885
+ *
1886
+ * Honors the same glyph palette (unicode vs ASCII) and `colorize` gate as the
1887
+ * tree renderer, so the key matches whatever the graph itself drew and stays
1888
+ * pipe-safe (zero ANSI when color is off). The caller adds the trailing blank
1889
+ * line that separates this stderr key from the tree on stdout.
1890
+ */
1891
+ function renderMigrationGraphLegend(opts) {
1892
+ const palette = paletteFor(opts.glyphMode ?? "unicode");
1893
+ const style = createAnsiMigrationListStyler({ useColor: opts.colorize });
1894
+ const node = palette.node.trimEnd();
1895
+ const sampleArrow = `${style.sourceHash("aaaaaa")} ${style.glyph(palette.forwardArrow)} ${style.destHash("bbbbbb")}`;
1896
+ const statusGlyphs = overlayStatusGlyphs(opts.glyphMode ?? "unicode");
1897
+ const appliedPending = opts.colorize ? ` ${green(statusGlyphs.applied)} ${style.summary("applied")} ${yellow(statusGlyphs.pending)} ${style.summary("pending")}` : ` ${statusGlyphs.applied} ${style.summary("applied")} ${statusGlyphs.pending} ${style.summary("pending")}`;
1898
+ const exampleMarkers = formatLegendExampleMarkers(opts.colorize);
1899
+ const exampleRefs = opts.colorize ? style.refs(["prod", "staging"]) : "(prod, staging)";
1900
+ return [
1901
+ "Legend:",
1902
+ ` ${style.kind(node)} ${style.summary("contract")} ${style.kind(palette.edgeArrow.forward)} ${style.summary("forward")} ${style.kind(palette.edgeArrow.rollback)} ${style.summary("rollback")}`,
1903
+ ` ${style.kind(palette.edgeArrow.self)} ${style.summary("migration without schema change")}`,
1904
+ appliedPending,
1905
+ ` ${style.kind(palette.emptySource)} ${style.summary("empty database (baseline)")}`,
1906
+ ` ${exampleMarkers} ${style.summary("live markers (contract on disk, database state)")}`,
1907
+ ` ${exampleRefs} ${style.summary("user-defined refs")}`,
1908
+ ` ${sampleArrow} ${style.summary("migration from contract aaaaaa to bbbbbb")}`
1909
+ ].join("\n");
1910
+ }
1911
+ //#endregion
1912
+ //#region src/utils/formatters/migration-graph-space-render.ts
1913
+ function mergeMigrationEdgeAnnotations(listOverlay, statusOverlay) {
1914
+ const merged = /* @__PURE__ */ new Map();
1915
+ for (const [migrationHash, listAnnotation] of listOverlay) {
1916
+ const statusAnnotation = statusOverlay.get(migrationHash);
1917
+ merged.set(migrationHash, {
1918
+ ...listAnnotation,
1919
+ ...statusAnnotation?.status !== void 0 ? { status: statusAnnotation.status } : {}
1920
+ });
1921
+ }
1922
+ return merged;
1923
+ }
1924
+ function computeGlobalMaxEdgeTreePrefixWidth(inputs) {
1925
+ let globalMax = 0;
1926
+ for (const input of inputs) {
1927
+ const layout = buildMigrationGraphLayout(buildMigrationGraphRows(input.graph, { contractHash: input.liveContractHash }));
1928
+ globalMax = Math.max(globalMax, computeMaxEdgeTreePrefixWidthForLayout(layout));
1929
+ }
1930
+ return globalMax;
1931
+ }
1932
+ function computeGlobalMaxDirNameWidth(inputs) {
1933
+ let globalMax = 0;
1934
+ for (const input of inputs) {
1935
+ const layout = buildMigrationGraphLayout(buildMigrationGraphRows(input.graph, { contractHash: input.liveContractHash }));
1936
+ globalMax = Math.max(globalMax, computeMaxDirNameLengthForLayout(layout));
1937
+ }
1938
+ return globalMax;
1939
+ }
1940
+ function renderMigrationGraphSpaceTreeInternal(input) {
1941
+ const layout = buildMigrationGraphLayout(buildMigrationGraphRows(input.graph, { contractHash: input.liveContractHash }));
1942
+ const listOverlay = buildEdgeAnnotationsByHashFromListEntries(input.migrations);
1943
+ const edgeAnnotationsByHash = input.statusOverlayByHash === void 0 ? listOverlay : mergeMigrationEdgeAnnotations(listOverlay, input.statusOverlayByHash);
1944
+ return renderMigrationGraphTree(layout, {
1945
+ refsByHash: input.refsByHash ?? buildRefsByHashFromListEntries(input.migrations),
1946
+ contractHash: input.liveContractHash,
1947
+ edgeAnnotationsByHash,
1948
+ colorize: input.colorize,
1949
+ glyphMode: input.glyphMode,
1950
+ ...input.dbHash !== void 0 ? { dbHash: input.dbHash } : {},
1951
+ ...input.styler !== void 0 ? { styler: input.styler } : {},
1952
+ ...input.globalMaxEdgeTreePrefixWidth !== void 0 ? { globalMaxEdgeTreePrefixWidth: input.globalMaxEdgeTreePrefixWidth } : {},
1953
+ ...input.globalMaxDirNameWidth !== void 0 ? { globalMaxDirNameWidth: input.globalMaxDirNameWidth } : {}
1954
+ });
1955
+ }
1956
+ function renderMigrationGraphSpaceTree(input) {
1957
+ return renderMigrationGraphSpaceTreeInternal(input);
1958
+ }
1959
+ function indentMigrationGraphTreeBlock(treeOutput, indent) {
1960
+ if (treeOutput.length === 0) return treeOutput;
1961
+ return treeOutput.split("\n").map((line) => line.length === 0 ? line : `${indent}${line}`).join("\n");
1962
+ }
1963
+ //#endregion
1964
+ export { renderMigrationGraphLegend as a, renderMigrationListWithStyle as c, renderMigrationGraphSpaceTree as i, abbreviateContractHash as l, computeGlobalMaxEdgeTreePrefixWidth as n, createAnsiMigrationListStyler as o, indentMigrationGraphTreeBlock as r, IDENTITY_MIGRATION_LIST_STYLER as s, computeGlobalMaxDirNameWidth as t };
1965
+
1966
+ //# sourceMappingURL=migration-graph-space-render-dmLLWift.mjs.map