@zyro-sec/merman 0.0.0-stage → 1.0.2

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 (92) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.test.ts +203 -0
  4. package/src/core/canvas.ts +228 -0
  5. package/src/core/color/style.test.ts +24 -0
  6. package/src/core/color/style.ts +56 -0
  7. package/src/core/drawing.test.ts +116 -0
  8. package/src/core/drawing.ts +301 -0
  9. package/src/core/geometry.test.ts +112 -0
  10. package/src/core/geometry.ts +347 -0
  11. package/src/core/mermaid.ts +38 -0
  12. package/src/core/render-grid.ts +51 -0
  13. package/src/core/spatial.test.ts +87 -0
  14. package/src/core/spatial.ts +243 -0
  15. package/src/core/text-lines.ts +32 -0
  16. package/src/core/text.test.ts +33 -0
  17. package/src/core/text.ts +44 -0
  18. package/src/detect.ts +17 -0
  19. package/src/diagnostics.ts +16 -0
  20. package/src/flowchart/drawing.ts +340 -0
  21. package/src/flowchart/flowchart.test.ts +2800 -0
  22. package/src/flowchart/labels.test.ts +127 -0
  23. package/src/flowchart/labels.ts +144 -0
  24. package/src/flowchart/layout.ts +1427 -0
  25. package/src/flowchart/options.ts +12 -0
  26. package/src/flowchart/parser.ts +467 -0
  27. package/src/flowchart/render.ts +10 -0
  28. package/src/flowchart/routing.test.ts +368 -0
  29. package/src/flowchart/routing.ts +1542 -0
  30. package/src/flowchart/style.ts +79 -0
  31. package/src/flowchart/types.ts +65 -0
  32. package/src/gantt/diagram.test.ts +124 -0
  33. package/src/gantt/diagram.ts +8 -0
  34. package/src/gantt/drawing.ts +191 -0
  35. package/src/gantt/parser.ts +161 -0
  36. package/src/gantt/render-grid.ts +17 -0
  37. package/src/gantt/style.ts +36 -0
  38. package/src/gantt/types.ts +44 -0
  39. package/src/gitgraph/diagram.test.ts +183 -0
  40. package/src/gitgraph/diagram.ts +8 -0
  41. package/src/gitgraph/drawing.ts +234 -0
  42. package/src/gitgraph/parser.ts +219 -0
  43. package/src/gitgraph/render-grid.ts +17 -0
  44. package/src/gitgraph/style.ts +37 -0
  45. package/src/gitgraph/types.ts +36 -0
  46. package/src/layout-audit.test.ts +92 -0
  47. package/src/markdown.ts +336 -0
  48. package/src/palette.test.ts +103 -0
  49. package/src/palette.ts +75 -0
  50. package/src/plugin.ts +15 -0
  51. package/src/sequence/diagram.test.ts +757 -0
  52. package/src/sequence/diagram.ts +8 -0
  53. package/src/sequence/drawing.ts +287 -0
  54. package/src/sequence/options.ts +8 -0
  55. package/src/sequence/parser.ts +282 -0
  56. package/src/sequence/placement.test.ts +219 -0
  57. package/src/sequence/placement.ts +684 -0
  58. package/src/sequence/render-grid.ts +22 -0
  59. package/src/sequence/style.ts +81 -0
  60. package/src/sequence/types.ts +74 -0
  61. package/src/state/diagram.test.ts +1386 -0
  62. package/src/state/diagram.ts +8 -0
  63. package/src/state/drawing.ts +360 -0
  64. package/src/state/endpoint.ts +15 -0
  65. package/src/state/layout.test.ts +314 -0
  66. package/src/state/layout.ts +1134 -0
  67. package/src/state/note.ts +59 -0
  68. package/src/state/options.ts +11 -0
  69. package/src/state/parser.ts +224 -0
  70. package/src/state/render-grid.ts +22 -0
  71. package/src/state/routing.test.ts +693 -0
  72. package/src/state/routing.ts +1522 -0
  73. package/src/state/search.ts +103 -0
  74. package/src/state/style.test.ts +113 -0
  75. package/src/state/style.ts +52 -0
  76. package/src/state/types.ts +63 -0
  77. package/src/state/visible-model.test.ts +84 -0
  78. package/src/state/visible-model.ts +77 -0
  79. package/src/test/diagnostics.test.ts +129 -0
  80. package/src/test/diagram.ts +32 -0
  81. package/src/test/layout-audit/fixtures.ts +538 -0
  82. package/src/test/layout-audit/harness.ts +522 -0
  83. package/src/test/markdown.test.ts +474 -0
  84. package/src/timeline/diagram.test.ts +188 -0
  85. package/src/timeline/diagram.ts +8 -0
  86. package/src/timeline/drawing.ts +109 -0
  87. package/src/timeline/parser.ts +119 -0
  88. package/src/timeline/render-grid.ts +17 -0
  89. package/src/timeline/style.ts +36 -0
  90. package/src/timeline/types.ts +31 -0
  91. package/tsconfig.json +10 -0
  92. package/README.md +0 -3
@@ -0,0 +1,243 @@
1
+ import { orthogonalPathPoints, type DiagramBounds, type DiagramPoint } from "./geometry.js"
2
+
3
+ export type SpatialRole = "body" | "boundary" | "terminal" | "route" | "label"
4
+
5
+ export interface SpatialSpan {
6
+ readonly y: number
7
+ readonly fromX: number
8
+ readonly toX: number
9
+ }
10
+
11
+ export interface SpatialClaim {
12
+ readonly id: string
13
+ readonly owner: string
14
+ readonly role: SpatialRole
15
+ readonly spans: readonly SpatialSpan[]
16
+ }
17
+
18
+ export interface SpatialContact {
19
+ owner: string
20
+ points: readonly DiagramPoint[]
21
+ }
22
+
23
+ export interface SpatialConflict {
24
+ moving: SpatialClaim
25
+ existing: SpatialClaim
26
+ point: DiagramPoint
27
+ }
28
+
29
+ export interface SpatialClearance {
30
+ x: number
31
+ y: number
32
+ }
33
+
34
+ export interface SpatialCollisionPolicy {
35
+ contacts?: readonly SpatialContact[]
36
+ clearance?: number | SpatialClearance | Partial<Record<SpatialRole, number | SpatialClearance>>
37
+ }
38
+
39
+ function normalizedSpan(y: number, fromX: number, toX: number): SpatialSpan {
40
+ return { y, fromX: Math.min(fromX, toX), toX: Math.max(fromX, toX) }
41
+ }
42
+
43
+ function assertFiniteInteger(value: number, name: string): void {
44
+ if (!Number.isFinite(value) || !Number.isInteger(value)) throw new RangeError(`${name} must be a finite integer`)
45
+ }
46
+
47
+ export function spatialRectSpans(bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">): SpatialSpan[] {
48
+ assertFiniteInteger(bounds.left, "bounds.left")
49
+ assertFiniteInteger(bounds.top, "bounds.top")
50
+ assertFiniteInteger(bounds.width, "bounds.width")
51
+ assertFiniteInteger(bounds.height, "bounds.height")
52
+ if (bounds.width <= 0 || bounds.height <= 0) throw new RangeError("Spatial bounds must have positive dimensions")
53
+ return Array.from({ length: bounds.height }, (_, offset) =>
54
+ normalizedSpan(bounds.top + offset, bounds.left, bounds.left + bounds.width - 1),
55
+ )
56
+ }
57
+
58
+ export function spatialPathSpans(points: readonly DiagramPoint[]): SpatialSpan[] {
59
+ for (const [index, point] of points.entries()) {
60
+ assertFiniteInteger(point.x, `points[${index}].x`)
61
+ assertFiniteInteger(point.y, `points[${index}].y`)
62
+ if (index > 0 && point.x !== points[index - 1]!.x && point.y !== points[index - 1]!.y) {
63
+ throw new RangeError("Spatial paths must be orthogonal")
64
+ }
65
+ }
66
+ const cells = new Map<number, Set<number>>()
67
+ const add = (point: DiagramPoint): void => {
68
+ const row = cells.get(point.y) ?? new Set<number>()
69
+ row.add(point.x)
70
+ cells.set(point.y, row)
71
+ }
72
+
73
+ if (points.length === 1) add(points[0]!)
74
+ for (const point of orthogonalPathPoints(points)) add(point)
75
+
76
+ return [...cells.entries()]
77
+ .sort(([left], [right]) => left - right)
78
+ .flatMap(([y, xs]) => {
79
+ const sorted = [...xs].sort((left, right) => left - right)
80
+ const [first, ...rest] = sorted
81
+ if (first === undefined) return []
82
+ const spans: SpatialSpan[] = []
83
+ let start = first
84
+ let end = first
85
+ for (const x of rest) {
86
+ if (x === end + 1) {
87
+ end = x
88
+ continue
89
+ }
90
+ spans.push(normalizedSpan(y, start, end))
91
+ start = x
92
+ end = x
93
+ }
94
+ spans.push(normalizedSpan(y, start, end))
95
+ return spans
96
+ })
97
+ }
98
+
99
+ export function spatialRectClaim(
100
+ id: string,
101
+ owner: string,
102
+ role: SpatialRole,
103
+ bounds: Pick<DiagramBounds, "left" | "top" | "width" | "height">,
104
+ ): SpatialClaim {
105
+ return { id, owner, role, spans: spatialRectSpans(bounds) }
106
+ }
107
+
108
+ export function spatialPathClaim(
109
+ id: string,
110
+ owner: string,
111
+ role: Extract<SpatialRole, "boundary" | "route">,
112
+ points: readonly DiagramPoint[],
113
+ ): SpatialClaim {
114
+ return { id, owner, role, spans: spatialPathSpans(points) }
115
+ }
116
+
117
+ function compareClaims(left: SpatialClaim, right: SpatialClaim): number {
118
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0
119
+ }
120
+
121
+ function sameClaim(left: SpatialClaim, right: SpatialClaim): boolean {
122
+ return (
123
+ left.id === right.id &&
124
+ left.owner === right.owner &&
125
+ left.role === right.role &&
126
+ left.spans.length === right.spans.length &&
127
+ left.spans.every(
128
+ (span, index) =>
129
+ span.y === right.spans[index]!.y &&
130
+ span.fromX === right.spans[index]!.fromX &&
131
+ span.toX === right.spans[index]!.toX,
132
+ )
133
+ )
134
+ }
135
+
136
+ function pointIsContact(point: DiagramPoint, existing: SpatialClaim, contacts: readonly SpatialContact[]): boolean {
137
+ return contacts.some(
138
+ (contact) =>
139
+ contact.owner === existing.owner &&
140
+ contact.points.some((candidate) => candidate.x === point.x && candidate.y === point.y),
141
+ )
142
+ }
143
+
144
+ function rolesMayOverlap(moving: SpatialClaim, existing: SpatialClaim): boolean {
145
+ if (moving.owner === existing.owner) return true
146
+ return moving.role === "route" && existing.role === "route"
147
+ }
148
+
149
+ function normalizeClearance(clearance: number | SpatialClearance | undefined): SpatialClearance {
150
+ const x = typeof clearance === "number" ? clearance : (clearance?.x ?? 0)
151
+ const y = typeof clearance === "number" ? clearance : (clearance?.y ?? 0)
152
+ assertFiniteInteger(x, "clearance.x")
153
+ assertFiniteInteger(y, "clearance.y")
154
+ if (x < 0 || y < 0) throw new RangeError("Spatial clearance cannot be negative")
155
+ return { x, y }
156
+ }
157
+
158
+ function inflateSpan(span: SpatialSpan, clearance: SpatialClearance): SpatialSpan {
159
+ return { y: span.y, fromX: span.fromX - clearance.x, toX: span.toX + clearance.x }
160
+ }
161
+
162
+ export class SpatialIndex {
163
+ static empty(): SpatialIndex {
164
+ return new SpatialIndex([])
165
+ }
166
+
167
+ readonly claims: readonly SpatialClaim[]
168
+
169
+ private constructor(claims: readonly SpatialClaim[]) {
170
+ this.claims = Object.freeze(
171
+ claims.map((claim) =>
172
+ Object.freeze({
173
+ ...claim,
174
+ spans: Object.freeze(
175
+ [...claim.spans]
176
+ .map((span) => Object.freeze({ ...span }))
177
+ .sort((left, right) => left.y - right.y || left.fromX - right.fromX || left.toX - right.toX),
178
+ ),
179
+ }),
180
+ ),
181
+ )
182
+ }
183
+
184
+ add(...claims: readonly SpatialClaim[]): SpatialIndex {
185
+ return this.overlay(new SpatialIndex(claims))
186
+ }
187
+
188
+ overlay(other: SpatialIndex): SpatialIndex {
189
+ const claims = new Map(this.claims.map((claim) => [claim.id, claim]))
190
+ for (const claim of other.claims) {
191
+ const existing = claims.get(claim.id)
192
+ if (existing && !sameClaim(existing, claim)) throw new Error(`Conflicting spatial claim id: ${claim.id}`)
193
+ claims.set(claim.id, claim)
194
+ }
195
+ return new SpatialIndex([...claims.values()].sort(compareClaims))
196
+ }
197
+
198
+ conflicts(moving: SpatialClaim, policy: SpatialCollisionPolicy = {}): SpatialConflict[] {
199
+ const contacts = policy.contacts ?? []
200
+ const conflicts: SpatialConflict[] = []
201
+
202
+ for (const existing of this.claims) {
203
+ if (rolesMayOverlap(moving, existing)) continue
204
+ const configuredClearance =
205
+ typeof policy.clearance === "number" || (policy.clearance && "x" in policy.clearance)
206
+ ? policy.clearance
207
+ : policy.clearance?.[existing.role]
208
+ const clearance = normalizeClearance(configuredClearance)
209
+ for (const movingSpan of moving.spans) {
210
+ for (let dy = -clearance.y; dy <= clearance.y; dy++) {
211
+ const inflated = inflateSpan({ ...movingSpan, y: movingSpan.y + dy }, clearance)
212
+ for (const existingSpan of existing.spans) {
213
+ if (inflated.y !== existingSpan.y) continue
214
+ const fromX = Math.max(inflated.fromX, existingSpan.fromX)
215
+ const toX = Math.min(inflated.toX, existingSpan.toX)
216
+ for (let x = fromX; x <= toX; x++) {
217
+ const point = { x, y: inflated.y }
218
+ const movingOccupiesPoint = moving.spans.some(
219
+ (span) => span.y === point.y && point.x >= span.fromX && point.x <= span.toX,
220
+ )
221
+ if (!(movingOccupiesPoint && pointIsContact(point, existing, contacts))) {
222
+ conflicts.push({ moving, existing, point })
223
+ }
224
+ }
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ return conflicts
231
+ }
232
+
233
+ isFree(claim: SpatialClaim, policy: SpatialCollisionPolicy = {}): boolean {
234
+ return this.conflicts(claim, policy).length === 0
235
+ }
236
+
237
+ firstFit<T extends { claim: SpatialClaim }>(
238
+ candidates: readonly T[],
239
+ policy: SpatialCollisionPolicy = {},
240
+ ): T | undefined {
241
+ return candidates.find((candidate) => this.isFree(candidate.claim, policy))
242
+ }
243
+ }
@@ -0,0 +1,32 @@
1
+ export interface DiagramTextRun {
2
+ text: string
3
+ italic: boolean
4
+ }
5
+
6
+ export interface DiagramTextLine {
7
+ text: string
8
+ runs: DiagramTextRun[]
9
+ }
10
+
11
+ export function parseDiagramTextLines(value: string): DiagramTextLine[] {
12
+ return value.split(/<br\s*\/?>/i).map((line) => {
13
+ const runs: DiagramTextRun[] = []
14
+ const source = line.trim()
15
+ const tag = /<\/?(?:i|em)\s*>/gi
16
+ let italic = false
17
+ let offset = 0
18
+
19
+ for (const match of source.matchAll(tag)) {
20
+ if (match.index > offset) runs.push({ text: source.slice(offset, match.index), italic })
21
+ italic = !match[0].startsWith("</")
22
+ offset = match.index + match[0].length
23
+ }
24
+ if (offset < source.length) runs.push({ text: source.slice(offset), italic })
25
+
26
+ return { text: runs.map((run) => run.text).join(""), runs }
27
+ })
28
+ }
29
+
30
+ export function splitDiagramLines(value: string): string[] {
31
+ return parseDiagramTextLines(value).map((line) => line.text)
32
+ }
@@ -0,0 +1,33 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { diagramTextWidth, measureDiagramTextBox, parseDiagramTextLines, splitDiagramLines } from "./text.js"
3
+
4
+ describe("diagram text helpers", () => {
5
+ test("splits Mermaid-style line breaks", () => {
6
+ expect(splitDiagramLines("one<br/> two <br>three")).toEqual(["one", "two", "three"])
7
+ })
8
+
9
+ test("extracts Mermaid italic markup from visible text", () => {
10
+ expect(parseDiagramTextLines("plain <i>italic</i><br/><em>again</em>")).toEqual([
11
+ {
12
+ text: "plain italic",
13
+ runs: [
14
+ { text: "plain ", italic: false },
15
+ { text: "italic", italic: true },
16
+ ],
17
+ },
18
+ { text: "again", runs: [{ text: "again", italic: true }] },
19
+ ])
20
+ })
21
+
22
+ test("measures padded text boxes", () => {
23
+ expect(measureDiagramTextBox("wide<br/>x", { paddingX: 2, paddingY: 1 })).toEqual({
24
+ width: 8,
25
+ height: 4,
26
+ lines: ["wide", "x"],
27
+ })
28
+ })
29
+
30
+ test("measures terminal cell width", () => {
31
+ expect(diagramTextWidth("abc")).toBe(3)
32
+ })
33
+ })
@@ -0,0 +1,44 @@
1
+ import stringWidth from "string-width"
2
+ import { splitDiagramLines } from "./text-lines.js"
3
+
4
+ export { parseDiagramTextLines, splitDiagramLines } from "./text-lines.js"
5
+
6
+ export interface DiagramTextBoxSize {
7
+ width: number
8
+ height: number
9
+ lines: string[]
10
+ }
11
+
12
+ export function diagramTextWidth(value: string): number {
13
+ return stringWidth(value)
14
+ }
15
+
16
+ export const DIAGRAM_LABEL_PADDING_X = 1
17
+
18
+ export function padDiagramLabelLine(value: string): string {
19
+ const padding = " ".repeat(DIAGRAM_LABEL_PADDING_X)
20
+ return `${padding}${value}${padding}`
21
+ }
22
+
23
+ export function measureDiagramLabelWidth(value: string, measure = diagramTextWidth): number {
24
+ return Math.max(...splitDiagramLines(value).map((line) => measure(line) + DIAGRAM_LABEL_PADDING_X * 2))
25
+ }
26
+
27
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" })
28
+
29
+ export function* diagramTextGraphemes(value: string): Generator<string> {
30
+ for (const { segment } of graphemeSegmenter.segment(value)) yield segment
31
+ }
32
+
33
+ export function measureDiagramTextBox(
34
+ value: string,
35
+ options: { paddingX?: number; paddingY?: number; minInnerWidth?: number } = {},
36
+ ): DiagramTextBoxSize {
37
+ const lines = splitDiagramLines(value)
38
+ const innerWidth = Math.max(...lines.map(diagramTextWidth), options.minInnerWidth ?? 1)
39
+ return {
40
+ width: innerWidth + (options.paddingX ?? 0) * 2,
41
+ height: lines.length + (options.paddingY ?? 0) * 2,
42
+ lines,
43
+ }
44
+ }
package/src/detect.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { MermaidDiagramKind } from "./diagnostics.js"
2
+ import { isMermaidFlowchartDiagram } from "./flowchart/parser.js"
3
+ import { isMermaidGanttDiagram } from "./gantt/parser.js"
4
+ import { isMermaidGitGraphDiagram } from "./gitgraph/parser.js"
5
+ import { isMermaidSequenceDiagram } from "./sequence/parser.js"
6
+ import { isMermaidStateDiagram } from "./state/parser.js"
7
+ import { isMermaidTimelineDiagram } from "./timeline/parser.js"
8
+
9
+ export function detectMermaidDiagram(content: string): MermaidDiagramKind | undefined {
10
+ if (isMermaidFlowchartDiagram(content)) return "flowchart"
11
+ if (isMermaidGanttDiagram(content)) return "gantt"
12
+ if (isMermaidGitGraphDiagram(content)) return "gitGraph"
13
+ if (isMermaidSequenceDiagram(content)) return "sequence"
14
+ if (isMermaidStateDiagram(content)) return "state"
15
+ if (isMermaidTimelineDiagram(content)) return "timeline"
16
+ return undefined
17
+ }
@@ -0,0 +1,16 @@
1
+ export type MermaidDiagramKind = "flowchart" | "sequence" | "state" | "timeline" | "gitGraph" | "gantt"
2
+
3
+ /** An otherwise valid diagram contains syntax that this renderer does not support. */
4
+ export class MermaidSyntaxError extends Error {
5
+ readonly _tag = "MermaidSyntaxError"
6
+
7
+ constructor(
8
+ readonly kind: MermaidDiagramKind,
9
+ readonly lineNumber: number,
10
+ readonly sourceLine: string,
11
+ reason = "Unsupported syntax",
12
+ ) {
13
+ super(`${reason} in ${kind} diagram at line ${lineNumber}: "${sourceLine}"`)
14
+ this.name = "MermaidSyntaxError"
15
+ }
16
+ }