@zyro-sec/merman 1.0.2 → 1.0.3

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 (91) hide show
  1. package/package.json +2 -2
  2. package/script/layout-audit.ts +98 -98
  3. package/src/core/canvas.ts +228 -228
  4. package/src/core/color/style.ts +56 -56
  5. package/src/core/drawing.ts +301 -301
  6. package/src/core/geometry.ts +347 -347
  7. package/src/core/mermaid.ts +38 -38
  8. package/src/core/render-grid.ts +51 -51
  9. package/src/core/spatial.ts +243 -243
  10. package/src/core/text-lines.ts +32 -32
  11. package/src/core/text.ts +44 -44
  12. package/src/detect.ts +17 -17
  13. package/src/diagnostics.ts +16 -16
  14. package/src/flowchart/drawing.ts +340 -340
  15. package/src/flowchart/labels.ts +144 -144
  16. package/src/flowchart/layout.ts +1427 -1427
  17. package/src/flowchart/options.ts +12 -12
  18. package/src/flowchart/parser.ts +467 -467
  19. package/src/flowchart/render.ts +10 -10
  20. package/src/flowchart/routing.ts +1542 -1542
  21. package/src/flowchart/style.ts +79 -79
  22. package/src/flowchart/types.ts +65 -65
  23. package/src/gantt/diagram.ts +8 -8
  24. package/src/gantt/drawing.ts +191 -191
  25. package/src/gantt/parser.ts +161 -161
  26. package/src/gantt/render-grid.ts +17 -17
  27. package/src/gantt/style.ts +36 -36
  28. package/src/gantt/types.ts +44 -44
  29. package/src/gitgraph/diagram.ts +8 -8
  30. package/src/gitgraph/drawing.ts +234 -234
  31. package/src/gitgraph/parser.ts +219 -219
  32. package/src/gitgraph/render-grid.ts +17 -17
  33. package/src/gitgraph/style.ts +37 -37
  34. package/src/gitgraph/types.ts +36 -36
  35. package/src/markdown.ts +336 -336
  36. package/src/palette.ts +75 -75
  37. package/src/plugin.ts +15 -15
  38. package/src/sequence/diagram.ts +8 -8
  39. package/src/sequence/drawing.ts +287 -287
  40. package/src/sequence/options.ts +8 -8
  41. package/src/sequence/parser.ts +282 -282
  42. package/src/sequence/placement.ts +684 -684
  43. package/src/sequence/render-grid.ts +22 -22
  44. package/src/sequence/style.ts +81 -81
  45. package/src/sequence/types.ts +74 -74
  46. package/src/state/diagram.ts +8 -8
  47. package/src/state/drawing.ts +360 -360
  48. package/src/state/endpoint.ts +15 -15
  49. package/src/state/layout.ts +1134 -1134
  50. package/src/state/note.ts +59 -59
  51. package/src/state/options.ts +11 -11
  52. package/src/state/parser.ts +224 -224
  53. package/src/state/render-grid.ts +22 -22
  54. package/src/state/routing.ts +1522 -1522
  55. package/src/state/search.ts +103 -103
  56. package/src/state/style.ts +52 -52
  57. package/src/state/types.ts +63 -63
  58. package/src/state/visible-model.ts +77 -77
  59. package/src/test/diagram.ts +32 -32
  60. package/src/test/layout-audit/fixtures.ts +538 -538
  61. package/src/test/layout-audit/harness.ts +522 -522
  62. package/src/timeline/diagram.ts +8 -8
  63. package/src/timeline/drawing.ts +109 -109
  64. package/src/timeline/parser.ts +119 -119
  65. package/src/timeline/render-grid.ts +17 -17
  66. package/src/timeline/style.ts +36 -36
  67. package/src/timeline/types.ts +31 -31
  68. package/tsconfig.json +10 -10
  69. package/src/core/canvas.test.ts +0 -203
  70. package/src/core/color/style.test.ts +0 -24
  71. package/src/core/drawing.test.ts +0 -116
  72. package/src/core/geometry.test.ts +0 -112
  73. package/src/core/spatial.test.ts +0 -87
  74. package/src/core/text.test.ts +0 -33
  75. package/src/flowchart/flowchart.test.ts +0 -2800
  76. package/src/flowchart/labels.test.ts +0 -127
  77. package/src/flowchart/routing.test.ts +0 -368
  78. package/src/gantt/diagram.test.ts +0 -124
  79. package/src/gitgraph/diagram.test.ts +0 -183
  80. package/src/layout-audit.test.ts +0 -92
  81. package/src/palette.test.ts +0 -103
  82. package/src/sequence/diagram.test.ts +0 -757
  83. package/src/sequence/placement.test.ts +0 -219
  84. package/src/state/diagram.test.ts +0 -1386
  85. package/src/state/layout.test.ts +0 -314
  86. package/src/state/routing.test.ts +0 -693
  87. package/src/state/style.test.ts +0 -113
  88. package/src/state/visible-model.test.ts +0 -84
  89. package/src/test/diagnostics.test.ts +0 -129
  90. package/src/test/markdown.test.ts +0 -474
  91. package/src/timeline/diagram.test.ts +0 -188
@@ -1,38 +1,38 @@
1
- export interface NumberedMermaidLine {
2
- readonly lineNumber: number
3
- readonly text: string
4
- }
5
-
6
- export function* numberedMermaidLines(content: string): Generator<NumberedMermaidLine> {
7
- const lines = content.split(/\r?\n/)
8
- for (let index = 0; index < lines.length; index += 1) {
9
- yield { lineNumber: index + 1, text: lines[index]!.trim() }
10
- }
11
- }
12
-
13
- export function* meaningfulNumberedMermaidLines(content: string): Generator<NumberedMermaidLine> {
14
- for (const line of numberedMermaidLines(content)) {
15
- if (line.text && !line.text.startsWith("%%")) yield line
16
- }
17
- }
18
-
19
- export function firstMeaningfulMermaidLine(content: string): string | undefined {
20
- for (const rawLine of content.split(/\r?\n/)) {
21
- const line = rawLine.trim()
22
- if (line && !line.startsWith("%%")) return line
23
- }
24
- return undefined
25
- }
26
-
27
- export function stripMermaidQuotes(value: string): string {
28
- const trimmed = value.trim()
29
- if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
30
- return decodeMermaidText(trimmed.slice(1, -1))
31
- }
32
- return decodeMermaidText(trimmed)
33
- }
34
-
35
- export function decodeMermaidText(value: string): string {
36
- return decodeHTMLStrict(value)
37
- }
38
- import { decodeHTMLStrict } from "entities"
1
+ export interface NumberedMermaidLine {
2
+ readonly lineNumber: number
3
+ readonly text: string
4
+ }
5
+
6
+ export function* numberedMermaidLines(content: string): Generator<NumberedMermaidLine> {
7
+ const lines = content.split(/\r?\n/)
8
+ for (let index = 0; index < lines.length; index += 1) {
9
+ yield { lineNumber: index + 1, text: lines[index]!.trim() }
10
+ }
11
+ }
12
+
13
+ export function* meaningfulNumberedMermaidLines(content: string): Generator<NumberedMermaidLine> {
14
+ for (const line of numberedMermaidLines(content)) {
15
+ if (line.text && !line.text.startsWith("%%")) yield line
16
+ }
17
+ }
18
+
19
+ export function firstMeaningfulMermaidLine(content: string): string | undefined {
20
+ for (const rawLine of content.split(/\r?\n/)) {
21
+ const line = rawLine.trim()
22
+ if (line && !line.startsWith("%%")) return line
23
+ }
24
+ return undefined
25
+ }
26
+
27
+ export function stripMermaidQuotes(value: string): string {
28
+ const trimmed = value.trim()
29
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
30
+ return decodeMermaidText(trimmed.slice(1, -1))
31
+ }
32
+ return decodeMermaidText(trimmed)
33
+ }
34
+
35
+ export function decodeMermaidText(value: string): string {
36
+ return decodeHTMLStrict(value)
37
+ }
38
+ import { decodeHTMLStrict } from "entities"
@@ -1,51 +1,51 @@
1
- import { StyledText, type TextChunk } from "@opentui/core"
2
- import type { DiagramCanvas, DiagramCanvasRun, DiagramCanvasRunOptions } from "./canvas.js"
3
-
4
- export function renderDiagramGridStyledText<Style extends string, Metadata extends object = object>(
5
- grid: DiagramCanvas<Style, Metadata>,
6
- fg: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["fg"],
7
- bg?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["bg"],
8
- options?: DiagramCanvasRunOptions<Style, Metadata> & {
9
- attributes?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["attributes"]
10
- },
11
- ): StyledText {
12
- const chunks: TextChunk[] = []
13
-
14
- grid.forEachRun(
15
- (run) => {
16
- chunks.push({
17
- __isChunk: true,
18
- text: run.text,
19
- fg: fg(run),
20
- bg: bg?.(run),
21
- attributes: options?.attributes?.(run),
22
- })
23
- },
24
- () => {
25
- chunks.push({ __isChunk: true, text: "\n" })
26
- },
27
- options,
28
- )
29
-
30
- return new StyledText(chunks)
31
- }
32
-
33
- export function renderDiagramGridStyledTextByStyle<Style extends string, Metadata extends object = object>(
34
- grid: DiagramCanvas<Style, Metadata>,
35
- foregrounds: Readonly<Record<Style, TextChunk["fg"]>>,
36
- backgrounds?: Readonly<Partial<Record<Style, TextChunk["bg"]>>>,
37
- options?: DiagramCanvasRunOptions<Style, Metadata> & {
38
- attributes?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["attributes"]
39
- },
40
- ): StyledText {
41
- const background =
42
- backgrounds && Object.values(backgrounds).some((value) => value !== undefined)
43
- ? (run: DiagramCanvasRun<Style, Metadata>) => (run.style ? backgrounds[run.style] : undefined)
44
- : undefined
45
- return renderDiagramGridStyledText(
46
- grid,
47
- (run) => (run.style ? foregrounds[run.style] : undefined),
48
- background,
49
- options,
50
- )
51
- }
1
+ import { StyledText, type TextChunk } from "@opentui/core"
2
+ import type { DiagramCanvas, DiagramCanvasRun, DiagramCanvasRunOptions } from "./canvas.js"
3
+
4
+ export function renderDiagramGridStyledText<Style extends string, Metadata extends object = object>(
5
+ grid: DiagramCanvas<Style, Metadata>,
6
+ fg: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["fg"],
7
+ bg?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["bg"],
8
+ options?: DiagramCanvasRunOptions<Style, Metadata> & {
9
+ attributes?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["attributes"]
10
+ },
11
+ ): StyledText {
12
+ const chunks: TextChunk[] = []
13
+
14
+ grid.forEachRun(
15
+ (run) => {
16
+ chunks.push({
17
+ __isChunk: true,
18
+ text: run.text,
19
+ fg: fg(run),
20
+ bg: bg?.(run),
21
+ attributes: options?.attributes?.(run),
22
+ })
23
+ },
24
+ () => {
25
+ chunks.push({ __isChunk: true, text: "\n" })
26
+ },
27
+ options,
28
+ )
29
+
30
+ return new StyledText(chunks)
31
+ }
32
+
33
+ export function renderDiagramGridStyledTextByStyle<Style extends string, Metadata extends object = object>(
34
+ grid: DiagramCanvas<Style, Metadata>,
35
+ foregrounds: Readonly<Record<Style, TextChunk["fg"]>>,
36
+ backgrounds?: Readonly<Partial<Record<Style, TextChunk["bg"]>>>,
37
+ options?: DiagramCanvasRunOptions<Style, Metadata> & {
38
+ attributes?: (run: DiagramCanvasRun<Style, Metadata>) => TextChunk["attributes"]
39
+ },
40
+ ): StyledText {
41
+ const background =
42
+ backgrounds && Object.values(backgrounds).some((value) => value !== undefined)
43
+ ? (run: DiagramCanvasRun<Style, Metadata>) => (run.style ? backgrounds[run.style] : undefined)
44
+ : undefined
45
+ return renderDiagramGridStyledText(
46
+ grid,
47
+ (run) => (run.style ? foregrounds[run.style] : undefined),
48
+ background,
49
+ options,
50
+ )
51
+ }
@@ -1,243 +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
- }
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
+ }