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
@@ -1,1081 +0,0 @@
1
- import { ifDefined } from "@prisma-next/utils/defined";
2
- import { bold, cyan, dim, magenta, yellow } from "colorette";
3
- import { EMPTY_CONTRACT_HASH } from "@prisma-next/migration-tools/constants";
4
- import { findPath } from "@prisma-next/migration-tools/migration-graph";
5
- import dagre from "@dagrejs/dagre";
6
- //#region src/utils/formatters/graph-types.ts
7
- /**
8
- * Immutable directed graph with adjacency-list indexing.
9
- *
10
- * Built once from flat arrays of nodes and edges, then passed around as
11
- * the primary graph representation for rendering, traversal, truncation,
12
- * and subgraph extraction.
13
- */
14
- var RenderGraph = class {
15
- nodes;
16
- edges;
17
- /** Forward adjacency: node id → outgoing edges. */
18
- forward;
19
- /** Set of node ids that have at least one incoming edge. */
20
- incomingNodes;
21
- /** Node lookup by id. */
22
- nodeById;
23
- constructor(nodes, edges) {
24
- this.nodes = nodes;
25
- this.edges = edges;
26
- const fwd = /* @__PURE__ */ new Map();
27
- const inc = /* @__PURE__ */ new Set();
28
- const byId = /* @__PURE__ */ new Map();
29
- for (const n of nodes) byId.set(n.id, n);
30
- for (const e of edges) {
31
- const list = fwd.get(e.from);
32
- if (list) list.push(e);
33
- else fwd.set(e.from, [e]);
34
- inc.add(e.to);
35
- }
36
- this.forward = fwd;
37
- this.incomingNodes = inc;
38
- this.nodeById = byId;
39
- }
40
- /** Outgoing edges from a node (empty array if none). */
41
- outgoing(nodeId) {
42
- return this.forward.get(nodeId) ?? [];
43
- }
44
- };
45
- //#endregion
46
- //#region src/utils/formatters/graph-migration-mapper.ts
47
- /**
48
- * Maps MigrationGraph + status info to the generic graph renderer types.
49
- */
50
- const STATUS_ICON = {
51
- applied: " ✓",
52
- pending: " ⧗",
53
- unreachable: " ✗"
54
- };
55
- /** Shorten a contract hash for display: strip sha256: prefix, take 7 chars. */
56
- function shortHash(hash) {
57
- return (hash.startsWith("sha256:") ? hash.slice(7) : hash).slice(0, 7);
58
- }
59
- function toShortId(hash) {
60
- return hash === EMPTY_CONTRACT_HASH ? "∅" : shortHash(hash);
61
- }
62
- /**
63
- * Convert a MigrationGraph + status info into the generic graph renderer types.
64
- */
65
- function migrationGraphToRenderInput(input) {
66
- const { graph, mode, markerHash, contractHash, refs, activeRefHash, edgeStatuses } = input;
67
- const statusByDirName = new Map(edgeStatuses?.map((e) => [e.dirName, e.status]));
68
- const nodeList = [];
69
- for (const nodeId of graph.nodes) {
70
- const markers = [];
71
- if (mode === "online" && markerHash === nodeId) markers.push({ kind: "db" });
72
- if (refs) {
73
- for (const ref of refs) if (ref.hash === nodeId) markers.push({
74
- kind: "ref",
75
- name: ref.name,
76
- active: ref.active
77
- });
78
- }
79
- if (contractHash === nodeId && contractHash !== EMPTY_CONTRACT_HASH) markers.push({
80
- kind: "contract",
81
- planned: true
82
- });
83
- nodeList.push({
84
- id: toShortId(nodeId),
85
- markers: markers.length > 0 ? markers : void 0
86
- });
87
- }
88
- const edgeList = [];
89
- for (const [, entries] of graph.forwardChain) for (const entry of entries) {
90
- const status = statusByDirName.get(entry.dirName);
91
- const icon = status ? STATUS_ICON[status] : "";
92
- const invariantsSuffix = entry.invariants.length > 0 ? ` provides [${entry.invariants.map((id) => JSON.stringify(id)).join(", ")}]` : "";
93
- const label = `${entry.dirName}${icon}${invariantsSuffix}`;
94
- edgeList.push({
95
- from: toShortId(entry.from),
96
- to: toShortId(entry.to),
97
- label,
98
- ...ifDefined("colorHint", status)
99
- });
100
- }
101
- const relevantPaths = [];
102
- const rootId = EMPTY_CONTRACT_HASH;
103
- function addPathFromRoot(targetHash) {
104
- if (!graph.nodes.has(targetHash)) return;
105
- const raw = findPath(graph, rootId, targetHash);
106
- if (raw && raw.length > 0) relevantPaths.push([toShortId(rootId), ...raw.map((e) => toShortId(e.to))]);
107
- }
108
- function addPathBetween(fromHash, toHash) {
109
- /* v8 ignore next -- @preserve */
110
- if (!graph.nodes.has(fromHash) || !graph.nodes.has(toHash)) return;
111
- const raw = findPath(graph, fromHash, toHash);
112
- if (raw && raw.length > 0) relevantPaths.push([toShortId(fromHash), ...raw.map((e) => toShortId(e.to))]);
113
- }
114
- if (mode === "online" && markerHash) addPathFromRoot(markerHash);
115
- if (activeRefHash && activeRefHash !== markerHash) addPathFromRoot(activeRefHash);
116
- if (contractHash !== EMPTY_CONTRACT_HASH) {
117
- let contractReached = false;
118
- if (markerHash && markerHash !== contractHash) {
119
- if (findPath(graph, markerHash, contractHash)) {
120
- addPathBetween(markerHash, contractHash);
121
- contractReached = true;
122
- }
123
- }
124
- if (activeRefHash && activeRefHash !== markerHash && activeRefHash !== contractHash) {
125
- if (findPath(graph, activeRefHash, contractHash)) {
126
- addPathBetween(activeRefHash, contractHash);
127
- contractReached = true;
128
- }
129
- }
130
- if (!contractReached && contractHash !== (markerHash ?? activeRefHash)) addPathFromRoot(contractHash);
131
- }
132
- if (relevantPaths.length === 0) addPathFromRoot([...graph.forwardChain.values()].flat().pop()?.to ?? EMPTY_CONTRACT_HASH);
133
- let spineTargetHash;
134
- if (activeRefHash && graph.nodes.has(activeRefHash)) spineTargetHash = activeRefHash;
135
- else if (contractHash !== EMPTY_CONTRACT_HASH && graph.nodes.has(contractHash)) spineTargetHash = contractHash;
136
- else spineTargetHash = [...graph.forwardChain.values()].flat().pop()?.to ?? EMPTY_CONTRACT_HASH;
137
- if (contractHash !== EMPTY_CONTRACT_HASH && !graph.nodes.has(contractHash)) {
138
- const contractMarkers = [];
139
- if (mode === "online" && markerHash === contractHash) contractMarkers.push({ kind: "db" });
140
- contractMarkers.push({
141
- kind: "contract",
142
- planned: false
143
- });
144
- nodeList.push({
145
- id: shortHash(contractHash),
146
- markers: contractMarkers
147
- });
148
- if (graph.nodes.has(spineTargetHash) || spineTargetHash === EMPTY_CONTRACT_HASH) edgeList.push({
149
- from: toShortId(spineTargetHash),
150
- to: shortHash(contractHash),
151
- style: "dashed"
152
- });
153
- }
154
- return {
155
- graph: new RenderGraph(nodeList, edgeList),
156
- options: {
157
- spineTarget: toShortId(spineTargetHash),
158
- rootId: "∅",
159
- colorize: true
160
- },
161
- relevantPaths
162
- };
163
- }
164
- //#endregion
165
- //#region src/utils/formatters/graph-render.ts
166
- /**
167
- * Terminal graph renderer.
168
- *
169
- * Renders directed graphs as ASCII/box-drawing art for terminal output. Uses
170
- * dagre for automatic layout (rank assignment + coordinate placement), then
171
- * stamps the result onto a {@link CharGrid} — a sparse character canvas that
172
- * resolves box-drawing junctions, color priority, and label placement.
173
- *
174
- * ## Rendering pipeline
175
- *
176
- * 1. **Layout** — dagre assigns (x, y) coordinates to nodes and polyline
177
- * control points to edges. We use `rankdir: 'TB'` (top-to-bottom).
178
- * 2. **Orthogonalization** — dagre's polylines may contain diagonal segments.
179
- * {@link selectBestVariant} resolves each diagonal into an L-shaped bend,
180
- * enumerating all 2^N combinations and picking the variant with fewest
181
- * corners and shortest total length.
182
- * 3. **Edge stamping** — orthogonal segments are stamped onto the CharGrid as
183
- * directional bitmasks. The grid resolves overlapping directions into the
184
- * correct box-drawing character (│, ─, ┌, ┼, etc.).
185
- * 4. **Label placement** — edge labels are placed adjacent to their polyline
186
- * segments, preferring horizontal (branch-specific) segments over shared
187
- * vertical trunks to avoid ambiguity.
188
- * 5. **Arrowheads** — ▾ ▴ ◂ ▸ placed one cell before the terminal point.
189
- * 6. **Node stamping** — `○ nodeId` with inline marker tags (db, contract,
190
- * ref names).
191
- * 7. **Elided indicator** — when truncation is active, `┊ (N earlier
192
- * migrations)` is stamped above the visible root.
193
- * 8. **Detached nodes** — rendered below the graph with `◇` and a dotted
194
- * connector.
195
- *
196
- * ## Graph filtering
197
- *
198
- * The caller controls what graph is rendered: the full graph, or a subgraph
199
- * extracted via {@link extractRelevantSubgraph} (union of relevant paths).
200
- * The renderer itself is agnostic — it renders whatever graph it receives.
201
- *
202
- * Truncation is supported via `options.limit`.
203
- *
204
- * ## Color accessibility
205
- *
206
- * Uses a CVD-safe palette — no red/green contrast. Shape and icon always
207
- * carry meaning; color only reinforces.
208
- */
209
- function segment(from, to) {
210
- return {
211
- from,
212
- to
213
- };
214
- }
215
- function isVertical(seg) {
216
- return seg.from.x === seg.to.x;
217
- }
218
- function manhattanLength(seg) {
219
- return Math.abs(seg.to.x - seg.from.x) + Math.abs(seg.to.y - seg.from.y);
220
- }
221
- /** Rotating palette for ref marker names, cycling through these for each ref. */
222
- const REF_COLORS = [
223
- yellow,
224
- magenta,
225
- bold,
226
- cyan
227
- ];
228
- /** Build the color palette, respecting the `colorize` flag. When false, all color functions become identity. */
229
- function buildColors(colorize) {
230
- const c = (fn) => colorize ? fn : (s) => s;
231
- return {
232
- spine: c(cyan),
233
- branch: c(dim),
234
- backward: c(magenta),
235
- applied: c(cyan),
236
- pending: c(yellow),
237
- unreachable: c(magenta),
238
- node: c(cyan),
239
- label: c(dim),
240
- marker: c(bold),
241
- ref: (index) => c(REF_COLORS[index % REF_COLORS.length])
242
- };
243
- }
244
- /** Map a `colorHint` value to its color function, or `undefined` for no hint. */
245
- function resolveHintColor(hint, colors) {
246
- if (hint === "applied") return colors.applied;
247
- if (hint === "pending") return colors.pending;
248
- if (hint === "unreachable") return colors.unreachable;
249
- }
250
- /**
251
- * Edge drawing priorities — higher priority wins when edges overlap on the
252
- * same grid cell. Backward edges are drawn on top so rollback paths remain
253
- * visible over spine and branch edges.
254
- */
255
- const PRIORITY = {
256
- branch: 1,
257
- spine: 2,
258
- backward: 3
259
- };
260
- const DIR = {
261
- up: 1,
262
- down: 2,
263
- left: 4,
264
- right: 8,
265
- dashed: 16
266
- };
267
- /** Arrow characters for edge termination (one cell before the target node). */
268
- const ARROW = {
269
- up: "▴",
270
- down: "▾",
271
- left: "◂",
272
- right: "▸"
273
- };
274
- /** Maps a direction bitmask to its box-drawing character. */
275
- const BOX_CHAR = {
276
- 0: " ",
277
- [DIR.up]: "│",
278
- [DIR.down]: "│",
279
- [DIR.up | DIR.down]: "│",
280
- [DIR.left]: "─",
281
- [DIR.right]: "─",
282
- [DIR.left | DIR.right]: "─",
283
- [DIR.down | DIR.right]: "┌",
284
- [DIR.down | DIR.left]: "┐",
285
- [DIR.up | DIR.right]: "└",
286
- [DIR.up | DIR.left]: "┘",
287
- [DIR.up | DIR.down | DIR.right]: "├",
288
- [DIR.up | DIR.down | DIR.left]: "┤",
289
- [DIR.left | DIR.right | DIR.down]: "┬",
290
- [DIR.left | DIR.right | DIR.up]: "┴",
291
- [DIR.up | DIR.down | DIR.left | DIR.right]: "┼",
292
- [DIR.up | DIR.dashed]: "┊",
293
- [DIR.down | DIR.dashed]: "┊",
294
- [DIR.up | DIR.down | DIR.dashed]: "┊",
295
- [DIR.left | DIR.dashed]: "┈",
296
- [DIR.right | DIR.dashed]: "┈",
297
- [DIR.left | DIR.right | DIR.dashed]: "┈"
298
- };
299
- /**
300
- * Convert a node's markers into renderable inline tags.
301
- *
302
- * - `db` → `◆ db`
303
- * - `contract` → `◆ contract` (applied) or `◇ contract` (planned)
304
- * - `ref` → the ref name, colored from the rotating {@link REF_COLORS} palette
305
- * - `custom` → the custom label
306
- */
307
- function buildInlineTags(markers, colors) {
308
- const tags = [];
309
- const refNames = markers.filter((m) => m.kind === "ref").map((m) => m.name);
310
- for (const m of markers) if (m.kind === "db") tags.push({
311
- text: "◆ db",
312
- color: colors.marker
313
- });
314
- else if (m.kind === "contract") tags.push({
315
- text: m.planned ? "◆ contract" : "◇ contract",
316
- color: colors.marker
317
- });
318
- else if (m.kind === "ref") tags.push({
319
- text: m.name,
320
- color: colors.ref(refNames.indexOf(m.name))
321
- });
322
- else if (m.kind === "custom") tags.push({
323
- text: m.label,
324
- color: colors.marker
325
- });
326
- return tags;
327
- }
328
- /** Total character width of inline tags including leading spaces (0 if no tags). */
329
- function inlineTagsWidth(tags) {
330
- if (tags.length === 0) return 0;
331
- return tags.reduce((w, t) => w + 1 + t.text.length, 0);
332
- }
333
- /**
334
- * Sparse character canvas for terminal graph rendering.
335
- *
336
- * Coordinates are unbounded integers — the grid auto-expands as content is
337
- * added and trims to the bounding box on {@link render}.
338
- */
339
- var CharGrid = class {
340
- connections = /* @__PURE__ */ new Map();
341
- cellColors = /* @__PURE__ */ new Map();
342
- chars = /* @__PURE__ */ new Map();
343
- reserved = /* @__PURE__ */ new Set();
344
- minX = Number.POSITIVE_INFINITY;
345
- maxX = Number.NEGATIVE_INFINITY;
346
- minY = Number.POSITIVE_INFINITY;
347
- maxY = Number.NEGATIVE_INFINITY;
348
- key(x, y) {
349
- return `${x},${y}`;
350
- }
351
- /** Expand the bounding box to include (x, y). */
352
- touch(x, y) {
353
- if (x < this.minX) this.minX = x;
354
- if (x > this.maxX) this.maxX = x;
355
- if (y < this.minY) this.minY = y;
356
- if (y > this.maxY) this.maxY = y;
357
- }
358
- /**
359
- * Add a directional connection at (x, y). Multiple calls at the same cell
360
- * are OR'd together — e.g. `addConnection(x, y, UP)` then
361
- * `addConnection(x, y, RIGHT)` produces a └ corner. Color follows
362
- * priority: higher-priority edges win at shared cells.
363
- */
364
- addConnection(x, y, dir, color, priority = PRIORITY.branch) {
365
- this.touch(x, y);
366
- const k = this.key(x, y);
367
- this.connections.set(k, (this.connections.get(k) ?? 0) | dir);
368
- const existing = this.cellColors.get(k);
369
- if (!existing || priority >= existing.priority) this.cellColors.set(k, {
370
- color,
371
- priority
372
- });
373
- }
374
- /** Stamp a horizontal edge segment from x1 to x2 at row y. */
375
- markHorizontal(y, x1, x2, color, priority, extraBits = 0) {
376
- const lo = Math.min(x1, x2);
377
- const hi = Math.max(x1, x2);
378
- /* v8 ignore next -- @preserve */
379
- if (lo === hi) return;
380
- this.addConnection(lo, y, DIR.right | extraBits, color, priority);
381
- for (let x = lo + 1; x < hi; x++) this.addConnection(x, y, DIR.left | DIR.right | extraBits, color, priority);
382
- this.addConnection(hi, y, DIR.left | extraBits, color, priority);
383
- }
384
- /** Stamp a vertical edge segment from y1 to y2 at column x. */
385
- markVertical(x, y1, y2, color, priority, extraBits = 0) {
386
- const lo = Math.min(y1, y2);
387
- const hi = Math.max(y1, y2);
388
- /* v8 ignore next -- @preserve */
389
- if (lo === hi) return;
390
- this.addConnection(x, lo, DIR.down | extraBits, color, priority);
391
- for (let y = lo + 1; y < hi; y++) this.addConnection(x, y, DIR.up | DIR.down | extraBits, color, priority);
392
- this.addConnection(x, hi, DIR.up | extraBits, color, priority);
393
- }
394
- /** Place literal text at (x, y). Each character occupies one cell. Text stamps override connections. */
395
- stampText(x, y, text, color) {
396
- for (let i = 0; i < text.length; i++) {
397
- const cx = x + i;
398
- this.touch(cx, y);
399
- this.chars.set(this.key(cx, y), {
400
- ch: text[i],
401
- color
402
- });
403
- }
404
- }
405
- /** True if (x, y) has stamped text or is in a reserved area (node labels). */
406
- hasLabel(x, y) {
407
- return this.chars.has(this.key(x, y)) || this.reserved.has(this.key(x, y));
408
- }
409
- /** True if (x, y) has any directional connection (an edge passes through). */
410
- hasConnection(x, y) {
411
- return (this.connections.get(this.key(x, y)) ?? 0) !== 0;
412
- }
413
- /** True if (x, y) has stamped text (not just a reserved area). */
414
- hasText(x, y) {
415
- return this.chars.has(this.key(x, y));
416
- }
417
- /** Reserve a horizontal span so label placement avoids it. Used for node id + marker regions. */
418
- reserveArea(x, y, width) {
419
- for (let i = 0; i < width; i++) this.reserved.add(this.key(x + i, y));
420
- }
421
- /** The largest y coordinate with content — used for positioning detached nodes below the graph. */
422
- getMaxY() {
423
- return this.maxY;
424
- }
425
- /**
426
- * Render the grid to a multi-line string.
427
- *
428
- * Iterates row by row over the bounding box, resolving each cell to either
429
- * its stamped text character or the box-drawing character for its
430
- * connection bitmask. Consecutive characters with the same color are
431
- * batched into a single ANSI-wrapped run for efficiency.
432
- */
433
- render() {
434
- /* v8 ignore next -- @preserve */
435
- if (this.minX === Number.POSITIVE_INFINITY) return "(empty)";
436
- const rows = [];
437
- for (let y = this.minY; y <= this.maxY; y++) {
438
- let row = "";
439
- let runChars = "";
440
- let runColor;
441
- const flush = () => {
442
- if (runChars.length === 0) return;
443
- row += runColor ? runColor(runChars) : runChars;
444
- runChars = "";
445
- };
446
- for (let x = this.minX; x <= this.maxX; x++) {
447
- const k = this.key(x, y);
448
- let ch;
449
- let color;
450
- const label = this.chars.get(k);
451
- if (label) {
452
- ch = label.ch;
453
- color = label.color;
454
- } else {
455
- const conn = this.connections.get(k) ?? 0;
456
- ch = BOX_CHAR[conn] ?? BOX_CHAR[conn & ~DIR.dashed] ?? " ";
457
- color = conn === 0 ? void 0 : this.cellColors.get(k)?.color;
458
- }
459
- if (color !== runColor) {
460
- flush();
461
- runColor = color;
462
- }
463
- runChars += ch;
464
- }
465
- flush();
466
- rows.push(row.trimEnd());
467
- }
468
- while (rows.length > 0 && rows[rows.length - 1] === "") rows.pop();
469
- return rows.join("\n");
470
- }
471
- };
472
- /**
473
- * Find the set of edge keys (`"from→to"`) on the shortest path from
474
- * `rootId` to `targetId`. Used to color spine edges distinctly from
475
- * branch edges in the rendered output.
476
- *
477
- * Returns an empty set if no path exists.
478
- */
479
- function findSpineEdges(graph, rootId, targetId) {
480
- const visited = new Set([rootId]);
481
- const parent = /* @__PURE__ */ new Map();
482
- const queue = [rootId];
483
- while (queue.length > 0) {
484
- const current = queue.shift();
485
- if (current === targetId) {
486
- const spineEdges = /* @__PURE__ */ new Set();
487
- let node = targetId;
488
- while (parent.has(node)) {
489
- const edge = parent.get(node);
490
- spineEdges.add(`${edge.from}→${edge.to}`);
491
- node = edge.from;
492
- }
493
- return spineEdges;
494
- }
495
- for (const edge of graph.outgoing(current)) if (!visited.has(edge.to)) {
496
- visited.add(edge.to);
497
- parent.set(edge.to, edge);
498
- queue.push(edge.to);
499
- }
500
- }
501
- return /* @__PURE__ */ new Set();
502
- }
503
- /**
504
- * Prepend `src` and append `tgt` to dagre's control points, round to
505
- * integers, and deduplicate consecutive identical points.
506
- */
507
- function prepareRawPoints(src, dagrePoints, tgt) {
508
- const rounded = [
509
- src,
510
- ...dagrePoints,
511
- tgt
512
- ].map((p) => ({
513
- x: Math.round(p.x),
514
- y: Math.round(p.y)
515
- }));
516
- const deduped = [rounded[0]];
517
- for (let i = 1; i < rounded.length; i++) {
518
- const prev = deduped[deduped.length - 1];
519
- const curr = rounded[i];
520
- if (curr.x !== prev.x || curr.y !== prev.y) deduped.push(curr);
521
- }
522
- return deduped;
523
- }
524
- function countDiagonals(points) {
525
- let count = 0;
526
- for (let i = 1; i < points.length; i++) {
527
- const prev = points[i - 1];
528
- const curr = points[i];
529
- if (prev.x !== curr.x && prev.y !== curr.y) count++;
530
- }
531
- return count;
532
- }
533
- /**
534
- * Decode a bitmask into an array of bend directions.
535
- *
536
- * Each bit selects how one diagonal is converted to an orthogonal corner:
537
- * 0 → horizontal-first, 1 → vertical-first. Used by {@link selectBestVariant}
538
- * to enumerate all 2^N combinations.
539
- */
540
- function bitsToBends(bits, count) {
541
- const bends = [];
542
- for (let k = 0; k < count; k++) bends.push(bits >> k & 1 ? "vertical-first" : "horizontal-first");
543
- return bends;
544
- }
545
- /**
546
- * Build one polyline variant by resolving each diagonal with the given bend direction.
547
- *
548
- * Diagonals are detected inline: when the last emitted point and the next
549
- * input point differ in both x and y, the segment is diagonal and is
550
- * resolved using the next value from `bends`. The result is deduplicated
551
- * to remove zero-length segments created when a bend coincides with an
552
- * adjacent point.
553
- */
554
- function buildVariant(points, bends) {
555
- /* v8 ignore next -- @preserve */
556
- if (points.length < 2) return points;
557
- let bendIdx = 0;
558
- const result = [points[0]];
559
- for (let i = 1; i < points.length; i++) {
560
- const prev = result[result.length - 1];
561
- const curr = points[i];
562
- if (prev.x === curr.x || prev.y === curr.y) result.push(curr);
563
- else {
564
- if ((bends[bendIdx++] ?? "horizontal-first") === "horizontal-first") result.push({
565
- x: curr.x,
566
- y: prev.y
567
- });
568
- else result.push({
569
- x: prev.x,
570
- y: curr.y
571
- });
572
- result.push(curr);
573
- }
574
- }
575
- const final = [result[0]];
576
- for (let i = 1; i < result.length; i++) {
577
- const prev = final[final.length - 1];
578
- const curr = result[i];
579
- if (curr.x !== prev.x || curr.y !== prev.y) final.push(curr);
580
- }
581
- return final;
582
- }
583
- /** Count the number of direction changes (corners) in an orthogonal polyline. */
584
- function countCorners(poly) {
585
- let corners = 0;
586
- for (let i = 1; i < poly.length - 1; i++) {
587
- const a = poly[i - 1];
588
- const b = poly[i];
589
- const c = poly[i + 1];
590
- if (a.x === b.x !== (b.x === c.x)) corners++;
591
- }
592
- return corners;
593
- }
594
- /** Manhattan length of a polyline (sum of absolute x and y deltas). */
595
- function polyLength(poly) {
596
- let len = 0;
597
- for (let i = 0; i < poly.length - 1; i++) len += Math.abs(poly[i + 1].x - poly[i].x) + Math.abs(poly[i + 1].y - poly[i].y);
598
- return len;
599
- }
600
- /**
601
- * Find the best (x, y) position to place an edge label adjacent to its
602
- * polyline. Returns null if no collision-free position exists.
603
- *
604
- * @param poly - The orthogonalized polyline for the edge.
605
- * @param label - The label text to place.
606
- * @param grid - The character grid (used for collision checks).
607
- * @param srcY - Y coordinate of the source node (for adjacency penalty).
608
- */
609
- function findLabelPlacement(poly, label, grid, srcY) {
610
- const segments = polyToSegments(poly);
611
- let best;
612
- for (const seg of segments) {
613
- const candidates = segmentLabelCandidates(seg, label.length);
614
- for (const pos of candidates) {
615
- if (labelCollides(grid, pos.x, pos.y, label)) continue;
616
- const score = scoreLabelCandidate(pos, seg, segments, label, grid, srcY);
617
- if (!best || score > best.score) best = {
618
- x: pos.x,
619
- y: pos.y,
620
- score
621
- };
622
- }
623
- }
624
- return best;
625
- }
626
- /** Convert a polyline into non-zero-length segments. */
627
- function polyToSegments(poly) {
628
- const segments = [];
629
- for (let i = 0; i < poly.length - 1; i++) {
630
- const seg = segment(poly[i], poly[i + 1]);
631
- if (manhattanLength(seg) > 0) segments.push(seg);
632
- }
633
- return segments;
634
- }
635
- /**
636
- * Generate all candidate (x, y) positions for placing a label adjacent
637
- * to a single segment. Positions are perpendicular to the segment:
638
- *
639
- * - Vertical segments: left and right, at every y along the segment.
640
- * - Horizontal segments: above and below, at every x where the label fits.
641
- */
642
- function segmentLabelCandidates(seg, labelLen) {
643
- const candidates = [];
644
- if (isVertical(seg)) {
645
- const minY = Math.min(seg.from.y, seg.to.y);
646
- const maxY = Math.max(seg.from.y, seg.to.y);
647
- for (const x of [seg.from.x + 2, seg.from.x - labelLen - 1]) for (let y = minY; y <= maxY; y++) candidates.push({
648
- x,
649
- y
650
- });
651
- } else {
652
- const minX = Math.min(seg.from.x, seg.to.x);
653
- const maxX = Math.max(seg.from.x, seg.to.x);
654
- for (const dy of [-1, 1]) {
655
- const y = seg.from.y + dy;
656
- for (let x = minX; x <= maxX - labelLen + 1; x++) candidates.push({
657
- x,
658
- y
659
- });
660
- }
661
- }
662
- return candidates;
663
- }
664
- /**
665
- * Score a candidate label position. Higher is better.
666
- *
667
- * Combines: segment length, surrounding whitespace, distance from
668
- * segment midpoint, source-node proximity penalty, and segment-position
669
- * bonus (horizontal/later segments preferred when the edge has bends).
670
- *
671
- * @param pos - Candidate position (top-left corner of the label text).
672
- * @param seg - The segment this candidate is adjacent to.
673
- * @param allSegments - All segments of the edge polyline (for segment-position bonus).
674
- * @param label - The label text (used for width and whitespace probing).
675
- * @param grid - The character grid (used for whitespace checks).
676
- * @param srcY - Y coordinate of the edge's source node (penalizes labels
677
- * that would appear to belong to the node rather than the edge).
678
- */
679
- function scoreLabelCandidate(pos, seg, allSegments, label, grid, srcY) {
680
- const len = manhattanLength(seg);
681
- const midX = Math.round((seg.from.x + seg.to.x) / 2);
682
- const midY = Math.round((seg.from.y + seg.to.y) / 2);
683
- let score = len;
684
- for (let dy = 1; dy <= 2; dy++) {
685
- if (!rowHasContent(grid, pos.x, pos.y - dy, label.length)) score += 3;
686
- if (!rowHasContent(grid, pos.x, pos.y + dy, label.length)) score += 3;
687
- }
688
- const labelCenterX = pos.x + Math.floor(label.length / 2);
689
- score -= (Math.abs(labelCenterX - midX) + Math.abs(pos.y - midY)) * 2;
690
- const labelCenterY = pos.y + Math.floor(label.length / 2);
691
- score -= (Math.abs(labelCenterY - midY) + Math.abs(pos.x - midX)) * 2;
692
- if (isVertical(seg) && pos.x > seg.from.x) score += 10;
693
- if (srcY !== void 0 && Math.abs(pos.y - srcY) <= 1) score -= 20;
694
- if (allSegments.some((s) => !isVertical(s))) {
695
- if (!isVertical(seg)) score += 15;
696
- const segIndex = allSegments.indexOf(seg);
697
- score += segIndex / allSegments.length * 5;
698
- }
699
- return score;
700
- }
701
- /** True if any cell in the horizontal span [x, x+width) at row y has content. */
702
- function rowHasContent(grid, x, y, width) {
703
- for (let i = 0; i < width; i++) if (grid.hasLabel(x + i, y) || grid.hasConnection(x + i, y)) return true;
704
- return false;
705
- }
706
- /**
707
- * Check if placing `text` at (x, y) would collide with existing content.
708
- * Checks one cell of padding on each side to keep labels visually separated.
709
- */
710
- function labelCollides(grid, x, y, text) {
711
- for (let i = -1; i <= text.length; i++) {
712
- const cx = x + i;
713
- if (grid.hasLabel(cx, y)) return true;
714
- if (i >= 0 && i < text.length && grid.hasConnection(cx, y)) return true;
715
- }
716
- return false;
717
- }
718
- /**
719
- * Resolve dagre's polyline into the best orthogonal variant and find the
720
- * optimal label position in a single pass.
721
- *
722
- * Enumerates all 2^N diagonal resolutions, scores each by:
723
- * - `corners * 10` — fewer corners preferred
724
- * - `+ manhattan length` — shorter paths preferred
725
- * - `+ 100` penalty if the label couldn't be placed
726
- *
727
- * For edges with no diagonals, the polyline is used as-is.
728
- */
729
- function selectBestVariant(src, dagrePoints, tgt, label, grid) {
730
- const rawPoints = prepareRawPoints(src, dagrePoints, tgt);
731
- const diagCount = countDiagonals(rawPoints);
732
- if (diagCount === 0) {
733
- const poly = buildVariant(rawPoints, []);
734
- return {
735
- poly,
736
- labelPos: label ? findLabelPlacement(poly, label, grid, src.y) : void 0
737
- };
738
- }
739
- const numVariants = 1 << diagCount;
740
- let bestPoly = null;
741
- let bestLabel;
742
- let bestScore = Number.POSITIVE_INFINITY;
743
- for (let bits = 0; bits < numVariants; bits++) {
744
- const poly = buildVariant(rawPoints, bitsToBends(bits, diagCount));
745
- const corners = countCorners(poly);
746
- const len = polyLength(poly);
747
- const labelPos = label ? findLabelPlacement(poly, label, grid, src.y) : void 0;
748
- const labelPenalty = label && !labelPos ? 100 : 0;
749
- const score = corners * 10 + len + labelPenalty;
750
- if (score < bestScore) {
751
- bestScore = score;
752
- bestPoly = poly;
753
- bestLabel = labelPos;
754
- }
755
- }
756
- return {
757
- poly: bestPoly ?? buildVariant(rawPoints, bitsToBends(0, diagCount)),
758
- labelPos: bestLabel
759
- };
760
- }
761
- /**
762
- * Extract the subgraph covering the union of multiple paths.
763
- *
764
- * Each path is an ordered list of node ids (root → target). The result
765
- * contains every node on any path plus every forward edge between
766
- * consecutive nodes on any path. Detached nodes are always included.
767
- *
768
- * When all paths overlap (the common case), the result is identical to
769
- * a single-path extract. When paths diverge (e.g. DB marker on a
770
- * different branch than the contract), the result naturally includes the
771
- * fork and both branches — exactly the minimal information needed.
772
- */
773
- function extractRelevantSubgraph(graph, paths) {
774
- const nodeSet = /* @__PURE__ */ new Set();
775
- const edgePairs = /* @__PURE__ */ new Set();
776
- for (const path of paths) for (let i = 0; i < path.length; i++) {
777
- nodeSet.add(path[i]);
778
- if (i > 0) edgePairs.add(`${path[i - 1]}\0${path[i]}`);
779
- }
780
- const dashedEdges = graph.edges.filter((e) => e.style === "dashed");
781
- for (const e of dashedEdges) {
782
- nodeSet.add(e.from);
783
- nodeSet.add(e.to);
784
- }
785
- return new RenderGraph(graph.nodes.filter((n) => nodeSet.has(n.id)), graph.edges.filter((e) => edgePairs.has(`${e.from}\0${e.to}`) || e.style === "dashed"));
786
- }
787
- /**
788
- * Truncate a graph to the last `limit` spine edges from the spine target.
789
- * The window expands to include any node carrying a db or contract marker
790
- * so those are never truncated away.
791
- *
792
- * For the full graph: keeps all branches that fork from the visible spine window.
793
- * For the spine view: caller should call extractSubgraph first, then truncate.
794
- */
795
- function truncateGraph(graph, spine, limit) {
796
- if (spine.length <= 1 || limit >= spine.length - 1) return {
797
- graph,
798
- elidedCount: 0,
799
- spine
800
- };
801
- let earliestMarkerIdx = spine.length;
802
- for (let i = 0; i < spine.length; i++) if (graph.nodeById.get(spine[i])?.markers?.some((m) => m.kind === "db" || m.kind === "contract")) {
803
- earliestMarkerIdx = i;
804
- break;
805
- }
806
- const markerDistance = spine.length - 1 - earliestMarkerIdx;
807
- const effectiveEdges = Math.max(limit, markerDistance);
808
- if (effectiveEdges >= spine.length - 1) return {
809
- graph,
810
- elidedCount: 0,
811
- spine
812
- };
813
- const keepFromIdx = spine.length - 1 - effectiveEdges;
814
- const truncatedSpine = spine.slice(keepFromIdx);
815
- const visibleSpineSet = new Set(truncatedSpine);
816
- const reachable = new Set(visibleSpineSet);
817
- const queue = [...truncatedSpine];
818
- while (queue.length > 0) {
819
- const current = queue.shift();
820
- for (const edge of graph.outgoing(current)) if (!reachable.has(edge.to)) {
821
- reachable.add(edge.to);
822
- queue.push(edge.to);
823
- }
824
- }
825
- const truncatedNodes = graph.nodes.filter((n) => reachable.has(n.id));
826
- const truncatedEdges = graph.edges.filter((e) => reachable.has(e.from) && reachable.has(e.to));
827
- const elidedCount = spine.length - 1 - effectiveEdges;
828
- return {
829
- graph: new RenderGraph(truncatedNodes, truncatedEdges),
830
- elidedCount,
831
- spine: truncatedSpine
832
- };
833
- }
834
- /**
835
- * After truncation the original root may not be in the visible graph.
836
- * Find the first node with no incoming edges as a fallback root.
837
- */
838
- function findVisibleRoot(graph, layoutNodes) {
839
- return layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id ?? "∅";
840
- }
841
- /**
842
- * The main rendering pipeline: dagre layout → edge stamping → label
843
- * placement → arrowheads → nodes → elided indicator → detached nodes.
844
- *
845
- * Called by {@link render} after optional truncation. Receives nodes/edges
846
- * and produces the final multi-line string.
847
- *
848
- * @param graph - The graph to render (may include detached nodes, which are
849
- * rendered below the main graph rather than laid out by dagre).
850
- * @param options - Render options (rootId, spineTarget, colorize).
851
- * @param elidedCount - If > 0, a `┊ (N earlier migrations)` indicator
852
- * is stamped above the visible root node.
853
- */
854
- function layoutAndRender(graph, options, elidedCount = 0) {
855
- const colors = buildColors(options.colorize ?? true);
856
- const layoutNodes = graph.nodes;
857
- const layoutNodeIds = new Set(layoutNodes.map((n) => n.id));
858
- const requestedRoot = options.rootId ?? layoutNodes[0]?.id ?? "∅";
859
- const spineEdgeKeys = findSpineEdges(graph, layoutNodeIds.has(requestedRoot) ? requestedRoot : findVisibleRoot(graph, layoutNodes), options.spineTarget);
860
- const g = new dagre.graphlib.Graph({ multigraph: true });
861
- g.setGraph({
862
- rankdir: "TB",
863
- ranksep: 4,
864
- nodesep: 6,
865
- marginx: 2,
866
- marginy: 1,
867
- ...options.dagreOptions
868
- });
869
- g.setDefaultEdgeLabel(() => ({}));
870
- for (const node of layoutNodes) {
871
- const tagWidth = inlineTagsWidth(buildInlineTags(node.markers ?? [], colors));
872
- g.setNode(node.id, {
873
- width: node.id.length + 6 + tagWidth,
874
- height: 1
875
- });
876
- }
877
- const edgeNames = [];
878
- for (let i = 0; i < graph.edges.length; i++) {
879
- const edge = graph.edges[i];
880
- const name = `e${i}`;
881
- edgeNames.push(name);
882
- g.setEdge(edge.from, edge.to, { label: edge.label ?? "" }, name);
883
- }
884
- dagre.layout(g);
885
- const nodePos = /* @__PURE__ */ new Map();
886
- for (const id of g.nodes()) {
887
- const n = g.node(id);
888
- nodePos.set(id, {
889
- x: Math.round(n.x),
890
- y: Math.round(n.y)
891
- });
892
- }
893
- const grid = new CharGrid();
894
- for (const node of layoutNodes) {
895
- const pos = nodePos.get(node.id);
896
- /* v8 ignore next -- @preserve */
897
- if (!pos) continue;
898
- const tagWidth = inlineTagsWidth(buildInlineTags(node.markers ?? [], colors));
899
- grid.reserveArea(pos.x - 1, pos.y, node.id.length + 4 + tagWidth);
900
- }
901
- const edgeEntries = [];
902
- for (let i = 0; i < graph.edges.length; i++) {
903
- const edge = graph.edges[i];
904
- const name = edgeNames[i];
905
- if (!name || !nodePos.has(edge.from) || !nodePos.has(edge.to)) continue;
906
- const src = nodePos.get(edge.from);
907
- const tgt = nodePos.get(edge.to);
908
- const dagrePoints = g.edge({
909
- v: edge.from,
910
- w: edge.to,
911
- name
912
- })?.points ?? [];
913
- const isBackward = tgt.y < src.y;
914
- const isSpine = spineEdgeKeys.has(`${edge.from}→${edge.to}`);
915
- const role = isBackward ? "backward" : isSpine ? "spine" : "branch";
916
- const edgeColor = resolveHintColor(edge.colorHint, colors) ?? (role === "backward" ? colors.backward : role === "spine" ? colors.spine : colors.branch);
917
- const priority = role === "backward" ? PRIORITY.backward : role === "spine" ? PRIORITY.spine : PRIORITY.branch;
918
- edgeEntries.push({
919
- idx: i,
920
- edge,
921
- dagrePoints,
922
- src,
923
- tgt,
924
- role,
925
- edgeColor,
926
- priority
927
- });
928
- }
929
- const drawnEdges = [];
930
- for (const entry of edgeEntries) {
931
- const { edge, dagrePoints, src, tgt, edgeColor, priority } = entry;
932
- const { poly } = selectBestVariant(src, dagrePoints, tgt, edge.label, grid);
933
- const dashedBit = edge.style === "dashed" ? DIR.dashed : 0;
934
- for (let j = 0; j < poly.length - 1; j++) {
935
- const a = poly[j];
936
- const b = poly[j + 1];
937
- if (a.y === b.y) grid.markHorizontal(a.y, a.x, b.x, edgeColor, priority, dashedBit);
938
- else if (a.x === b.x) grid.markVertical(a.x, a.y, b.y, edgeColor, priority, dashedBit);
939
- }
940
- drawnEdges.push({
941
- edge,
942
- poly,
943
- role: entry.role,
944
- srcY: src.y
945
- });
946
- }
947
- const labelOrder = [...drawnEdges].map((de, i) => ({
948
- ...de,
949
- i
950
- })).filter((de) => de.edge.label).sort((a, b) => (b.edge.label?.length ?? 0) - (a.edge.label?.length ?? 0));
951
- for (const { edge, poly, role, srcY } of labelOrder) {
952
- /* v8 ignore next -- @preserve */
953
- if (!edge.label) continue;
954
- const labelPos = findLabelPlacement(poly, edge.label, grid, srcY);
955
- if (labelPos) {
956
- const labelColor = resolveHintColor(edge.colorHint, colors) ?? (role === "backward" ? colors.backward : role === "spine" ? colors.spine : colors.label);
957
- grid.stampText(labelPos.x, labelPos.y, edge.label, labelColor);
958
- }
959
- }
960
- for (const { edge, poly, role } of drawnEdges) {
961
- /* v8 ignore next -- @preserve */
962
- if (poly.length < 2) continue;
963
- const last = poly[poly.length - 1];
964
- const prev = poly[poly.length - 2];
965
- const edgeColor = resolveHintColor(edge.colorHint, colors) ?? (role === "backward" ? colors.backward : role === "spine" ? colors.spine : colors.branch);
966
- let ax;
967
- let ay;
968
- let arrow;
969
- if (prev.x === last.x) if (last.y > prev.y) {
970
- ax = last.x;
971
- ay = last.y - 1;
972
- arrow = ARROW.down;
973
- } else {
974
- ax = last.x;
975
- ay = last.y + 1;
976
- arrow = ARROW.up;
977
- }
978
- else if (last.x > prev.x) {
979
- ax = last.x - 1;
980
- ay = last.y;
981
- arrow = ARROW.right;
982
- } else {
983
- ax = last.x + 1;
984
- ay = last.y;
985
- arrow = ARROW.left;
986
- }
987
- if (ax !== void 0 && ay !== void 0 && arrow && !grid.hasText(ax, ay)) grid.stampText(ax, ay, arrow, edgeColor);
988
- }
989
- const spineNodeIds = /* @__PURE__ */ new Set();
990
- for (const key of spineEdgeKeys) {
991
- const [from, to] = key.split("→");
992
- if (from) spineNodeIds.add(from);
993
- if (to) spineNodeIds.add(to);
994
- }
995
- for (const node of layoutNodes) {
996
- const pos = nodePos.get(node.id);
997
- if (!pos) continue;
998
- const isSpineNode = spineNodeIds.has(node.id);
999
- const nodeColor = isSpineNode ? colors.spine : colors.branch;
1000
- grid.stampText(pos.x, pos.y, "○", nodeColor);
1001
- grid.stampText(pos.x + 1, pos.y, " ");
1002
- const hasMarkers = node.markers && node.markers.length > 0;
1003
- grid.stampText(pos.x + 2, pos.y, node.id, isSpineNode || hasMarkers ? bold : dim);
1004
- const tags = buildInlineTags(node.markers ?? [], colors);
1005
- if (tags.length > 0) {
1006
- let bx = pos.x + 2 + node.id.length;
1007
- for (const tag of tags) {
1008
- grid.stampText(bx, pos.y, " ");
1009
- bx++;
1010
- grid.stampText(bx, pos.y, tag.text, tag.color);
1011
- bx += tag.text.length;
1012
- }
1013
- }
1014
- }
1015
- if (elidedCount > 0) {
1016
- const topNodeId = layoutNodes.find((n) => !graph.incomingNodes.has(n.id))?.id ?? layoutNodes[0]?.id;
1017
- const rootPos = topNodeId ? nodePos.get(topNodeId) : void 0;
1018
- if (rootPos) {
1019
- const label = elidedCount === 1 ? "1 earlier migration" : `${elidedCount} earlier migrations`;
1020
- const topY = rootPos.y - 3;
1021
- grid.stampText(rootPos.x, topY, "┊", colors.label);
1022
- grid.stampText(rootPos.x, topY + 1, "┊", colors.label);
1023
- grid.stampText(rootPos.x + 2, topY + 1, `(${label})`, colors.label);
1024
- grid.stampText(rootPos.x, topY + 2, "┊", colors.label);
1025
- }
1026
- }
1027
- return grid.render();
1028
- }
1029
- /**
1030
- * BFS to find the ordered node path from `rootId` to `targetId`.
1031
- * Used for truncation — the spine path determines which edges to keep.
1032
- *
1033
- * Returns `[rootId]` if no path exists.
1034
- */
1035
- function findSpinePath(graph, rootId, targetId) {
1036
- const visited = new Set([rootId]);
1037
- const parent = /* @__PURE__ */ new Map();
1038
- const queue = [rootId];
1039
- while (queue.length > 0) {
1040
- const current = queue.shift();
1041
- if (current === targetId) {
1042
- const path = [];
1043
- let node = targetId;
1044
- while (node !== rootId) {
1045
- path.unshift(node);
1046
- node = parent.get(node);
1047
- }
1048
- path.unshift(rootId);
1049
- return path;
1050
- }
1051
- for (const edge of graph.outgoing(current)) if (!visited.has(edge.to)) {
1052
- visited.add(edge.to);
1053
- parent.set(edge.to, current);
1054
- queue.push(edge.to);
1055
- }
1056
- }
1057
- return [rootId];
1058
- }
1059
- /**
1060
- * Render a graph with optional truncation.
1061
- *
1062
- * The caller decides what to pass in: the full graph for `--graph`, or a
1063
- * subgraph extracted via {@link extractRelevantSubgraph} for the default view.
1064
- */
1065
- function render(graph, options) {
1066
- if (options.limit !== void 0) {
1067
- const { graph: truncated, elidedCount } = truncateGraph(graph, findSpinePath(graph, options.rootId ?? graph.nodes[0]?.id ?? "∅", options.spineTarget), options.limit);
1068
- return layoutAndRender(truncated, options, elidedCount);
1069
- }
1070
- return layoutAndRender(graph, options);
1071
- }
1072
- const graphRenderer = { render };
1073
- /** True if the graph is a single linear chain (no branching), ignoring dashed edges. */
1074
- function isLinearGraph(graph) {
1075
- for (const node of graph.nodes) if (graph.outgoing(node.id).filter((e) => e.style !== "dashed").length > 1) return false;
1076
- return true;
1077
- }
1078
- //#endregion
1079
- export { migrationGraphToRenderInput as i, graphRenderer as n, isLinearGraph as r, extractRelevantSubgraph as t };
1080
-
1081
- //# sourceMappingURL=graph-render-rFAqZujX.mjs.map