@vielzeug/wire 0.0.0-stage → 26.11.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +48 -2
- package/dist/_format.cjs +2 -0
- package/dist/_format.cjs.map +1 -0
- package/dist/_format.d.ts +3 -0
- package/dist/_format.d.ts.map +1 -0
- package/dist/_format.js +8 -0
- package/dist/_format.js.map +1 -0
- package/dist/_heap.cjs +2 -0
- package/dist/_heap.cjs.map +1 -0
- package/dist/_heap.d.ts +12 -0
- package/dist/_heap.d.ts.map +1 -0
- package/dist/_heap.js +37 -0
- package/dist/_heap.js.map +1 -0
- package/dist/_sides.cjs +2 -0
- package/dist/_sides.cjs.map +1 -0
- package/dist/_sides.d.ts +20 -0
- package/dist/_sides.d.ts.map +1 -0
- package/dist/_sides.js +55 -0
- package/dist/_sides.js.map +1 -0
- package/dist/bezier.cjs +2 -0
- package/dist/bezier.cjs.map +1 -0
- package/dist/bezier.d.ts +24 -0
- package/dist/bezier.d.ts.map +1 -0
- package/dist/bezier.js +34 -0
- package/dist/bezier.js.map +1 -0
- package/dist/edit.cjs +2 -0
- package/dist/edit.cjs.map +1 -0
- package/dist/edit.d.ts +93 -0
- package/dist/edit.d.ts.map +1 -0
- package/dist/edit.js +170 -0
- package/dist/edit.js.map +1 -0
- package/dist/errors.cjs +2 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +11 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +9 -0
- package/dist/errors.js.map +1 -0
- package/dist/graph.cjs +2 -0
- package/dist/graph.cjs.map +1 -0
- package/dist/graph.d.ts +21 -0
- package/dist/graph.d.ts.map +1 -0
- package/dist/graph.js +81 -0
- package/dist/graph.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/orthogonal.cjs +2 -0
- package/dist/orthogonal.cjs.map +1 -0
- package/dist/orthogonal.d.ts +37 -0
- package/dist/orthogonal.d.ts.map +1 -0
- package/dist/orthogonal.js +122 -0
- package/dist/orthogonal.js.map +1 -0
- package/dist/path.cjs +2 -0
- package/dist/path.cjs.map +1 -0
- package/dist/path.d.ts +19 -0
- package/dist/path.d.ts.map +1 -0
- package/dist/path.js +33 -0
- package/dist/path.js.map +1 -0
- package/dist/ports.cjs +2 -0
- package/dist/ports.cjs.map +1 -0
- package/dist/ports.d.ts +21 -0
- package/dist/ports.d.ts.map +1 -0
- package/dist/ports.js +36 -0
- package/dist/ports.js.map +1 -0
- package/dist/types.d.ts +31 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/wire.cjs +2 -0
- package/dist/wire.cjs.map +1 -0
- package/dist/wire.iife.js +2 -0
- package/dist/wire.iife.js.map +1 -0
- package/dist/wire.js +543 -0
- package/dist/wire.js.map +1 -0
- package/package.json +48 -4
package/dist/edit.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { WireConfigError as e } from "./errors.js";
|
|
2
|
+
// src/edit.ts
|
|
3
|
+
var t = 10, n = 6, r = 4, i = 64;
|
|
4
|
+
function cubicAt(e, t) {
|
|
5
|
+
let n = 1 - t, r = n * n * n, i = 3 * n * n * t, a = 3 * n * t * t, o = t * t * t;
|
|
6
|
+
return {
|
|
7
|
+
x: r * e.from.x + i * e.c1.x + a * e.c2.x + o * e.to.x,
|
|
8
|
+
y: r * e.from.y + i * e.c1.y + a * e.c2.y + o * e.to.y
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function requirePoint(t, n) {
|
|
12
|
+
if (!Number.isFinite(t.x) || !Number.isFinite(t.y)) throw new e(`Wire edit ${n} must have finite coordinates, received (${t.x}, ${t.y}).`);
|
|
13
|
+
}
|
|
14
|
+
function requirePositive(t, n) {
|
|
15
|
+
if (!Number.isFinite(t) || t <= 0) throw new e(`Wire edit ${n} must be a finite positive number, received ${String(t)}.`);
|
|
16
|
+
}
|
|
17
|
+
function requireUnitT(t) {
|
|
18
|
+
if (!Number.isFinite(t) || t < 0 || t > 1) throw new e(`Wire edit t must be a finite number in [0, 1], received ${String(t)}.`);
|
|
19
|
+
}
|
|
20
|
+
function arrowhead(r, i, a = {}) {
|
|
21
|
+
requirePoint(r, "arrowhead tip"), requirePoint(i, "arrowhead direction");
|
|
22
|
+
let o = Math.hypot(i.x, i.y);
|
|
23
|
+
if (o === 0) throw new e("Wire edit arrowhead direction must be non-zero.");
|
|
24
|
+
let s = a.length ?? t, c = a.width ?? n;
|
|
25
|
+
requirePositive(s, "arrowhead length"), requirePositive(c, "arrowhead width");
|
|
26
|
+
let l = i.x / o, u = i.y / o, d = -u, f = l, p = r.x - l * s, m = r.y - u * s, h = c / 2;
|
|
27
|
+
return [
|
|
28
|
+
{
|
|
29
|
+
x: r.x,
|
|
30
|
+
y: r.y
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
x: p + d * h,
|
|
34
|
+
y: m + f * h
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
x: p - d * h,
|
|
38
|
+
y: m - f * h
|
|
39
|
+
}
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
function polylineLengths(e) {
|
|
43
|
+
let t = Array(e.length);
|
|
44
|
+
t[0] = 0;
|
|
45
|
+
for (let n = 1; n < e.length; n++) t[n] = t[n - 1] + Math.hypot(e[n].x - e[n - 1].x, e[n].y - e[n - 1].y);
|
|
46
|
+
return t;
|
|
47
|
+
}
|
|
48
|
+
function pointAtPolylineLength(e, t, n) {
|
|
49
|
+
let r = t[t.length - 1];
|
|
50
|
+
if (r === 0) return {
|
|
51
|
+
x: e[0].x,
|
|
52
|
+
y: e[0].y
|
|
53
|
+
};
|
|
54
|
+
let i = Math.min(Math.max(n, 0), r), a = 1, o = t.length - 1;
|
|
55
|
+
for (; a < o;) {
|
|
56
|
+
let e = a + o >> 1;
|
|
57
|
+
t[e] < i ? a = e + 1 : o = e;
|
|
58
|
+
}
|
|
59
|
+
let s = e[a - 1], c = e[a], l = t[a] - t[a - 1];
|
|
60
|
+
if (l === 0) return {
|
|
61
|
+
x: s.x,
|
|
62
|
+
y: s.y
|
|
63
|
+
};
|
|
64
|
+
let u = (i - t[a - 1]) / l;
|
|
65
|
+
return {
|
|
66
|
+
x: s.x + (c.x - s.x) * u,
|
|
67
|
+
y: s.y + (c.y - s.y) * u
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function bezierTable(e) {
|
|
71
|
+
let t = Array(65), n = Array(65);
|
|
72
|
+
for (let n = 0; n <= i; n++) t[n] = cubicAt(e, n / i);
|
|
73
|
+
n[0] = 0;
|
|
74
|
+
for (let e = 1; e <= i; e++) n[e] = n[e - 1] + Math.hypot(t[e].x - t[e - 1].x, t[e].y - t[e - 1].y);
|
|
75
|
+
return {
|
|
76
|
+
cumulative: n,
|
|
77
|
+
samples: t,
|
|
78
|
+
total: n[i]
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function uAtBezierLength(e, t) {
|
|
82
|
+
let n = Math.min(Math.max(t, 0), e.total), r = 1, a = i;
|
|
83
|
+
for (; r < a;) {
|
|
84
|
+
let t = r + a >> 1;
|
|
85
|
+
e.cumulative[t] < n ? r = t + 1 : a = t;
|
|
86
|
+
}
|
|
87
|
+
let o = e.cumulative[r] - e.cumulative[r - 1], s = o === 0 ? 0 : (n - e.cumulative[r - 1]) / o;
|
|
88
|
+
return (r - 1 + s) / i;
|
|
89
|
+
}
|
|
90
|
+
function sampledLengthAt(e, t) {
|
|
91
|
+
let n = Math.min(Math.max(t, 0), 1) * i, r = Math.min(Math.floor(n), 63), a = n - r;
|
|
92
|
+
return e.cumulative[r] + a * (e.cumulative[r + 1] - e.cumulative[r]);
|
|
93
|
+
}
|
|
94
|
+
function requireCurve(e, t) {
|
|
95
|
+
requirePoint(e.from, `${t} from`), requirePoint(e.c1, `${t} c1`), requirePoint(e.c2, `${t} c2`), requirePoint(e.to, `${t} to`);
|
|
96
|
+
}
|
|
97
|
+
function pointOnPolyline(t, n) {
|
|
98
|
+
if (t.length < 2) throw new e(`Wire edit pointOnPolyline requires at least 2 points, received ${t.length}.`);
|
|
99
|
+
for (let e = 0; e < t.length; e++) requirePoint(t[e], `pointOnPolyline points[${e}]`);
|
|
100
|
+
requireUnitT(n);
|
|
101
|
+
let r = polylineLengths(t);
|
|
102
|
+
return pointAtPolylineLength(t, r, n * r[r.length - 1]);
|
|
103
|
+
}
|
|
104
|
+
function pointOnBezier(e, t) {
|
|
105
|
+
requireCurve(e, "pointOnBezier"), requireUnitT(t);
|
|
106
|
+
let n = bezierTable(e);
|
|
107
|
+
return n.total === 0 ? {
|
|
108
|
+
x: e.from.x,
|
|
109
|
+
y: e.from.y
|
|
110
|
+
} : cubicAt(e, uAtBezierLength(n, t * n.total));
|
|
111
|
+
}
|
|
112
|
+
function distanceToSegment(e, t, n) {
|
|
113
|
+
let r = n.x - t.x, i = n.y - t.y, a = r * r + i * i;
|
|
114
|
+
if (a === 0) return {
|
|
115
|
+
distance: Math.hypot(e.x - t.x, e.y - t.y),
|
|
116
|
+
ratio: 0
|
|
117
|
+
};
|
|
118
|
+
let o = Math.min(Math.max(((e.x - t.x) * r + (e.y - t.y) * i) / a, 0), 1), s = t.x + r * o, c = t.y + i * o;
|
|
119
|
+
return {
|
|
120
|
+
distance: Math.hypot(e.x - s, e.y - c),
|
|
121
|
+
ratio: o
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function hitPolyline(t, n, i = {}) {
|
|
125
|
+
if (t.length < 2) throw new e(`Wire edit hitPolyline requires at least 2 points, received ${t.length}.`);
|
|
126
|
+
for (let e = 0; e < t.length; e++) requirePoint(t[e], `hitPolyline points[${e}]`);
|
|
127
|
+
requirePoint(n, "hitPolyline point");
|
|
128
|
+
let a = i.threshold ?? r;
|
|
129
|
+
requirePositive(a, "hitPolyline threshold");
|
|
130
|
+
let o = polylineLengths(t), s = o[o.length - 1], c = Infinity, l = 0;
|
|
131
|
+
for (let e = 1; e < t.length; e++) {
|
|
132
|
+
let r = distanceToSegment(n, t[e - 1], t[e]);
|
|
133
|
+
r.distance < c && (c = r.distance, l = o[e - 1] + r.ratio * (o[e] - o[e - 1]));
|
|
134
|
+
}
|
|
135
|
+
return c > a ? null : {
|
|
136
|
+
distance: c,
|
|
137
|
+
t: s === 0 ? 0 : l / s
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
function hitBezier(e, t, n = {}) {
|
|
141
|
+
requireCurve(e, "hitBezier"), requirePoint(t, "hitBezier point");
|
|
142
|
+
let a = n.threshold ?? r;
|
|
143
|
+
requirePositive(a, "hitBezier threshold");
|
|
144
|
+
let o = bezierTable(e);
|
|
145
|
+
if (o.total === 0) {
|
|
146
|
+
let n = Math.hypot(t.x - e.from.x, t.y - e.from.y);
|
|
147
|
+
return n <= a ? {
|
|
148
|
+
distance: n,
|
|
149
|
+
t: 0
|
|
150
|
+
} : null;
|
|
151
|
+
}
|
|
152
|
+
let s = 0, c = Infinity;
|
|
153
|
+
for (let e = 0; e <= i; e++) {
|
|
154
|
+
let n = Math.hypot(t.x - o.samples[e].x, t.y - o.samples[e].y);
|
|
155
|
+
n < c && (c = n, s = e);
|
|
156
|
+
}
|
|
157
|
+
let l = Math.max(0, (s - 1) / i), u = Math.min(1, (s + 1) / i);
|
|
158
|
+
for (let n = 0; n < 32; n++) {
|
|
159
|
+
let n = l + (u - l) / 3, r = u - (u - l) / 3, i = cubicAt(e, n), a = cubicAt(e, r);
|
|
160
|
+
Math.hypot(t.x - i.x, t.y - i.y) < Math.hypot(t.x - a.x, t.y - a.y) ? u = r : l = n;
|
|
161
|
+
}
|
|
162
|
+
let d = (l + u) / 2, f = cubicAt(e, d), p = Math.hypot(t.x - f.x, t.y - f.y);
|
|
163
|
+
return p > a ? null : {
|
|
164
|
+
distance: p,
|
|
165
|
+
t: sampledLengthAt(o, d) / o.total
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
export { arrowhead, hitBezier, hitPolyline, pointOnBezier, pointOnPolyline };
|
|
169
|
+
|
|
170
|
+
//# sourceMappingURL=edit.js.map
|
package/dist/edit.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"edit.js","names":["DEFAULT_ARROWHEAD_LENGTH","DEFAULT_ARROWHEAD_WIDTH","DEFAULT_HIT_THRESHOLD","BEZIER_SAMPLES","v","u","a","b","c","d","curve","value","WireConfigError","label","tip","direction","magnitude","length","options","width","ux","uy","px","py","baseX","baseY","half","cumulative","points","i","total","clamped","target","low","high","mid","start","end","segmentLength","ratio","samples","table","span","scaled","cell","t","abx","aby","segmentLengthSq","point","projX","projY","threshold","bestDistance","bestLength","hit","distance","bestIndex","lo","hi","m1","m2","p1","p2","closest"],"sources":["../src/edit.ts"],"sourcesContent":["import { WireConfigError } from './errors.js';\nimport type { CubicBezier, Point } from './types.js';\n\nconst DEFAULT_ARROWHEAD_LENGTH = 10;\nconst DEFAULT_ARROWHEAD_WIDTH = 6;\nconst DEFAULT_HIT_THRESHOLD = 4;\nconst BEZIER_SAMPLES = 64;\n\n/** Evaluates the cubic bezier at raw parameter `u` in `[0, 1]`. */\nfunction cubicAt(curve: CubicBezier, u: number): Point {\n const v = 1 - u;\n const a = v * v * v;\n const b = 3 * v * v * u;\n const c = 3 * v * u * u;\n const d = u * u * u;\n return {\n x: a * curve.from.x + b * curve.c1.x + c * curve.c2.x + d * curve.to.x,\n y: a * curve.from.y + b * curve.c1.y + c * curve.c2.y + d * curve.to.y,\n };\n}\n\n/** Options for {@link arrowhead}. */\nexport interface ArrowheadOptions {\n /** Distance from the tip back along the shaft. Default 10. */\n readonly length?: number;\n /** Full width of the base, perpendicular to the shaft. Default 6. */\n readonly width?: number;\n}\n\n/** Options for the hit-test helpers. */\nexport interface HitOptions {\n /** Maximum distance from the shape for a hit. Default 4. */\n readonly threshold?: number;\n}\n\n/** Where a point hit a shape. */\nexport interface HitResult {\n /** Euclidean distance from the query point to the closest point on the shape. */\n readonly distance: number;\n /** Position along the shape, normalized by arc length in `[0, 1]`. */\n readonly t: number;\n}\n\nfunction requirePoint(value: Point, label: string): void {\n if (!Number.isFinite(value.x) || !Number.isFinite(value.y)) {\n throw new WireConfigError(`Wire edit ${label} must have finite coordinates, received (${value.x}, ${value.y}).`);\n }\n}\n\nfunction requirePositive(value: number, label: string): void {\n if (!Number.isFinite(value) || value <= 0) {\n throw new WireConfigError(`Wire edit ${label} must be a finite positive number, received ${String(value)}.`);\n }\n}\n\nfunction requireUnitT(t: number): void {\n if (!Number.isFinite(t) || t < 0 || t > 1) {\n throw new WireConfigError(`Wire edit t must be a finite number in [0, 1], received ${String(t)}.`);\n }\n}\n\n/**\n * Build a filled triangle that caps a line at `tip`, pointing along\n * `direction`. The apex sits at `tip`; the base sits `length` behind it\n * along `-direction`, `width` apart. `direction` may be any non-zero\n * vector and is normalized internally.\n *\n * @param tip - The apex of the arrowhead.\n * @param direction - The direction the line arrives from, pointing toward the tip.\n * @param options - Head `length` (default 10) and `width` (default 6).\n * @returns `[tip, baseLeft, baseRight]` as three points.\n * @throws {@link WireConfigError} when a point is non-finite, `direction` is\n * zero, or `length`/`width` are not finite positive numbers.\n */\nexport function arrowhead(tip: Point, direction: Point, options: ArrowheadOptions = {}): Point[] {\n requirePoint(tip, 'arrowhead tip');\n requirePoint(direction, 'arrowhead direction');\n const magnitude = Math.hypot(direction.x, direction.y);\n if (magnitude === 0) {\n throw new WireConfigError('Wire edit arrowhead direction must be non-zero.');\n }\n const length = options.length ?? DEFAULT_ARROWHEAD_LENGTH;\n const width = options.width ?? DEFAULT_ARROWHEAD_WIDTH;\n requirePositive(length, 'arrowhead length');\n requirePositive(width, 'arrowhead width');\n const ux = direction.x / magnitude;\n const uy = direction.y / magnitude;\n // Perpendicular unit vector for the base offsets.\n const px = -uy;\n const py = ux;\n const baseX = tip.x - ux * length;\n const baseY = tip.y - uy * length;\n const half = width / 2;\n return [\n { x: tip.x, y: tip.y },\n { x: baseX + px * half, y: baseY + py * half },\n { x: baseX - px * half, y: baseY - py * half },\n ];\n}\n\nfunction polylineLengths(points: readonly Point[]): number[] {\n const cumulative = new Array<number>(points.length);\n cumulative[0] = 0;\n for (let i = 1; i < points.length; i++) {\n cumulative[i] = cumulative[i - 1] + Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);\n }\n return cumulative;\n}\n\nfunction pointAtPolylineLength(points: readonly Point[], cumulative: readonly number[], target: number): Point {\n const total = cumulative[cumulative.length - 1];\n if (total === 0) {\n return { x: points[0].x, y: points[0].y };\n }\n const clamped = Math.min(Math.max(target, 0), total);\n let low = 1;\n let high = cumulative.length - 1;\n while (low < high) {\n const mid = (low + high) >> 1;\n if (cumulative[mid] < clamped) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n const start = points[low - 1];\n const end = points[low];\n const segmentLength = cumulative[low] - cumulative[low - 1];\n if (segmentLength === 0) {\n return { x: start.x, y: start.y };\n }\n const ratio = (clamped - cumulative[low - 1]) / segmentLength;\n return { x: start.x + (end.x - start.x) * ratio, y: start.y + (end.y - start.y) * ratio };\n}\n\n/** Sampled arc-length lookup table for one cubic bezier. */\ninterface BezierTable {\n readonly cumulative: number[];\n readonly samples: Point[];\n readonly total: number;\n}\n\nfunction bezierTable(curve: CubicBezier): BezierTable {\n const samples = new Array<Point>(BEZIER_SAMPLES + 1);\n const cumulative = new Array<number>(BEZIER_SAMPLES + 1);\n for (let i = 0; i <= BEZIER_SAMPLES; i++) {\n samples[i] = cubicAt(curve, i / BEZIER_SAMPLES);\n }\n cumulative[0] = 0;\n for (let i = 1; i <= BEZIER_SAMPLES; i++) {\n cumulative[i] = cumulative[i - 1] + Math.hypot(samples[i].x - samples[i - 1].x, samples[i].y - samples[i - 1].y);\n }\n return { cumulative, samples, total: cumulative[BEZIER_SAMPLES] };\n}\n\n/** Raw bezier parameter `u` whose sampled arc length is `target`. */\nfunction uAtBezierLength(table: BezierTable, target: number): number {\n const clamped = Math.min(Math.max(target, 0), table.total);\n let low = 1;\n let high = BEZIER_SAMPLES;\n while (low < high) {\n const mid = (low + high) >> 1;\n if (table.cumulative[mid] < clamped) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n const span = table.cumulative[low] - table.cumulative[low - 1];\n const ratio = span === 0 ? 0 : (clamped - table.cumulative[low - 1]) / span;\n return (low - 1 + ratio) / BEZIER_SAMPLES;\n}\n\n/** Sampled arc length up to raw parameter `u`, interpolated within its cell. */\nfunction sampledLengthAt(table: BezierTable, u: number): number {\n const scaled = Math.min(Math.max(u, 0), 1) * BEZIER_SAMPLES;\n const cell = Math.min(Math.floor(scaled), BEZIER_SAMPLES - 1);\n const ratio = scaled - cell;\n return table.cumulative[cell] + ratio * (table.cumulative[cell + 1] - table.cumulative[cell]);\n}\n\nfunction requireCurve(curve: CubicBezier, label: string): void {\n requirePoint(curve.from, `${label} from`);\n requirePoint(curve.c1, `${label} c1`);\n requirePoint(curve.c2, `${label} c2`);\n requirePoint(curve.to, `${label} to`);\n}\n\n/**\n * Point on a polyline at parameter `t`, where `t` is normalized by total\n * arc length (not by segment index): `t = 0.5` is the point halfway along\n * the wire's length. Exact for polylines.\n *\n * @param points - Two or more finite points.\n * @param t - Position in `[0, 1]` along the total length.\n * @returns The point at that length. A degenerate all-duplicate polyline\n * returns its first point for every `t`.\n * @throws {@link WireConfigError} when `points` has fewer than two finite\n * points or `t` is outside `[0, 1]`.\n */\nexport function pointOnPolyline(points: readonly Point[], t: number): Point {\n if (points.length < 2) {\n throw new WireConfigError(`Wire edit pointOnPolyline requires at least 2 points, received ${points.length}.`);\n }\n for (let i = 0; i < points.length; i++) {\n requirePoint(points[i], `pointOnPolyline points[${i}]`);\n }\n requireUnitT(t);\n const cumulative = polylineLengths(points);\n return pointAtPolylineLength(points, cumulative, t * cumulative[cumulative.length - 1]);\n}\n\n/**\n * Point on a cubic bezier at parameter `t`, where `t` is normalized by arc\n * length: `t = 0.5` is the point halfway along the curve's drawn length,\n * not the raw bezier midpoint.\n *\n * The arc-length mapping is approximated with a fixed lookup table of 64\n * samples, so `t` is accurate to within roughly one sample cell of the\n * true length fraction — sub-pixel for typical wire sizes.\n *\n * @param curve - A cubic bezier with finite endpoints and control points.\n * @param t - Position in `[0, 1]` along the curve length.\n * @returns The point at that length. A degenerate zero-length curve returns\n * its start for every `t`.\n * @throws {@link WireConfigError} when any curve point is non-finite or `t`\n * is outside `[0, 1]`.\n */\nexport function pointOnBezier(curve: CubicBezier, t: number): Point {\n requireCurve(curve, 'pointOnBezier');\n requireUnitT(t);\n const table = bezierTable(curve);\n if (table.total === 0) {\n return { x: curve.from.x, y: curve.from.y };\n }\n return cubicAt(curve, uAtBezierLength(table, t * table.total));\n}\n\nfunction distanceToSegment(point: Point, a: Point, b: Point): { distance: number; ratio: number } {\n const abx = b.x - a.x;\n const aby = b.y - a.y;\n const segmentLengthSq = abx * abx + aby * aby;\n if (segmentLengthSq === 0) {\n return { distance: Math.hypot(point.x - a.x, point.y - a.y), ratio: 0 };\n }\n const ratio = Math.min(Math.max(((point.x - a.x) * abx + (point.y - a.y) * aby) / segmentLengthSq, 0), 1);\n const projX = a.x + abx * ratio;\n const projY = a.y + aby * ratio;\n return { distance: Math.hypot(point.x - projX, point.y - projY), ratio };\n}\n\n/**\n * Closest point on a polyline to `point`, parameterized by arc length.\n * Exact: every segment is tested analytically.\n *\n * @param points - Two or more finite points.\n * @param point - The query point.\n * @param options - `threshold` (default 4): the maximum distance for a hit.\n * @returns The length-normalized `t` and `distance` of the closest point, or\n * `null` when the closest point is farther away than `threshold`.\n * @throws {@link WireConfigError} when `points` has fewer than two finite\n * points, `point` is non-finite, or `threshold` is not finite positive.\n */\nexport function hitPolyline(points: readonly Point[], point: Point, options: HitOptions = {}): HitResult | null {\n if (points.length < 2) {\n throw new WireConfigError(`Wire edit hitPolyline requires at least 2 points, received ${points.length}.`);\n }\n for (let i = 0; i < points.length; i++) {\n requirePoint(points[i], `hitPolyline points[${i}]`);\n }\n requirePoint(point, 'hitPolyline point');\n const threshold = options.threshold ?? DEFAULT_HIT_THRESHOLD;\n requirePositive(threshold, 'hitPolyline threshold');\n const cumulative = polylineLengths(points);\n const total = cumulative[cumulative.length - 1];\n let bestDistance = Infinity;\n let bestLength = 0;\n for (let i = 1; i < points.length; i++) {\n const hit = distanceToSegment(point, points[i - 1], points[i]);\n if (hit.distance < bestDistance) {\n bestDistance = hit.distance;\n bestLength = cumulative[i - 1] + hit.ratio * (cumulative[i] - cumulative[i - 1]);\n }\n }\n if (bestDistance > threshold) {\n return null;\n }\n return { distance: bestDistance, t: total === 0 ? 0 : bestLength / total };\n}\n\n/**\n * Closest point on a cubic bezier to `point`, parameterized by arc length.\n * Uses the same 64-sample lookup table as {@link pointOnBezier}: the nearest\n * sample is refined by ternary search on the true curve, so the reported\n * `distance` is accurate; `t` carries the table's arc-length tolerance.\n *\n * @param curve - A cubic bezier with finite endpoints and control points.\n * @param point - The query point.\n * @param options - `threshold` (default 4): the maximum distance for a hit.\n * @returns The length-normalized `t` and `distance` of the closest point, or\n * `null` when the closest point is farther away than `threshold`.\n * @throws {@link WireConfigError} when any curve point is non-finite,\n * `point` is non-finite, or `threshold` is not finite positive.\n */\nexport function hitBezier(curve: CubicBezier, point: Point, options: HitOptions = {}): HitResult | null {\n requireCurve(curve, 'hitBezier');\n requirePoint(point, 'hitBezier point');\n const threshold = options.threshold ?? DEFAULT_HIT_THRESHOLD;\n requirePositive(threshold, 'hitBezier threshold');\n const table = bezierTable(curve);\n if (table.total === 0) {\n const distance = Math.hypot(point.x - curve.from.x, point.y - curve.from.y);\n return distance <= threshold ? { distance, t: 0 } : null;\n }\n let bestIndex = 0;\n let bestDistance = Infinity;\n for (let i = 0; i <= BEZIER_SAMPLES; i++) {\n const distance = Math.hypot(point.x - table.samples[i].x, point.y - table.samples[i].y);\n if (distance < bestDistance) {\n bestDistance = distance;\n bestIndex = i;\n }\n }\n // Refine within the neighbouring samples with ternary search, clamped to the\n // curve so an endpoint sample never extrapolates past t=0 or t=1.\n let lo = Math.max(0, (bestIndex - 1) / BEZIER_SAMPLES);\n let hi = Math.min(1, (bestIndex + 1) / BEZIER_SAMPLES);\n for (let i = 0; i < 32; i++) {\n const m1 = lo + (hi - lo) / 3;\n const m2 = hi - (hi - lo) / 3;\n const p1 = cubicAt(curve, m1);\n const p2 = cubicAt(curve, m2);\n const d1 = Math.hypot(point.x - p1.x, point.y - p1.y);\n const d2 = Math.hypot(point.x - p2.x, point.y - p2.y);\n if (d1 < d2) {\n hi = m2;\n } else {\n lo = m1;\n }\n }\n const u = (lo + hi) / 2;\n const closest = cubicAt(curve, u);\n const distance = Math.hypot(point.x - closest.x, point.y - closest.y);\n if (distance > threshold) {\n return null;\n }\n return { distance, t: sampledLengthAt(table, u) / table.total };\n}\n"],"mappings":";;AAGA,IAAMA,IAA2B,IAC3BC,IAA0B,GAC1BC,IAAwB,GACxBC,IAAiB;AAGvB,SAAS,QAAQ,GAAoB,GAAkB;CACrD,IAAMC,IAAI,IAAIC,GACRC,IAAIF,IAAIA,IAAIA,GACZG,IAAI,IAAIH,IAAIA,IAAIC,GAChBG,IAAI,IAAIJ,IAAIC,IAAIA,GAChBI,IAAIJ,IAAIA,IAAIA;CAClB,OAAO;EACL,GAAGC,IAAII,EAAM,KAAK,IAAIH,IAAIG,EAAM,GAAG,IAAIF,IAAIE,EAAM,GAAG,IAAID,IAAIC,EAAM,GAAG;EACrE,GAAGJ,IAAII,EAAM,KAAK,IAAIH,IAAIG,EAAM,GAAG,IAAIF,IAAIE,EAAM,GAAG,IAAID,IAAIC,EAAM,GAAG;CACvE;AACF;AAwBA,SAAS,aAAa,GAAc,GAAqB;CACvD,IAAI,CAAC,OAAO,SAASC,EAAM,CAAC,KAAK,CAAC,OAAO,SAASA,EAAM,CAAC,GACvD,MAAM,IAAIC,EAAgB,aAAaC,EAAM,2CAA2CF,EAAM,EAAE,IAAIA,EAAM,EAAE,GAAG;AAEnH;AAEA,SAAS,gBAAgB,GAAe,GAAqB;CAC3D,IAAI,CAAC,OAA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AAGoB,EAAM,IAAIR,EAAM,QAAQZ,EAAE,CAAC,CAAC;EACtF,AAAI2B,IAAWH,MACb,IAAeG,GACf,IAAY3B;CAEhB;CAGA,IAAI6B,IAAK,KAAK,IAAI,IAAID,IAAY,KAAKtD,CAAc,GACjDwD,IAAK,KAAK,IAAI,IAAIF,IAAY,KAAKtD,CAAc;CACrD,KAAK,IAAI0B,IAAI,GAAGA,IAAI,IAAI,KAAK;EAC3B,IAAM+B,IAAKF,KAAMC,IAAKD,KAAM,GACtBG,IAAKF,KAAMA,IAAKD,KAAM,GACtBI,IAAK,QAAQpD,GAAOkD,CAAE,GACtBG,IAAK,QAAQrD,GAAOmD,CAAE;EAG5B,AAFW,KAAK,MAAMZ,EAAM,IAAIa,EAAG,GAAGb,EAAM,IAAIa,EAAG,CAE/C,IADO,KAAK,MAAMb,EAAM,IAAIc,EAAG,GAAGd,EAAM,IAAIc,EAAG,CAC1C,IACP,IAAKF,IAEL,IAAKD;CAET;CACA,IAAMvD,KAAKqD,IAAKC,KAAM,GAChBK,IAAU,QAAQtD,GAAOL,CAAC,GAC1BmD,IAAW,KAAK,MAAMP,EAAM,IAAIe,EAAQ,GAAGf,EAAM,IAAIe,EAAQ,CAAC;CAIpE,OAHIR,IAAWJ,IACN,OAEF;EAAE;EAAU,GAAG,gBAAgBX,GAAOpC,CAAC,IAAIoC,EAAM;CAAM;AAChE"}
|
package/dist/errors.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var WireError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},WireGraphError=class extends WireError{},WireConfigError=class extends WireError{};exports.WireConfigError=WireConfigError,exports.WireError=WireError,exports.WireGraphError=WireGraphError;
|
|
2
|
+
//# sourceMappingURL=errors.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":["message","opts"],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wire errors. Use `instanceof WireError` to catch any wire-originated error. */\nexport class WireError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a graph operation receives an edge that references a node id outside the supplied node set. */\nexport class WireGraphError extends WireError {}\n\n/** Thrown when routing options are invalid, such as a negative `handleLength`, `padding`, `stub`, or `bendPenalty`. */\nexport class WireConfigError extends WireError {}\n"],"mappings":"AACA,IAAa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,CAChD,MAAMA,EAASC,CAAI,EACnB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,eAAb,cAAoC,SAAU,CAAC,EAGlC,gBAAb,cAAqC,SAAU,CAAC,E"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Base class for all wire errors. Use `instanceof WireError` to catch any wire-originated error. */
|
|
2
|
+
export declare class WireError extends Error {
|
|
3
|
+
constructor(message: string, opts?: ErrorOptions);
|
|
4
|
+
}
|
|
5
|
+
/** Thrown when a graph operation receives an edge that references a node id outside the supplied node set. */
|
|
6
|
+
export declare class WireGraphError extends WireError {
|
|
7
|
+
}
|
|
8
|
+
/** Thrown when routing options are invalid, such as a negative `handleLength`, `padding`, `stub`, or `bendPenalty`. */
|
|
9
|
+
export declare class WireConfigError extends WireError {
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qGAAqG;AACrG,qBAAa,SAAU,SAAQ,KAAK;gBACtB,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;CAKjD;AAED,8GAA8G;AAC9G,qBAAa,cAAe,SAAQ,SAAS;CAAG;AAEhD,uHAAuH;AACvH,qBAAa,eAAgB,SAAQ,SAAS;CAAG"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var WireError = class extends Error {
|
|
3
|
+
constructor(e, t) {
|
|
4
|
+
super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
|
|
5
|
+
}
|
|
6
|
+
}, WireGraphError = class extends WireError {}, WireConfigError = class extends WireError {};
|
|
7
|
+
export { WireConfigError, WireError, WireGraphError };
|
|
8
|
+
|
|
9
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":["message","opts"],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wire errors. Use `instanceof WireError` to catch any wire-originated error. */\nexport class WireError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a graph operation receives an edge that references a node id outside the supplied node set. */\nexport class WireGraphError extends WireError {}\n\n/** Thrown when routing options are invalid, such as a negative `handleLength`, `padding`, `stub`, or `bendPenalty`. */\nexport class WireConfigError extends WireError {}\n"],"mappings":";AACA,IAAa,YAAb,cAA+B,MAAM;CACnC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAMA,GAASC,CAAI,GACnB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,iBAAb,cAAoC,UAAU,CAAC,GAGlC,kBAAb,cAAqC,UAAU,CAAC"}
|
package/dist/graph.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./_heap.cjs"),t=require("./errors.cjs");function buildNodeIndex(e){let n=new Map;for(let r of e){if(n.has(r))throw new t.WireGraphError(`Duplicate node id "${r}" in the node list.`);n.set(r,n.size)}return n}function validateEdgeEndpoints(e,n){for(let r of n){if(!e.has(r.from))throw new t.WireGraphError(`Edge from "${r.from}" to "${r.to}" references unknown node id "${r.from}".`);if(!e.has(r.to))throw new t.WireGraphError(`Edge from "${r.from}" to "${r.to}" references unknown node id "${r.to}".`)}}function topologicalOrder(n,r){let i=buildNodeIndex(n);validateEdgeEndpoints(i,r);let a=n.length,o=Array.from({length:a},()=>[]),s=Array(a).fill(0);for(let e of r){let t=i.get(e.from),n=i.get(e.to);o[t].push(n),s[n]=(s[n]??0)+1}let c=new e.MinHeap;for(let e=0;e<a;e+=1)s[e]===0&&c.push(e,e);let l=[];for(;c.size>0;){let e=c.pop();l.push(n[e]);for(let t of o[e]){let e=(s[t]??0)-1;s[t]=e,e===0&&c.push(t,t)}}if(l.length!==a)throw new t.WireGraphError(`Graph contains a cycle; no topological order exists. Use findCyclicGroups() to locate it.`);return l}function findCyclicGroups(e,t){let n=buildNodeIndex(e);validateEdgeEndpoints(n,t);let r=e.length,i=Array.from({length:r},()=>[]),a=Array(r).fill(!1);for(let e of t){let t=n.get(e.from),r=n.get(e.to);t===r&&(a[t]=!0),i[t].push(r)}let o=Array(r).fill(-1),s=Array(r).fill(-1),c=Array(r).fill(!1),l=[],u=[],d=0,strongConnect=t=>{let n=[{child:0,node:t}],enter=e=>{s[e]=d,o[e]=d,d+=1,l.push(e),c[e]=!0};for(enter(t);n.length>0;){let t=n[n.length-1],r=i[t.node];if(t.child<r.length){let e=r[t.child];t.child+=1,s[e]===-1?(enter(e),n.push({child:0,node:e})):c[e]&&(o[t.node]=Math.min(o[t.node],s[e]));continue}n.pop();let d=n[n.length-1];if(d&&(o[d.node]=Math.min(o[d.node],o[t.node])),o[t.node]===s[t.node]){let n=[],r=-1;do r=l.pop(),c[r]=!1,n.push(r);while(r!==t.node);(n.length>1||n.length===1&&a[n[0]])&&(n.sort((e,t)=>e-t),u.push(n.map(t=>e[t])))}}};for(let e=0;e<r;e+=1)s[e]===-1&&strongConnect(e);return u.sort((e,t)=>n.get(e[0])-n.get(t[0])),u}exports.findCyclicGroups=findCyclicGroups,exports.topologicalOrder=topologicalOrder;
|
|
2
|
+
//# sourceMappingURL=graph.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.cjs","names":["WireGraphError","MinHeap","require__heap","require_errors","index","id","nodeIds","edge","edges","count","outgoing","indegree","from","to","ready","i","order","node","next","remaining","selfLoop","lowLink","discovery","onStack","stack","cycles","time","work","root","frame","children","child","parent","component","member","a","b"],"sources":["../src/graph.ts"],"sourcesContent":["import { MinHeap } from './_heap.js';\nimport { WireGraphError } from './errors.js';\nimport type { Edge } from './types.js';\n\n/** Maps each node id to its input-order index; rejects duplicates so ordering contracts stay well-defined. */\nfunction buildNodeIndex(nodeIds: readonly string[]): Map<string, number> {\n const index = new Map<string, number>();\n for (const id of nodeIds) {\n if (index.has(id)) {\n throw new WireGraphError(`Duplicate node id \"${id}\" in the node list.`);\n }\n index.set(id, index.size);\n }\n return index;\n}\n\nfunction validateEdgeEndpoints(index: ReadonlyMap<string, number>, edges: readonly Edge[]): void {\n for (const edge of edges) {\n if (!index.has(edge.from)) {\n throw new WireGraphError(`Edge from \"${edge.from}\" to \"${edge.to}\" references unknown node id \"${edge.from}\".`);\n }\n if (!index.has(edge.to)) {\n throw new WireGraphError(`Edge from \"${edge.from}\" to \"${edge.to}\" references unknown node id \"${edge.to}\".`);\n }\n }\n}\n\n/**\n * Returns the node ids in topological order using Kahn's algorithm.\n *\n * Ties between ready nodes break by position in `nodeIds`, so the result is fully\n * deterministic for the same inputs. Parallel edges are tolerated; self-loops and\n * larger cycles make ordering impossible and throw `WireGraphError`.\n */\nexport function topologicalOrder(nodeIds: readonly string[], edges: readonly Edge[]): string[] {\n const index = buildNodeIndex(nodeIds);\n validateEdgeEndpoints(index, edges);\n\n const count = nodeIds.length;\n const outgoing: number[][] = Array.from({ length: count }, () => []);\n const indegree = new Array<number>(count).fill(0);\n for (const edge of edges) {\n const from = index.get(edge.from) as number;\n const to = index.get(edge.to) as number;\n outgoing[from]!.push(to);\n indegree[to] = (indegree[to] ?? 0) + 1;\n }\n\n // Ready nodes are always consumed in input order, never an arbitrary FIFO; the heap\n // keyed by input index keeps wide graphs at O(n log n).\n const ready = new MinHeap();\n for (let i = 0; i < count; i += 1) {\n if (indegree[i] === 0) ready.push(i, i);\n }\n\n const order: string[] = [];\n while (ready.size > 0) {\n const node = ready.pop();\n order.push(nodeIds[node] as string);\n for (const next of outgoing[node]!) {\n const remaining = (indegree[next] ?? 0) - 1;\n indegree[next] = remaining;\n if (remaining === 0) ready.push(next, next);\n }\n }\n\n if (order.length !== count) {\n throw new WireGraphError(\n 'Graph contains a cycle; no topological order exists. Use findCyclicGroups() to locate it.',\n );\n }\n return order;\n}\n\n/**\n * Returns the groups of nodes that are mutually reachable (strongly connected\n * components, Tarjan).\n *\n * Each returned group is an SCC with more than one node, or a single node carrying a\n * self-loop — never an exponential enumeration of elementary cycles. A group is a set\n * of nodes, not a path through them: members are sorted by input position, which does\n * not describe any particular cycle. Groups are ordered by the input position of their\n * first member, so results are deterministic.\n */\nexport function findCyclicGroups(nodeIds: readonly string[], edges: readonly Edge[]): string[][] {\n const index = buildNodeIndex(nodeIds);\n validateEdgeEndpoints(index, edges);\n\n const count = nodeIds.length;\n const outgoing: number[][] = Array.from({ length: count }, () => []);\n const selfLoop = new Array<boolean>(count).fill(false);\n for (const edge of edges) {\n const from = index.get(edge.from) as number;\n const to = index.get(edge.to) as number;\n if (from === to) selfLoop[from] = true;\n outgoing[from]!.push(to);\n }\n\n const lowLink = new Array<number>(count).fill(-1);\n const discovery = new Array<number>(count).fill(-1);\n const onStack = new Array<boolean>(count).fill(false);\n const stack: number[] = [];\n const cycles: string[][] = [];\n let time = 0;\n\n const strongConnect = (root: number): void => {\n // Iterative Tarjan: node editors can hold thousands of nodes, and recursion depth\n // must not scale with the longest dependency chain.\n const work: { node: number; child: number }[] = [{ child: 0, node: root }];\n const enter = (node: number): void => {\n discovery[node] = time;\n lowLink[node] = time;\n time += 1;\n stack.push(node);\n onStack[node] = true;\n };\n enter(root);\n\n while (work.length > 0) {\n const frame = work[work.length - 1] as { node: number; child: number };\n const children = outgoing[frame.node]!;\n if (frame.child < children.length) {\n const child = children[frame.child] as number;\n frame.child += 1;\n if (discovery[child] === -1) {\n enter(child);\n work.push({ child: 0, node: child });\n } else if (onStack[child]) {\n lowLink[frame.node] = Math.min(lowLink[frame.node] as number, discovery[child] as number);\n }\n continue;\n }\n\n work.pop();\n const parent = work[work.length - 1];\n if (parent) {\n lowLink[parent.node] = Math.min(lowLink[parent.node] as number, lowLink[frame.node] as number);\n }\n if ((lowLink[frame.node] as number) === (discovery[frame.node] as number)) {\n const component: number[] = [];\n let member = -1;\n do {\n member = stack.pop() as number;\n onStack[member] = false;\n component.push(member);\n } while (member !== frame.node);\n\n const isCyclic = component.length > 1 || (component.length === 1 && selfLoop[component[0] as number]);\n if (isCyclic) {\n component.sort((a, b) => a - b);\n cycles.push(component.map((member) => nodeIds[member] as string));\n }\n }\n }\n };\n\n for (let i = 0; i < count; i += 1) {\n if (discovery[i] === -1) strongConnect(i);\n }\n\n cycles.sort((a, b) => (index.get(a[0] as string) as number) - (index.get(b[0] as string) as number));\n return cycles;\n}\n"],"mappings":"A,yDAKA,SAAS,eAAe,EAAiD,CACvE,IAAMI,EAAQ,IAAI,IAClB,IAAK,IAAMC,KAAMC,EAAS,CACxB,GAAIF,EAAM,IAAIC,CAAE,EACd,MAAM,IAAIL,EAAAA,eAAe,sBAAsBK,EAAG,oBAAoB,EAExED,EAAM,IAAIC,EAAID,EAAM,IAAI,CAC1B,CACA,OAAOA,CACT,CAEA,SAAS,sBAAsB,EAAoC,EAA8B,CAC/F,IAAK,IAAMG,KAAQC,EAAO,CACxB,GAAI,CAACJ,EAAM,IAAIG,EAAK,IAAI,EACtB,MAAM,IAAIP,EAAAA,eAAe,cAAcO,EAAK,KAAK,QAAQA,EAAK,GAAG,gCAAgCA,EAAK,KAAK,GAAG,EAEhH,GAAI,CAACH,EAAM,IAAIG,EAAK,EAAE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O,MAAiBX,EAAQQ,EAAM,KAAe,GAE1FR,EAAQQ,EAAM,QAAsBP,EAAUO,EAAM,MAAkB,CACzE,IAAMI,EAAsB,CAAC,EACzBC,EAAS,GACb,EACE,GAASV,EAAM,IAAI,EACnB,EAAQU,GAAU,GAClBD,EAAU,KAAKC,CAAM,QACdA,IAAWL,EAAM,OAETI,EAAU,OAAS,GAAMA,EAAU,SAAW,GAAKb,EAASa,EAAU,OAErFA,EAAU,MAAM,EAAG,IAAME,EAAIC,CAAC,EAC9BX,EAAO,KAAKQ,EAAU,IAAK,GAAW3B,EAAQ4B,EAAiB,CAAC,EAEpE,CACF,CACF,EAEA,IAAK,IAAInB,EAAI,EAAGA,EAAIN,EAAO,GAAK,EAC1Ba,EAAUP,KAAO,IAAI,cAAcA,CAAC,EAI1C,OADAU,EAAO,MAAM,EAAG,IAAOrB,EAAM,IAAI+B,EAAE,EAAY,EAAgB/B,EAAM,IAAIgC,EAAE,EAAY,CAAY,EAC5FX,CACT,C"}
|
package/dist/graph.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Edge } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Returns the node ids in topological order using Kahn's algorithm.
|
|
4
|
+
*
|
|
5
|
+
* Ties between ready nodes break by position in `nodeIds`, so the result is fully
|
|
6
|
+
* deterministic for the same inputs. Parallel edges are tolerated; self-loops and
|
|
7
|
+
* larger cycles make ordering impossible and throw `WireGraphError`.
|
|
8
|
+
*/
|
|
9
|
+
export declare function topologicalOrder(nodeIds: readonly string[], edges: readonly Edge[]): string[];
|
|
10
|
+
/**
|
|
11
|
+
* Returns the groups of nodes that are mutually reachable (strongly connected
|
|
12
|
+
* components, Tarjan).
|
|
13
|
+
*
|
|
14
|
+
* Each returned group is an SCC with more than one node, or a single node carrying a
|
|
15
|
+
* self-loop — never an exponential enumeration of elementary cycles. A group is a set
|
|
16
|
+
* of nodes, not a path through them: members are sorted by input position, which does
|
|
17
|
+
* not describe any particular cycle. Groups are ordered by the input position of their
|
|
18
|
+
* first member, so results are deterministic.
|
|
19
|
+
*/
|
|
20
|
+
export declare function findCyclicGroups(nodeIds: readonly string[], edges: readonly Edge[]): string[][];
|
|
21
|
+
//# sourceMappingURL=graph.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../src/graph.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAyBvC;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,MAAM,EAAE,CAsC7F;AAED;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,MAAM,EAAE,EAAE,CA8E/F"}
|
package/dist/graph.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { MinHeap as e } from "./_heap.js";
|
|
2
|
+
import { WireGraphError as t } from "./errors.js";
|
|
3
|
+
// src/graph.ts
|
|
4
|
+
function buildNodeIndex(e) {
|
|
5
|
+
let n = /* @__PURE__ */ new Map();
|
|
6
|
+
for (let r of e) {
|
|
7
|
+
if (n.has(r)) throw new t(`Duplicate node id "${r}" in the node list.`);
|
|
8
|
+
n.set(r, n.size);
|
|
9
|
+
}
|
|
10
|
+
return n;
|
|
11
|
+
}
|
|
12
|
+
function validateEdgeEndpoints(e, n) {
|
|
13
|
+
for (let r of n) {
|
|
14
|
+
if (!e.has(r.from)) throw new t(`Edge from "${r.from}" to "${r.to}" references unknown node id "${r.from}".`);
|
|
15
|
+
if (!e.has(r.to)) throw new t(`Edge from "${r.from}" to "${r.to}" references unknown node id "${r.to}".`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function topologicalOrder(n, r) {
|
|
19
|
+
let i = buildNodeIndex(n);
|
|
20
|
+
validateEdgeEndpoints(i, r);
|
|
21
|
+
let a = n.length, o = Array.from({ length: a }, () => []), s = Array(a).fill(0);
|
|
22
|
+
for (let e of r) {
|
|
23
|
+
let t = i.get(e.from), n = i.get(e.to);
|
|
24
|
+
o[t].push(n), s[n] = (s[n] ?? 0) + 1;
|
|
25
|
+
}
|
|
26
|
+
let c = new e();
|
|
27
|
+
for (let e = 0; e < a; e += 1) s[e] === 0 && c.push(e, e);
|
|
28
|
+
let l = [];
|
|
29
|
+
for (; c.size > 0;) {
|
|
30
|
+
let e = c.pop();
|
|
31
|
+
l.push(n[e]);
|
|
32
|
+
for (let t of o[e]) {
|
|
33
|
+
let e = (s[t] ?? 0) - 1;
|
|
34
|
+
s[t] = e, e === 0 && c.push(t, t);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (l.length !== a) throw new t("Graph contains a cycle; no topological order exists. Use findCyclicGroups() to locate it.");
|
|
38
|
+
return l;
|
|
39
|
+
}
|
|
40
|
+
function findCyclicGroups(e, t) {
|
|
41
|
+
let n = buildNodeIndex(e);
|
|
42
|
+
validateEdgeEndpoints(n, t);
|
|
43
|
+
let r = e.length, i = Array.from({ length: r }, () => []), a = Array(r).fill(!1);
|
|
44
|
+
for (let e of t) {
|
|
45
|
+
let t = n.get(e.from), r = n.get(e.to);
|
|
46
|
+
t === r && (a[t] = !0), i[t].push(r);
|
|
47
|
+
}
|
|
48
|
+
let o = Array(r).fill(-1), s = Array(r).fill(-1), c = Array(r).fill(!1), l = [], u = [], d = 0, strongConnect = (t) => {
|
|
49
|
+
let n = [{
|
|
50
|
+
child: 0,
|
|
51
|
+
node: t
|
|
52
|
+
}], enter = (e) => {
|
|
53
|
+
s[e] = d, o[e] = d, d += 1, l.push(e), c[e] = !0;
|
|
54
|
+
};
|
|
55
|
+
for (enter(t); n.length > 0;) {
|
|
56
|
+
let t = n[n.length - 1], r = i[t.node];
|
|
57
|
+
if (t.child < r.length) {
|
|
58
|
+
let e = r[t.child];
|
|
59
|
+
t.child += 1, s[e] === -1 ? (enter(e), n.push({
|
|
60
|
+
child: 0,
|
|
61
|
+
node: e
|
|
62
|
+
})) : c[e] && (o[t.node] = Math.min(o[t.node], s[e]));
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
n.pop();
|
|
66
|
+
let d = n[n.length - 1];
|
|
67
|
+
if (d && (o[d.node] = Math.min(o[d.node], o[t.node])), o[t.node] === s[t.node]) {
|
|
68
|
+
let n = [], r = -1;
|
|
69
|
+
do
|
|
70
|
+
r = l.pop(), c[r] = !1, n.push(r);
|
|
71
|
+
while (r !== t.node);
|
|
72
|
+
(n.length > 1 || n.length === 1 && a[n[0]]) && (n.sort((e, t) => e - t), u.push(n.map((t) => e[t])));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
for (let e = 0; e < r; e += 1) s[e] === -1 && strongConnect(e);
|
|
77
|
+
return u.sort((e, t) => n.get(e[0]) - n.get(t[0])), u;
|
|
78
|
+
}
|
|
79
|
+
export { findCyclicGroups, topologicalOrder };
|
|
80
|
+
|
|
81
|
+
//# sourceMappingURL=graph.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.js","names":["index","id","nodeIds","WireGraphError","edge","edges","count","outgoing","indegree","from","to","ready","MinHeap","i","order","node","next","remaining","selfLoop","lowLink","discovery","onStack","stack","cycles","time","work","root","frame","children","child","parent","component","member","a","b"],"sources":["../src/graph.ts"],"sourcesContent":["import { MinHeap } from './_heap.js';\nimport { WireGraphError } from './errors.js';\nimport type { Edge } from './types.js';\n\n/** Maps each node id to its input-order index; rejects duplicates so ordering contracts stay well-defined. */\nfunction buildNodeIndex(nodeIds: readonly string[]): Map<string, number> {\n const index = new Map<string, number>();\n for (const id of nodeIds) {\n if (index.has(id)) {\n throw new WireGraphError(`Duplicate node id \"${id}\" in the node list.`);\n }\n index.set(id, index.size);\n }\n return index;\n}\n\nfunction validateEdgeEndpoints(index: ReadonlyMap<string, number>, edges: readonly Edge[]): void {\n for (const edge of edges) {\n if (!index.has(edge.from)) {\n throw new WireGraphError(`Edge from \"${edge.from}\" to \"${edge.to}\" references unknown node id \"${edge.from}\".`);\n }\n if (!index.has(edge.to)) {\n throw new WireGraphError(`Edge from \"${edge.from}\" to \"${edge.to}\" references unknown node id \"${edge.to}\".`);\n }\n }\n}\n\n/**\n * Returns the node ids in topological order using Kahn's algorithm.\n *\n * Ties between ready nodes break by position in `nodeIds`, so the result is fully\n * deterministic for the same inputs. Parallel edges are tolerated; self-loops and\n * larger cycles make ordering impossible and throw `WireGraphError`.\n */\nexport function topologicalOrder(nodeIds: readonly string[], edges: readonly Edge[]): string[] {\n const index = buildNodeIndex(nodeIds);\n validateEdgeEndpoints(index, edges);\n\n const count = nodeIds.length;\n const outgoing: number[][] = Array.from({ length: count }, () => []);\n const indegree = new Array<number>(count).fill(0);\n for (const edge of edges) {\n const from = index.get(edge.from) as number;\n const to = index.get(edge.to) as number;\n outgoing[from]!.push(to);\n indegree[to] = (indegree[to] ?? 0) + 1;\n }\n\n // Ready nodes are always consumed in input order, never an arbitrary FIFO; the heap\n // keyed by input index keeps wide graphs at O(n log n).\n const ready = new MinHeap();\n for (let i = 0; i < count; i += 1) {\n if (indegree[i] === 0) ready.push(i, i);\n }\n\n const order: string[] = [];\n while (ready.size > 0) {\n const node = ready.pop();\n order.push(nodeIds[node] as string);\n for (const next of outgoing[node]!) {\n const remaining = (indegree[next] ?? 0) - 1;\n indegree[next] = remaining;\n if (remaining === 0) ready.push(next, next);\n }\n }\n\n if (order.length !== count) {\n throw new WireGraphError(\n 'Graph contains a cycle; no topological order exists. Use findCyclicGroups() to locate it.',\n );\n }\n return order;\n}\n\n/**\n * Returns the groups of nodes that are mutually reachable (strongly connected\n * components, Tarjan).\n *\n * Each returned group is an SCC with more than one node, or a single node carrying a\n * self-loop — never an exponential enumeration of elementary cycles. A group is a set\n * of nodes, not a path through them: members are sorted by input position, which does\n * not describe any particular cycle. Groups are ordered by the input position of their\n * first member, so results are deterministic.\n */\nexport function findCyclicGroups(nodeIds: readonly string[], edges: readonly Edge[]): string[][] {\n const index = buildNodeIndex(nodeIds);\n validateEdgeEndpoints(index, edges);\n\n const count = nodeIds.length;\n const outgoing: number[][] = Array.from({ length: count }, () => []);\n const selfLoop = new Array<boolean>(count).fill(false);\n for (const edge of edges) {\n const from = index.get(edge.from) as number;\n const to = index.get(edge.to) as number;\n if (from === to) selfLoop[from] = true;\n outgoing[from]!.push(to);\n }\n\n const lowLink = new Array<number>(count).fill(-1);\n const discovery = new Array<number>(count).fill(-1);\n const onStack = new Array<boolean>(count).fill(false);\n const stack: number[] = [];\n const cycles: string[][] = [];\n let time = 0;\n\n const strongConnect = (root: number): void => {\n // Iterative Tarjan: node editors can hold thousands of nodes, and recursion depth\n // must not scale with the longest dependency chain.\n const work: { node: number; child: number }[] = [{ child: 0, node: root }];\n const enter = (node: number): void => {\n discovery[node] = time;\n lowLink[node] = time;\n time += 1;\n stack.push(node);\n onStack[node] = true;\n };\n enter(root);\n\n while (work.length > 0) {\n const frame = work[work.length - 1] as { node: number; child: number };\n const children = outgoing[frame.node]!;\n if (frame.child < children.length) {\n const child = children[frame.child] as number;\n frame.child += 1;\n if (discovery[child] === -1) {\n enter(child);\n work.push({ child: 0, node: child });\n } else if (onStack[child]) {\n lowLink[frame.node] = Math.min(lowLink[frame.node] as number, discovery[child] as number);\n }\n continue;\n }\n\n work.pop();\n const parent = work[work.length - 1];\n if (parent) {\n lowLink[parent.node] = Math.min(lowLink[parent.node] as number, lowLink[frame.node] as number);\n }\n if ((lowLink[frame.node] as number) === (discovery[frame.node] as number)) {\n const component: number[] = [];\n let member = -1;\n do {\n member = stack.pop() as number;\n onStack[member] = false;\n component.push(member);\n } while (member !== frame.node);\n\n const isCyclic = component.length > 1 || (component.length === 1 && selfLoop[component[0] as number]);\n if (isCyclic) {\n component.sort((a, b) => a - b);\n cycles.push(component.map((member) => nodeIds[member] as string));\n }\n }\n }\n };\n\n for (let i = 0; i < count; i += 1) {\n if (discovery[i] === -1) strongConnect(i);\n }\n\n cycles.sort((a, b) => (index.get(a[0] as string) as number) - (index.get(b[0] as string) as number));\n return cycles;\n}\n"],"mappings":";;;AAKA,SAAS,eAAe,GAAiD;CACvE,IAAMA,oBAAQ,IAAI,IAAoB;CACtC,KAAK,IAAMC,KAAMC,GAAS;EACxB,IAAIF,EAAM,IAAIC,CAAE,GACd,MAAM,IAAIE,EAAe,sBAAsBF,EAAG,oBAAoB;EAExE,EAAM,IAAIA,GAAID,EAAM,IAAI;CAC1B;CACA,OAAOA;AACT;AAEA,SAAS,sBAAsB,GAAoC,GAA8B;CAC/F,KAAK,IAAMI,KAAQC,GAAO;EACxB,IAAI,CAACL,EAAM,IAAII,EAAK,IAAI,GACtB,MAAM,IAAID,EAAe,cAAcC,EAAK,KAAK,QAAQA,EAAK,GAAG,gCAAgCA,EAAK,KAAK,GAAG;EAEhH,IAAI,CAACJ,EAAM,IAAII,EAAK,EAAE,GACpB,MAAM,IAAID,EAAe,cAAcC,EAAK,KAAK,QAAQA,EAAK,GAAG,gCAAgCA,EAAK,GAAG,GAAG;CAEhH;AACF;AASA,SAAgB,iBAAiB,GAA4B,GAAkC;CAC7F,IAAMJ,IAAQ,eAAeE,CAAO;CACpC,sBAAsBF,GAAOK,CAAK;CAElC,IAAMC,IAAQJ,EAAQ,QAChBK,IAAuB,MAAM,KAAK,EAAE,QAAQD,EAAM,SAAS,CAAC,CAAC,GAC7DE,IAAe,MAAcF,CAAK,CAAC,CAAC,KAAK,CAAC;CAChD,KAAK,IAAMF,KAAQC,GAAO;EACxB,IAAMI,IAAOT,EAAM,IAAII,EAAK,IAAI,GAC1BM,IAAKV,EAAM,IAAII,EAAK,EAAE;EAE5B,AADAG,EAASE,EAAK,CAAE,KAAKC,CAAE,GACvB,EAASA,MAAOF,EAASE,MAAO,KAAK;CACvC;CAIA,IAAMC,IAAQ,IAAIC,EAAQ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AE,EAAY,IAAgBjC,EAAM,IAAIkC,EAAE,EAAY,CAAY,GAC5FX;AACT"}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./bezier.cjs"),t=require("./edit.cjs"),n=require("./errors.cjs"),r=require("./graph.cjs"),i=require("./orthogonal.cjs"),a=require("./path.cjs"),o=require("./ports.cjs");exports.WireConfigError=n.WireConfigError,exports.WireError=n.WireError,exports.WireGraphError=n.WireGraphError,exports.arrowhead=t.arrowhead,exports.bezierRoute=e.bezierRoute,exports.bezierToSvgPath=a.bezierToSvgPath,exports.findCyclicGroups=r.findCyclicGroups,exports.floatingSide=o.floatingSide,exports.hitBezier=t.hitBezier,exports.hitPolyline=t.hitPolyline,exports.orthogonalRoute=i.orthogonalRoute,exports.pointOnBezier=t.pointOnBezier,exports.pointOnPolyline=t.pointOnPolyline,exports.polylineToSvgPath=a.polylineToSvgPath,exports.portAnchor=o.portAnchor,exports.topologicalOrder=r.topologicalOrder;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { type BezierRouteOptions, bezierRoute } from './bezier.js';
|
|
2
|
+
export { type ArrowheadOptions, arrowhead, type HitOptions, type HitResult, hitBezier, hitPolyline, pointOnBezier, pointOnPolyline, } from './edit.js';
|
|
3
|
+
export { WireConfigError, WireError, WireGraphError } from './errors.js';
|
|
4
|
+
export { findCyclicGroups, topologicalOrder } from './graph.js';
|
|
5
|
+
export { type OrthogonalRouteOptions, orthogonalRoute } from './orthogonal.js';
|
|
6
|
+
export { bezierToSvgPath, type PolylinePathOptions, polylineToSvgPath } from './path.js';
|
|
7
|
+
export { floatingSide, portAnchor } from './ports.js';
|
|
8
|
+
export type { CubicBezier, Edge, Point, PortAnchor, PortSide, Rect } from './types.js';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EACL,KAAK,gBAAgB,EACrB,SAAS,EACT,KAAK,UAAU,EACf,KAAK,SAAS,EACd,SAAS,EACT,WAAW,EACX,aAAa,EACb,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,KAAK,sBAAsB,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,KAAK,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AACzF,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACtD,YAAY,EAAE,WAAW,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { bezierRoute as e } from "./bezier.js";
|
|
2
|
+
import { arrowhead as t, hitBezier as n, hitPolyline as r, pointOnBezier as i, pointOnPolyline as a } from "./edit.js";
|
|
3
|
+
import { WireConfigError as o, WireError as s, WireGraphError as c } from "./errors.js";
|
|
4
|
+
import { findCyclicGroups as l, topologicalOrder as u } from "./graph.js";
|
|
5
|
+
import { orthogonalRoute as d } from "./orthogonal.js";
|
|
6
|
+
import { bezierToSvgPath as f, polylineToSvgPath as p } from "./path.js";
|
|
7
|
+
import { floatingSide as m, portAnchor as h } from "./ports.js";
|
|
8
|
+
export { o as WireConfigError, s as WireError, c as WireGraphError, t as arrowhead, e as bezierRoute, f as bezierToSvgPath, l as findCyclicGroups, m as floatingSide, n as hitBezier, r as hitPolyline, d as orthogonalRoute, i as pointOnBezier, a as pointOnPolyline, p as polylineToSvgPath, h as portAnchor, u as topologicalOrder };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./_heap.cjs"),t=require("./_sides.cjs"),n=require("./errors.cjs");var r=5;function padRect(e,t){return{x0:e.x-t,x1:e.x+e.width+t,y0:e.y-t,y1:e.y+e.height+t}}function pointBlocked(e,t,n){for(let r of n)if(e>r.x0&&e<r.x1&&t>r.y0&&t<r.y1)return!0;return!1}function spanBlocked(e,t,n){let r=Math.min(e.x,t.x),i=Math.max(e.x,t.x),a=Math.min(e.y,t.y),o=Math.max(e.y,t.y);for(let e of n)if(a===o){if(a>e.y0&&a<e.y1&&r<e.x1&&e.x0<i)return!0}else if(r===i&&r>e.x0&&r<e.x1&&a<e.y1&&e.y0<o)return!0;return!1}function ownersOf(e,t){return t.filter(t=>pointBlocked(e.x,e.y,[t]))}function escapeDistance(e,n,r){let i=t.DELTA[n],a=0;for(let t of r){let n=i.x>0?t.x1-e.x:i.x<0?e.x-t.x0:i.y>0?t.y1-e.y:e.y-t.y0;n>a&&(a=n)}return a}function orthogonalRoute(i,a,o={}){let s=o.padding??8,c=o.bendPenalty??12,l=o.stub??16;if(!Number.isFinite(s)||s<0)throw new n.WireConfigError(`Orthogonal padding must be a finite non-negative number, received ${String(s)}.`);if(!Number.isFinite(c)||c<0)throw new n.WireConfigError(`Bend penalty must be a finite non-negative number, received ${String(c)}.`);if(!Number.isFinite(l)||l<0)throw new n.WireConfigError(`Stub must be a finite non-negative number, received ${String(l)}.`);let u={x:i.x,y:i.y},d={x:a.x,y:a.y};if(u.x===d.x&&u.y===d.y)return[u];let f=(o.obstacles??[]).map(e=>padRect(e,s)),p=ownersOf(u,f),m=ownersOf(d,f),othersFor=e=>e.length===0?f:f.filter(t=>!e.includes(t)),h=othersFor(p),g=othersFor(m),_=t.SIDE_DIR[i.side],v=t.SIDE_DIR[a.side];if(u.x===d.x||u.y===d.y){let e=u.x===d.x?d.y>u.y?t.Dir.Down:t.Dir.Up:d.x>u.x?t.Dir.Right:t.Dir.Left,n=l===0&&p.length===0||_===e,r=l===0&&m.length===0||t.OPPOSITE[v]===e,i=f.filter(e=>!p.includes(e)&&!m.includes(e));if(n&&r&&!spanBlocked(u,d,i))return[u,d]}let exitTip=(e,n,r,i)=>{let a=t.SIDE_VECTOR[n],o=Math.max(l,escapeDistance(e,r,i));return{x:e.x+a.x*o,y:e.y+a.y*o}},y=exitTip(u,i.side,_,p),b=exitTip(d,a.side,v,m);if(spanBlocked(u,y,h)||spanBlocked(d,b,g))return null;let x=y,S=b,C=l>0||p.length>0?_:t.Dir.None,w=l>0||m.length>0?v:t.Dir.None,T=new Set([x.x,S.x]),E=new Set([x.y,S.y]);for(let e of f)T.add(e.x0),T.add(e.x1),E.add(e.y0),E.add(e.y1);let D=[...T].sort((e,t)=>e-t),O=[...E].sort((e,t)=>e-t),k=D.length,A=O.length,j=k*A,nodeX=e=>D[e%k],nodeY=e=>O[Math.floor(e/k)],nodeAt=(e,t)=>O.indexOf(t)*k+D.indexOf(e),M=nodeAt(x.x,x.y),N=nodeAt(S.x,S.y);if(pointBlocked(nodeX(M),nodeY(M),f)||pointBlocked(nodeX(N),nodeY(N),f))return null;let P=j*r,F=new Float64Array(P).fill(1/0),I=new Int32Array(P).fill(-1),L=new Uint8Array(P),heuristic=e=>Math.abs(nodeX(e)-S.x)+Math.abs(nodeY(e)-S.y),stateId=(e,t)=>e*r+t,R=new e.MinHeap,z=stateId(M,C);F[z]=0,R.push(heuristic(M),z);let B=-1;for(;R.size>0&&B===-1;){let e=R.pop();if(L[e])continue;L[e]=1;let n=Math.floor(e/r),i=e%r;if(n===N&&(w===t.Dir.None||i!==w)){B=e;break}let a=nodeX(n),o=nodeY(n),s=[[t.Dir.Left,n-1],[t.Dir.Right,n+1],[t.Dir.Up,n-k],[t.Dir.Down,n+k]];for(let[r,l]of s){if(r===t.Dir.Left&&n%k===0||r===t.Dir.Right&&n%k===k-1||r===t.Dir.Up&&n<k||r===t.Dir.Down&&n>=(A-1)*k)continue;let s=nodeX(l),u=nodeY(l);if(pointBlocked(s,u,f)||spanBlocked({x:a,y:o},{x:s,y:u},f))continue;let d=Math.abs(s-a)+Math.abs(u-o),p=i!==t.Dir.None&&i!==r?c:0,m=F[e]+d+p,h=stateId(l,r);m<F[h]&&(F[h]=m,I[h]=e,R.push(m+heuristic(l),h))}}if(B===-1)return null;let V=[];for(let e=B;e!==-1;e=I[e])V.push(Math.floor(e/r));V.reverse();let H=[u,...V.filter((e,t)=>{if(t===0||t===V.length-1)return!0;let n=V[t-1],r=V[t+1];return!(nodeX(n)===nodeX(e)&&nodeX(e)===nodeX(r)||nodeY(n)===nodeY(e)&&nodeY(e)===nodeY(r))}).map(e=>({x:nodeX(e),y:nodeY(e)})),d];for(let e=1;e<H.length-1;e+=1){let t=H[e-1],n=H[e],r=H[e+1];(t.x===n.x&&n.x===r.x||t.y===n.y&&n.y===r.y)&&(H.splice(e,1),--e)}return H}exports.orthogonalRoute=orthogonalRoute;
|
|
2
|
+
//# sourceMappingURL=orthogonal.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orthogonal.cjs","names":["DELTA","WireConfigError","SIDE_DIR","Dir","OPPOSITE","SIDE_VECTOR","MinHeap","require__heap","require__sides","require_errors","DIR_COUNT","rect","padding","obstacles","px","py","xLow","a","b","xHigh","yLow","yHigh","point","delta","dir","distance","owners","along","options","bendPenalty","stub","start","from","goal","to","startOwners","goalOwners","startOthers","goalOthers","fromDir","toDir","agreesWithStart","agreesWithGoal","freeSpan","vector","side","fromTip","toTip","routeStart","routeGoal","startDir","forbiddenIncoming","xs","ys","xLines","yLines","columns","rows","nodeCount","node","y","x","startNode","goalNode","stateCount","gScore","parent","closed","open","startState","goalState","current","incoming","cx","cy","candidates","neighbor","nx","ny","step","bend","nextScore","nextState","nodes","state","points","i","prev","next","cur"],"sources":["../src/orthogonal.ts"],"sourcesContent":["import { MinHeap } from './_heap.js';\nimport { DELTA, Dir, type Move, OPPOSITE, SIDE_DIR, SIDE_VECTOR } from './_sides.js';\nimport { WireConfigError } from './errors.js';\nimport type { Point, PortAnchor, PortSide, Rect } from './types.js';\n\n/** Configuration for `orthogonalRoute()`. */\nexport interface OrthogonalRouteOptions {\n /** Cost added per bend, on top of path length. Defaults to 12. */\n bendPenalty?: number;\n /**\n * Rectangles the route must not cross — typically every node's raw bounding box.\n * `padding` supplies the clearance, so do not inflate the rects yourself. The\n * obstacles a port sits inside are exempted for that port's straight exit segment\n * only; the rest of the route still avoids them.\n */\n obstacles?: readonly Rect[];\n /** Distance obstacles are inflated by; routes may travel along the inflated boundary. Defaults to 8. */\n padding?: number;\n /**\n * Distance the route runs straight out of a port before it may bend, and straight\n * into the target port. Defaults to 16; `0` disables the directional stubs (a port\n * inside an obstacle still exits straight to clear it).\n */\n stub?: number;\n}\n\n/** Number of direction slots packed per grid node in a state id (`node * DIR_COUNT + dir`). */\nconst DIR_COUNT = 5;\n\ninterface PaddedRect {\n x0: number;\n x1: number;\n y0: number;\n y1: number;\n}\n\nfunction padRect(rect: Rect, padding: number): PaddedRect {\n return {\n x0: rect.x - padding,\n x1: rect.x + rect.width + padding,\n y0: rect.y - padding,\n y1: rect.y + rect.height + padding,\n };\n}\n\n/** A point exactly on a padded boundary is free: routes are allowed to hug obstacle margins. */\nfunction pointBlocked(px: number, py: number, obstacles: readonly PaddedRect[]): boolean {\n for (const rect of obstacles) {\n if (px > rect.x0 && px < rect.x1 && py > rect.y0 && py < rect.y1) return true;\n }\n return false;\n}\n\n/** Whether the open axis-aligned span from `a` to `b` passes through an obstacle interior. */\nfunction spanBlocked(a: Point, b: Point, obstacles: readonly PaddedRect[]): boolean {\n const xLow = Math.min(a.x, b.x);\n const xHigh = Math.max(a.x, b.x);\n const yLow = Math.min(a.y, b.y);\n const yHigh = Math.max(a.y, b.y);\n for (const rect of obstacles) {\n if (yLow === yHigh) {\n if (yLow > rect.y0 && yLow < rect.y1 && xLow < rect.x1 && rect.x0 < xHigh) return true;\n } else if (xLow === xHigh && xLow > rect.x0 && xLow < rect.x1 && yLow < rect.y1 && rect.y0 < yHigh) {\n return true;\n }\n }\n return false;\n}\n\n/** Obstacles whose padded interior contains `point` — the obstacles that \"own\" the port. */\nfunction ownersOf(point: Point, obstacles: readonly PaddedRect[]): PaddedRect[] {\n return obstacles.filter((rect) => pointBlocked(point.x, point.y, [rect]));\n}\n\n/**\n * Distance from `point` to the padded boundary of `owners`, measured along `dir`.\n * Zero when the point is outside every owner.\n */\nfunction escapeDistance(point: Point, dir: Move, owners: readonly PaddedRect[]): number {\n const delta = DELTA[dir];\n let distance = 0;\n for (const rect of owners) {\n const along =\n delta.x > 0\n ? rect.x1 - point.x\n : delta.x < 0\n ? point.x - rect.x0\n : delta.y > 0\n ? rect.y1 - point.y\n : point.y - rect.y0;\n if (along > distance) distance = along;\n }\n return distance;\n}\n\n/**\n * Routes a Manhattan (axis-aligned) polyline between two ports over a visibility grid\n * built from the obstacle corners, using A* with a per-bend penalty.\n *\n * Pass every node's raw rect as `obstacles`; `padding` supplies the clearance. A port\n * that sits inside an obstacle (its own node, since ports are on node boundaries) is\n * exempted only for the straight exit segment out of that port; the searched route\n * never enters any padded obstacle interior, including its own nodes.\n *\n * Returns the waypoint polyline with `from` first and `to` last, or `null` when every\n * route is blocked (including a blocked exit segment). Cost is path length plus\n * `bendPenalty` per bend, so among equal length routes the one with fewer bends wins.\n * Expansion order is fully deterministic.\n */\nexport function orthogonalRoute(\n from: PortAnchor,\n to: PortAnchor,\n options: OrthogonalRouteOptions = {},\n): Point[] | null {\n const padding = options.padding ?? 8;\n const bendPenalty = options.bendPenalty ?? 12;\n const stub = options.stub ?? 16;\n if (!Number.isFinite(padding) || padding < 0) {\n throw new WireConfigError(`Orthogonal padding must be a finite non-negative number, received ${String(padding)}.`);\n }\n if (!Number.isFinite(bendPenalty) || bendPenalty < 0) {\n throw new WireConfigError(`Bend penalty must be a finite non-negative number, received ${String(bendPenalty)}.`);\n }\n if (!Number.isFinite(stub) || stub < 0) {\n throw new WireConfigError(`Stub must be a finite non-negative number, received ${String(stub)}.`);\n }\n\n const start: Point = { x: from.x, y: from.y };\n const goal: Point = { x: to.x, y: to.y };\n if (start.x === goal.x && start.y === goal.y) return [start];\n\n const obstacles = (options.obstacles ?? []).map((rect) => padRect(rect, padding));\n const startOwners = ownersOf(start, obstacles);\n const goalOwners = ownersOf(goal, obstacles);\n // Obstacles to check against for a segment leaving `owners`: everything except those owners.\n const othersFor = (owners: readonly PaddedRect[]): PaddedRect[] =>\n owners.length === 0 ? obstacles : obstacles.filter((rect) => !owners.includes(rect));\n const startOthers = othersFor(startOwners);\n const goalOthers = othersFor(goalOwners);\n\n // Port stubs: the route leaves the source port straight along its side and enters\n // the target port along that side, so wires never peel off a port sideways. A port\n // inside an obstacle always exits straight far enough to clear the obstacle margin,\n // even when `stub` is smaller than that distance (or zero).\n const fromDir = SIDE_DIR[from.side];\n const toDir = SIDE_DIR[to.side];\n\n // Straight shot: when the direct segment agrees with both port sides and is clear\n // of every obstacle except the endpoints' own owners, it is optimal by construction\n // (also covers facing ports closer than two stubs).\n if (start.x === goal.x || start.y === goal.y) {\n const dir: Move =\n start.x !== goal.x ? (goal.x > start.x ? Dir.Right : Dir.Left) : goal.y > start.y ? Dir.Down : Dir.Up;\n // A port with no forced exit (no stub, no owner to escape) accepts any direction.\n const agreesWithStart = (stub === 0 && startOwners.length === 0) || fromDir === dir;\n const agreesWithGoal = (stub === 0 && goalOwners.length === 0) || OPPOSITE[toDir] === dir;\n const freeSpan = obstacles.filter((rect) => !startOwners.includes(rect) && !goalOwners.includes(rect));\n if (agreesWithStart && agreesWithGoal && !spanBlocked(start, goal, freeSpan)) return [start, goal];\n }\n\n const exitTip = (point: Point, side: PortSide, dir: Move, owners: readonly PaddedRect[]): Point => {\n const vector = SIDE_VECTOR[side];\n const distance = Math.max(stub, escapeDistance(point, dir, owners));\n return { x: point.x + vector.x * distance, y: point.y + vector.y * distance };\n };\n const fromTip = exitTip(start, from.side, fromDir, startOwners);\n const toTip = exitTip(goal, to.side, toDir, goalOwners);\n\n // The exit segment may cross its own owners but no other obstacle; a blocked exit\n // means the port is walled in, so no route exists.\n if (spanBlocked(start, fromTip, startOthers)) return null;\n if (spanBlocked(goal, toTip, goalOthers)) return null;\n\n const routeStart = fromTip;\n const routeGoal = toTip;\n // `stub: 0` disables the directional stubs unless an owner escape forced one.\n const startDir: Dir = stub > 0 || startOwners.length > 0 ? fromDir : Dir.None;\n // The route must not arrive at the goal tip moving along the port's outward\n // direction (that would overshoot the port and double back); any other incoming\n // direction continues smoothly into the final stub segment.\n const forbiddenIncoming: Dir = stub > 0 || goalOwners.length > 0 ? toDir : Dir.None;\n\n // Grid lines: every obstacle edge plus the exit tips' own rows and columns.\n const xs = new Set<number>([routeStart.x, routeGoal.x]);\n const ys = new Set<number>([routeStart.y, routeGoal.y]);\n for (const rect of obstacles) {\n xs.add(rect.x0);\n xs.add(rect.x1);\n ys.add(rect.y0);\n ys.add(rect.y1);\n }\n const xLines = [...xs].sort((a, b) => a - b);\n const yLines = [...ys].sort((a, b) => a - b);\n const columns = xLines.length;\n const rows = yLines.length;\n const nodeCount = columns * rows;\n\n const nodeX = (node: number): number => xLines[node % columns] as number;\n const nodeY = (node: number): number => yLines[Math.floor(node / columns)] as number;\n const nodeAt = (x: number, y: number): number => yLines.indexOf(y) * columns + xLines.indexOf(x);\n\n const startNode = nodeAt(routeStart.x, routeStart.y);\n const goalNode = nodeAt(routeGoal.x, routeGoal.y);\n if (pointBlocked(nodeX(startNode), nodeY(startNode), obstacles)) return null;\n if (pointBlocked(nodeX(goalNode), nodeY(goalNode), obstacles)) return null;\n\n // State = grid node × incoming direction (Dir.None only for the start).\n const stateCount = nodeCount * DIR_COUNT;\n const gScore = new Float64Array(stateCount).fill(Number.POSITIVE_INFINITY);\n const parent = new Int32Array(stateCount).fill(-1);\n const closed = new Uint8Array(stateCount);\n\n const heuristic = (node: number): number => Math.abs(nodeX(node) - routeGoal.x) + Math.abs(nodeY(node) - routeGoal.y);\n const stateId = (node: number, dir: Dir): number => node * DIR_COUNT + dir;\n\n const open = new MinHeap();\n const startState = stateId(startNode, startDir);\n gScore[startState] = 0;\n open.push(heuristic(startNode), startState);\n\n let goalState = -1;\n while (open.size > 0 && goalState === -1) {\n const current = open.pop();\n if (closed[current]) continue;\n closed[current] = 1;\n\n const node = Math.floor(current / DIR_COUNT);\n const incoming = (current % DIR_COUNT) as Dir;\n if (node === goalNode && (forbiddenIncoming === Dir.None || incoming !== forbiddenIncoming)) {\n goalState = current;\n break;\n }\n\n const cx = nodeX(node);\n const cy = nodeY(node);\n const candidates: readonly [Dir, number][] = [\n [Dir.Left, node - 1],\n [Dir.Right, node + 1],\n [Dir.Up, node - columns],\n [Dir.Down, node + columns],\n ];\n for (const [dir, neighbor] of candidates) {\n // Validate grid bounds: Left/Right must stay in the same row, Up/Down in the same column.\n if (dir === Dir.Left && node % columns === 0) continue;\n if (dir === Dir.Right && node % columns === columns - 1) continue;\n if (dir === Dir.Up && node < columns) continue;\n if (dir === Dir.Down && node >= (rows - 1) * columns) continue;\n\n const nx = nodeX(neighbor);\n const ny = nodeY(neighbor);\n if (pointBlocked(nx, ny, obstacles)) continue;\n if (spanBlocked({ x: cx, y: cy }, { x: nx, y: ny }, obstacles)) continue;\n\n const step = Math.abs(nx - cx) + Math.abs(ny - cy);\n const bend = incoming !== Dir.None && incoming !== dir ? bendPenalty : 0;\n const nextScore = (gScore[current] as number) + step + bend;\n const nextState = stateId(neighbor, dir);\n if (nextScore < (gScore[nextState] as number)) {\n gScore[nextState] = nextScore;\n parent[nextState] = current;\n open.push(nextScore + heuristic(neighbor), nextState);\n }\n }\n }\n\n if (goalState === -1) return null;\n\n const nodes: number[] = [];\n for (let state = goalState; state !== -1; state = parent[state] as number) {\n nodes.push(Math.floor(state / DIR_COUNT));\n }\n nodes.reverse();\n\n // Collapse collinear runs so the polyline carries waypoints only at bends.\n const collapsed: Point[] = nodes\n .filter((node, i) => {\n if (i === 0 || i === nodes.length - 1) return true;\n const prev = nodes[i - 1] as number;\n const next = nodes[i + 1] as number;\n const collinear =\n (nodeX(prev) === nodeX(node) && nodeX(node) === nodeX(next)) ||\n (nodeY(prev) === nodeY(node) && nodeY(node) === nodeY(next));\n return !collinear;\n })\n .map((node) => ({ x: nodeX(node), y: nodeY(node) }));\n\n // Re-attach the exact ports outside the stub tips, then drop stub tips that are\n // collinear with their neighbours so a straight-through route keeps two points.\n const points = [start, ...collapsed, goal];\n for (let i = 1; i < points.length - 1; i += 1) {\n const prev = points[i - 1] as Point;\n const cur = points[i] as Point;\n const next = points[i + 1] as Point;\n if ((prev.x === cur.x && cur.x === next.x) || (prev.y === cur.y && cur.y === next.y)) {\n points.splice(i, 1);\n i -= 1;\n }\n }\n return points;\n}\n"],"mappings":"A,mFA2BA,IAAMU,EAAY,EASlB,SAAS,QAAQ,EAAY,EAA6B,CACxD,MAAO,CACL,GAAIC,EAAK,EAAIC,EACb,GAAID,EAAK,EAAIA,EAAK,MAAQC,EAC1B,GAAID,EAAK,EAAIC,EACb,GAAID,EAAK,EAAIA,EAAK,OAASC,CAC7B,CACF,CAGA,SAAS,aAAa,EAAY,EAAY,EAA2C,CACvF,IAAK,IAAMD,KAAQE,EACjB,GAAIC,EAAKH,EAAK,IAAMG,EAAKH,EAAK,IAAMI,EAAKJ,EAAK,IAAMI,EAAKJ,EAAK,GAAI,MAAO,GAE3E,MAAO,EACT,CAGA,SAAS,YAAY,EAAU,EAAU,EAA2C,CAClF,IAAMK,EAAO,KAAK,IAAIC,EAAE,EAAGC,EAAE,CAAC,EACxBC,EAAQ,KAAK,IAAIF,EAAE,EAAGC,EAAE,CAAC,EACzBE,EAAO,KAAK,IAAIH,EAAE,EAAGC,EAAE,CAAC,EACxBG,EAAQ,KAAK,IAAIJ,EAAE,EAAGC,EAAE,CAAC,EAC/B,IAAK,IAAMP,KAAQE,EACjB,GAA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AAG,MAAO,GAC9C,IAAMI,EAAOJ,EAAMG,EAAI,GACjBE,EAAOL,EAAMG,EAAI,GAIvB,MAAO,EAFJ,MAAMC,CAAI,IAAM,MAAM5B,CAAI,GAAK,MAAMA,CAAI,IAAM,MAAM6B,CAAI,GACzD,MAAMD,CAAI,IAAM,MAAM5B,CAAI,GAAK,MAAMA,CAAI,IAAM,MAAM6B,CAAI,EAE9D,CAAC,CAAC,CACD,IAAK,IAAU,CAAE,EAAG,MAAM7B,CAAI,EAAG,EAAG,MAAMA,CAAI,CAAE,EAIzB,EAAW1B,CAAI,EACzC,IAAK,IAAIqD,EAAI,EAAGA,EAAID,EAAO,OAAS,EAAG,GAAK,EAAG,CAC7C,IAAME,EAAOF,EAAOC,EAAI,GAClBG,EAAMJ,EAAOC,GACbE,EAAOH,EAAOC,EAAI,IACnBC,EAAK,IAAME,EAAI,GAAKA,EAAI,IAAMD,EAAK,GAAOD,EAAK,IAAME,EAAI,GAAKA,EAAI,IAAMD,EAAK,KAChFH,EAAO,OAAOC,EAAG,CAAC,EAClB,IAEJ,CACA,OAAOD,CACT,C"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { Point, PortAnchor, Rect } from './types.js';
|
|
2
|
+
/** Configuration for `orthogonalRoute()`. */
|
|
3
|
+
export interface OrthogonalRouteOptions {
|
|
4
|
+
/** Cost added per bend, on top of path length. Defaults to 12. */
|
|
5
|
+
bendPenalty?: number;
|
|
6
|
+
/**
|
|
7
|
+
* Rectangles the route must not cross — typically every node's raw bounding box.
|
|
8
|
+
* `padding` supplies the clearance, so do not inflate the rects yourself. The
|
|
9
|
+
* obstacles a port sits inside are exempted for that port's straight exit segment
|
|
10
|
+
* only; the rest of the route still avoids them.
|
|
11
|
+
*/
|
|
12
|
+
obstacles?: readonly Rect[];
|
|
13
|
+
/** Distance obstacles are inflated by; routes may travel along the inflated boundary. Defaults to 8. */
|
|
14
|
+
padding?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Distance the route runs straight out of a port before it may bend, and straight
|
|
17
|
+
* into the target port. Defaults to 16; `0` disables the directional stubs (a port
|
|
18
|
+
* inside an obstacle still exits straight to clear it).
|
|
19
|
+
*/
|
|
20
|
+
stub?: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Routes a Manhattan (axis-aligned) polyline between two ports over a visibility grid
|
|
24
|
+
* built from the obstacle corners, using A* with a per-bend penalty.
|
|
25
|
+
*
|
|
26
|
+
* Pass every node's raw rect as `obstacles`; `padding` supplies the clearance. A port
|
|
27
|
+
* that sits inside an obstacle (its own node, since ports are on node boundaries) is
|
|
28
|
+
* exempted only for the straight exit segment out of that port; the searched route
|
|
29
|
+
* never enters any padded obstacle interior, including its own nodes.
|
|
30
|
+
*
|
|
31
|
+
* Returns the waypoint polyline with `from` first and `to` last, or `null` when every
|
|
32
|
+
* route is blocked (including a blocked exit segment). Cost is path length plus
|
|
33
|
+
* `bendPenalty` per bend, so among equal length routes the one with fewer bends wins.
|
|
34
|
+
* Expansion order is fully deterministic.
|
|
35
|
+
*/
|
|
36
|
+
export declare function orthogonalRoute(from: PortAnchor, to: PortAnchor, options?: OrthogonalRouteOptions): Point[] | null;
|
|
37
|
+
//# sourceMappingURL=orthogonal.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orthogonal.d.ts","sourceRoot":"","sources":["../src/orthogonal.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAY,IAAI,EAAE,MAAM,YAAY,CAAC;AAEpE,6CAA6C;AAC7C,MAAM,WAAW,sBAAsB;IACrC,kEAAkE;IAClE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,SAAS,IAAI,EAAE,CAAC;IAC5B,wGAAwG;IACxG,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAuED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,UAAU,EAChB,EAAE,EAAE,UAAU,EACd,OAAO,GAAE,sBAA2B,GACnC,KAAK,EAAE,GAAG,IAAI,CA0LhB"}
|