@vielzeug/wire 26.11.23 → 26.11.25

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.
@@ -1 +1 @@
1
- {"version":3,"file":"wire.iife.js","names":["exports","SIDE_VECTOR","Dir","DELTA","SIDE_DIR","OPPOSITE","message","opts","DEFAULT_HANDLE_LENGTH","handleLength","options","fromVector","from","toVector","to","items","i","parent","parentItem","item","top","last","left","right","smallest","swap","index","id","nodeIds","edge","edges","count","outgoing","indegree","ready","order","node","next","remaining","selfLoop","lowLink","discovery","onStack","stack","cycles","time","work","root","frame","children","child","component","member","a","b","DIR_COUNT","rect","padding","obstacles","px","py","xLow","xHigh","yLow","yHigh","point","delta","dir","distance","owners","along","bendPenalty","stub","start","goal","startOwners","goalOwners","startOthers","goalOthers","fromDir","toDir","agreesWithStart","agreesWithGoal","freeSpan","vector","side","fromTip","toTip","routeStart","routeGoal","startDir","forbiddenIncoming","xs","ys","xLines","yLines","columns","rows","nodeCount","y","x","startNode","goalNode","stateCount","gScore","closed","open","startState","goalState","current","incoming","cx","cy","candidates","neighbor","nx","ny","step","bend","nextScore","nextState","nodes","state","points","prev","cur","rounded","value","first","parts","curve","offset"],"sources":["../src/_sides.ts","../src/errors.ts","../src/bezier.ts","../src/_heap.ts","../src/graph.ts","../src/orthogonal.ts","../src/_format.ts","../src/path.ts","../src/ports.ts"],"sourcesContent":["import type { Point, PortSide } from './types.js';\n\n/** Outward unit vector for each port side; shared by the routers. */\nexport const SIDE_VECTOR: Readonly<Record<PortSide, Point>> = {\n bottom: { x: 0, y: 1 },\n left: { x: -1, y: 0 },\n right: { x: 1, y: 0 },\n top: { x: 0, y: -1 },\n};\n\n/** Grid movement directions; `None` (0) marks a start state with no incoming direction. */\nexport const Dir = { Down: 4, Left: 1, None: 0, Right: 2, Up: 3 } as const;\nexport type Dir = (typeof Dir)[keyof typeof Dir];\n/** The four real movement directions, excluding the `None` sentinel. */\nexport type Move = Exclude<Dir, typeof Dir.None>;\n\n/** Unit steps per movement direction, in grid order. */\nexport const DELTA: Readonly<Record<Move, Point>> = {\n [Dir.Left]: { x: -1, y: 0 },\n [Dir.Right]: { x: 1, y: 0 },\n [Dir.Up]: { x: 0, y: -1 },\n [Dir.Down]: { x: 0, y: 1 },\n};\n\n/** Outward direction a port on the given side faces. */\nexport const SIDE_DIR: Readonly<Record<PortSide, Move>> = {\n bottom: Dir.Down,\n left: Dir.Left,\n right: Dir.Right,\n top: Dir.Up,\n};\n\nexport const OPPOSITE: Readonly<Record<Move, Move>> = {\n [Dir.Down]: Dir.Up,\n [Dir.Left]: Dir.Right,\n [Dir.Right]: Dir.Left,\n [Dir.Up]: Dir.Down,\n};\n","/** 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","import { SIDE_VECTOR } from './_sides.js';\nimport { WireConfigError } from './errors.js';\nimport type { CubicBezier, PortAnchor } from './types.js';\n\n/** Default control-point distance for `bezierRoute()` when `handleLength` is omitted. */\nconst DEFAULT_HANDLE_LENGTH = 40;\n\n/** Configuration for `bezierRoute()`. */\nexport interface BezierRouteOptions {\n /** Distance each control point extends outward from its port along the port side. Defaults to 40. */\n handleLength?: number;\n}\n\n/**\n * Builds a cubic bezier segment between two ports.\n *\n * Control points extend outward from each port along its side, so the curve leaves\n * and enters ports perpendicular to the node edge.\n */\nexport function bezierRoute(from: PortAnchor, to: PortAnchor, options: BezierRouteOptions = {}): CubicBezier {\n const handleLength = options.handleLength ?? DEFAULT_HANDLE_LENGTH;\n if (!Number.isFinite(handleLength) || handleLength < 0) {\n throw new WireConfigError(\n `Bezier handleLength must be a finite non-negative number, received ${String(handleLength)}.`,\n );\n }\n\n const fromVector = SIDE_VECTOR[from.side];\n const toVector = SIDE_VECTOR[to.side];\n\n return {\n c1: { x: from.x + fromVector.x * handleLength, y: from.y + fromVector.y * handleLength },\n c2: { x: to.x + toVector.x * handleLength, y: to.y + toVector.y * handleLength },\n from: { x: from.x, y: from.y },\n to: { x: to.x, y: to.y },\n };\n}\n","/**\n * Binary min-heap ordered by a numeric key. Ties between equal keys resolve by heap\n * structure, which is fully determined by the push sequence, so extraction is\n * deterministic for identical input.\n */\nexport class MinHeap {\n private readonly items: { key: number; value: number }[] = [];\n\n get size(): number {\n return this.items.length;\n }\n\n push(key: number, value: number): void {\n const items = this.items;\n items.push({ key, value });\n let i = items.length - 1;\n while (i > 0) {\n const parent = (i - 1) >> 1;\n const parentItem = items[parent]!;\n const item = items[i]!;\n if (parentItem.key <= item.key) break;\n items[parent] = item;\n items[i] = parentItem;\n i = parent;\n }\n }\n\n pop(): number {\n const items = this.items;\n const top = items[0]!;\n const last = items.pop()!;\n if (items.length > 0) {\n items[0] = last;\n let i = 0;\n for (;;) {\n const left = i * 2 + 1;\n const right = left + 1;\n let smallest = i;\n if (left < items.length && items[left]!.key < items[smallest]!.key) smallest = left;\n if (right < items.length && items[right]!.key < items[smallest]!.key) smallest = right;\n if (smallest === i) break;\n const item = items[i]!;\n const swap = items[smallest]!;\n items[i] = swap;\n items[smallest] = item;\n i = smallest;\n }\n }\n return top.value;\n }\n}\n","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","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","/** Formats a number for SVG path output: rounded to micro-precision, no `-0`, no exponent noise. */\nexport function fmt(value: number): string {\n const rounded = Math.round(value * 1e6) / 1e6;\n return Object.is(rounded, -0) ? '0' : String(rounded);\n}\n","import { fmt } from './_format.js';\nimport type { CubicBezier, Point } from './types.js';\n\n/** Formats a polyline as an SVG path `d` string using absolute moveto and lineto commands. */\nexport function polylineToSvgPath(points: readonly Point[]): string {\n const first = points[0];\n if (!first) return '';\n const parts = [`M ${fmt(first.x)} ${fmt(first.y)}`];\n for (let i = 1; i < points.length; i += 1) {\n const point = points[i] as Point;\n parts.push(`L ${fmt(point.x)} ${fmt(point.y)}`);\n }\n return parts.join(' ');\n}\n\n/** Formats a cubic bezier segment as an SVG path `d` string using absolute curveto commands. */\nexport function bezierToSvgPath(curve: CubicBezier): string {\n return `M ${fmt(curve.from.x)} ${fmt(curve.from.y)} C ${fmt(curve.c1.x)} ${fmt(curve.c1.y)}, ${fmt(curve.c2.x)} ${fmt(curve.c2.y)}, ${fmt(curve.to.x)} ${fmt(curve.to.y)}`;\n}\n","import { WireConfigError } from './errors.js';\nimport type { PortAnchor, PortSide, Rect } from './types.js';\n\n/**\n * Places a port on `side` of `rect` and returns its world position with the side it faces.\n *\n * `offset` is the 0..1 fraction along the side (0 is the side's lower coordinate,\n * 0.5 the middle). Screen convention applies: `top` is smaller y.\n */\nexport function portAnchor(rect: Rect, side: PortSide, offset = 0.5): PortAnchor {\n if (!Number.isFinite(offset) || offset < 0 || offset > 1) {\n throw new WireConfigError(`Port offset must be a finite number between 0 and 1, received ${String(offset)}.`);\n }\n switch (side) {\n case 'bottom':\n return { side, x: rect.x + rect.width * offset, y: rect.y + rect.height };\n case 'left':\n return { side, x: rect.x, y: rect.y + rect.height * offset };\n case 'right':\n return { side, x: rect.x + rect.width, y: rect.y + rect.height * offset };\n case 'top':\n return { side, x: rect.x + rect.width * offset, y: rect.y };\n }\n}\n"],"mappings":"A,mFAGA,IAAaC,EAAiD,CAC5D,OAAQ,CAAE,EAAG,EAAG,EAAG,CAAE,EACrB,KAAM,CAAE,EAAG,GAAI,EAAG,CAAE,EACpB,MAAO,CAAE,EAAG,EAAG,EAAG,CAAE,EACpB,IAAK,CAAE,EAAG,EAAG,EAAG,EAAG,CACrB,EAGaC,EAAM,CAAE,KAAM,EAAG,KAAM,EAAG,KAAM,EAAG,MAAO,EAAG,GAAI,CAAE,EAMnDC,EAAuC,EACjDD,EAAI,MAAO,CAAE,EAAG,GAAI,EAAG,CAAE,GACzBA,EAAI,OAAQ,CAAE,EAAG,EAAG,EAAG,CAAE,GACzBA,EAAI,IAAK,CAAE,EAAG,EAAG,EAAG,EAAG,GACvBA,EAAI,MAAO,CAAE,EAAG,EAAG,EAAG,CAAE,CAC3B,EAGaE,EAA6C,CACxD,OAAQF,EAAI,KACZ,KAAMA,EAAI,KACV,MAAOA,EAAI,MACX,IAAKA,EAAI,EACX,EAEaG,EAAyC,EAC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AAM,GAAG,CAAC,EAAE,GAAG,IAAIA,EAAM,GAAG,CAAC,EAAE,IAAI,IAAIA,EAAM,GAAG,CAAC,EAAE,GAAG,IAAIA,EAAM,GAAG,CAAC,EAAE,IAAI,IAAIA,EAAM,GAAG,CAAC,EAAE,GAAG,IAAIA,EAAM,GAAG,CAAC,GACzK,CCTA,SAAgB,WAAW,EAAY,EAAgB,EAAS,GAAiB,CAC/E,GAAI,CAAC,OAAO,SAASC,CAAM,GAAKA,EAAS,GAAKA,EAAS,EACrD,MAAM,IAAI,gBAAgB,iEAAiE,OAAOA,CAAM,EAAE,EAAE,EAE9G,OAAQ9C,EAAR,CACE,IAAK,SACH,MAAO,CAAE,OAAM,EAAG7B,EAAK,EAAIA,EAAK,MAAQ2E,EAAQ,EAAG3E,EAAK,EAAIA,EAAK,MAAO,EAC1E,IAAK,OACH,MAAO,CAAE,OAAM,EAAGA,EAAK,EAAG,EAAGA,EAAK,EAAIA,EAAK,OAAS2E,CAAO,EAC7D,IAAK,QACH,MAAO,CAAE,OAAM,EAAG3E,EAAK,EAAIA,EAAK,MAAO,EAAGA,EAAK,EAAIA,EAAK,OAAS2E,CAAO,EAC1E,IAAK,MACH,MAAO,CAAE,OAAM,EAAG3E,EAAK,EAAIA,EAAK,MAAQ2E,EAAQ,EAAG3E,EAAK,CAAE,CAC9D,CACF,C"}
1
+ {"version":3,"file":"wire.iife.js","names":["exports","SIDE_VECTOR","Dir","DELTA","SIDE_DIR","OPPOSITE","message","opts","DEFAULT_HANDLE_LENGTH","SELF_LOOP_HANDLE_RATIO","handleLength","options","fromVector","from","toVector","to","effectiveHandle","spacing","DEFAULT_ARROWHEAD_LENGTH","DEFAULT_ARROWHEAD_WIDTH","DEFAULT_HIT_THRESHOLD","BEZIER_SAMPLES","v","u","a","b","c","d","curve","value","label","t","tip","direction","magnitude","length","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","abx","aby","segmentLengthSq","point","projX","projY","threshold","bestDistance","bestLength","hit","distance","bestIndex","lo","hi","m1","m2","p1","p2","closest","items","parent","parentItem","item","top","last","left","right","smallest","swap","index","id","nodeIds","edge","edges","count","outgoing","indegree","ready","order","node","next","remaining","selfLoop","lowLink","discovery","onStack","stack","cycles","time","work","root","frame","children","child","component","member","DIR_COUNT","rect","padding","obstacles","xLow","xHigh","yLow","yHigh","delta","dir","owners","along","bendPenalty","stub","goal","startOwners","goalOwners","startOthers","goalOthers","fromDir","toDir","agreesWithStart","agreesWithGoal","freeSpan","vector","side","fromTip","toTip","routeStart","routeGoal","startDir","forbiddenIncoming","xs","ys","xLines","yLines","columns","rows","nodeCount","y","x","startNode","goalNode","stateCount","gScore","closed","open","startState","goalState","current","incoming","cx","cy","candidates","neighbor","nx","ny","step","bend","nextScore","nextState","nodes","state","prev","cur","rounded","COLLINEAR_EPSILON","cornerRadius","first","parts","inLen","outLen","inX","inY","outX","outY","radius","offset","toward","dx","dy"],"sources":["../src/_sides.ts","../src/errors.ts","../src/bezier.ts","../src/edit.ts","../src/_heap.ts","../src/graph.ts","../src/orthogonal.ts","../src/_format.ts","../src/path.ts","../src/ports.ts"],"sourcesContent":["import type { Point, PortSide } from './types.js';\n\n/** Outward unit vector for each port side; shared by the routers. */\nexport const SIDE_VECTOR: Readonly<Record<PortSide, Point>> = {\n bottom: { x: 0, y: 1 },\n left: { x: -1, y: 0 },\n right: { x: 1, y: 0 },\n top: { x: 0, y: -1 },\n};\n\n/** Grid movement directions; `None` (0) marks a start state with no incoming direction. */\nexport const Dir = { Down: 4, Left: 1, None: 0, Right: 2, Up: 3 } as const;\nexport type Dir = (typeof Dir)[keyof typeof Dir];\n/** The four real movement directions, excluding the `None` sentinel. */\nexport type Move = Exclude<Dir, typeof Dir.None>;\n\n/** Unit steps per movement direction, in grid order. */\nexport const DELTA: Readonly<Record<Move, Point>> = {\n [Dir.Left]: { x: -1, y: 0 },\n [Dir.Right]: { x: 1, y: 0 },\n [Dir.Up]: { x: 0, y: -1 },\n [Dir.Down]: { x: 0, y: 1 },\n};\n\n/** Outward direction a port on the given side faces. */\nexport const SIDE_DIR: Readonly<Record<PortSide, Move>> = {\n bottom: Dir.Down,\n left: Dir.Left,\n right: Dir.Right,\n top: Dir.Up,\n};\n\nexport const OPPOSITE: Readonly<Record<Move, Move>> = {\n [Dir.Down]: Dir.Up,\n [Dir.Left]: Dir.Right,\n [Dir.Right]: Dir.Left,\n [Dir.Up]: Dir.Down,\n};\n","/** 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","import { SIDE_VECTOR } from './_sides.js';\nimport { WireConfigError } from './errors.js';\nimport type { CubicBezier, PortAnchor } from './types.js';\n\n/** Default control-point distance for `bezierRoute()` when `handleLength` is omitted. */\nconst DEFAULT_HANDLE_LENGTH = 40;\n\n/** Configuration for `bezierRoute()`. */\nexport interface BezierRouteOptions {\n /** Distance each control point extends outward from its port along the port side. Defaults to 40. */\n handleLength?: number;\n /**\n * Widen the handles so an edge whose endpoints sit on the same side of one\n * node forms a visible loop instead of collapsing onto that side. When the\n * ports share a side, each handle grows to `1.5 *` the distance between the\n * ports (never smaller than `handleLength`), keeping the loop symmetric and\n * deterministic. Ignored when the ports face different sides. Defaults to false.\n */\n selfLoop?: boolean;\n}\n\n/** Multiplier applied to the port spacing when `selfLoop` widens the handles. */\nconst SELF_LOOP_HANDLE_RATIO = 1.5;\n\n/**\n * Builds a cubic bezier segment between two ports.\n *\n * Control points extend outward from each port along its side, so the curve leaves\n * and enters ports perpendicular to the node edge. With `selfLoop` and both ports\n * on the same side, the handles stretch to `1.5 *` the port spacing so the curve\n * bulges outward into a loop.\n */\nexport function bezierRoute(from: PortAnchor, to: PortAnchor, options: BezierRouteOptions = {}): CubicBezier {\n const handleLength = options.handleLength ?? DEFAULT_HANDLE_LENGTH;\n if (!Number.isFinite(handleLength) || handleLength < 0) {\n throw new WireConfigError(\n `Bezier handleLength must be a finite non-negative number, received ${String(handleLength)}.`,\n );\n }\n\n const fromVector = SIDE_VECTOR[from.side];\n const toVector = SIDE_VECTOR[to.side];\n\n let effectiveHandle = handleLength;\n if (options.selfLoop && from.side === to.side) {\n const spacing = Math.hypot(to.x - from.x, to.y - from.y);\n effectiveHandle = Math.max(handleLength, spacing * SELF_LOOP_HANDLE_RATIO);\n }\n\n return {\n c1: { x: from.x + fromVector.x * effectiveHandle, y: from.y + fromVector.y * effectiveHandle },\n c2: { x: to.x + toVector.x * effectiveHandle, y: to.y + toVector.y * effectiveHandle },\n from: { x: from.x, y: from.y },\n to: { x: to.x, y: to.y },\n };\n}\n","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","/**\n * Binary min-heap ordered by a numeric key. Ties between equal keys resolve by heap\n * structure, which is fully determined by the push sequence, so extraction is\n * deterministic for identical input.\n */\nexport class MinHeap {\n private readonly items: { key: number; value: number }[] = [];\n\n get size(): number {\n return this.items.length;\n }\n\n push(key: number, value: number): void {\n const items = this.items;\n items.push({ key, value });\n let i = items.length - 1;\n while (i > 0) {\n const parent = (i - 1) >> 1;\n const parentItem = items[parent]!;\n const item = items[i]!;\n if (parentItem.key <= item.key) break;\n items[parent] = item;\n items[i] = parentItem;\n i = parent;\n }\n }\n\n pop(): number {\n const items = this.items;\n const top = items[0]!;\n const last = items.pop()!;\n if (items.length > 0) {\n items[0] = last;\n let i = 0;\n for (;;) {\n const left = i * 2 + 1;\n const right = left + 1;\n let smallest = i;\n if (left < items.length && items[left]!.key < items[smallest]!.key) smallest = left;\n if (right < items.length && items[right]!.key < items[smallest]!.key) smallest = right;\n if (smallest === i) break;\n const item = items[i]!;\n const swap = items[smallest]!;\n items[i] = swap;\n items[smallest] = item;\n i = smallest;\n }\n }\n return top.value;\n }\n}\n","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","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","/** Formats a number for SVG path output: rounded to micro-precision, no `-0`, no exponent noise. */\nexport function fmt(value: number): string {\n const rounded = Math.round(value * 1e6) / 1e6;\n return Object.is(rounded, -0) ? '0' : String(rounded);\n}\n","import { fmt } from './_format.js';\nimport { WireConfigError } from './errors.js';\nimport type { CubicBezier, Point } from './types.js';\n\n/** Configuration for `polylineToSvgPath()`. */\nexport interface PolylinePathOptions {\n /**\n * Radius used to round interior corners with quadratic arcs (`Q` commands).\n * Each corner is clamped to half of its shortest adjacent run, so tight\n * bends never overlap. `0` or omitted keeps sharp `L` corners.\n */\n cornerRadius?: number;\n}\n\n/** Below this normalized cross product, three points count as collinear. */\nconst COLLINEAR_EPSILON = 1e-9;\n\n/**\n * Formats a polyline as an SVG path `d` string using absolute moveto and lineto\n * commands. With `cornerRadius`, interior corners are replaced by entry/exit runs\n * joined by a quadratic `Q` arc; the corner point itself is not emitted.\n */\nexport function polylineToSvgPath(points: readonly Point[], options: PolylinePathOptions = {}): string {\n const cornerRadius = options.cornerRadius ?? 0;\n if (!Number.isFinite(cornerRadius) || cornerRadius < 0) {\n throw new WireConfigError(\n `Path cornerRadius must be a finite non-negative number, received ${String(cornerRadius)}.`,\n );\n }\n const first = points[0];\n if (!first) return '';\n const last = points[points.length - 1] as Point;\n const parts = [`M ${fmt(first.x)} ${fmt(first.y)}`];\n if (cornerRadius === 0) {\n for (let i = 1; i < points.length; i += 1) {\n const point = points[i] as Point;\n parts.push(`L ${fmt(point.x)} ${fmt(point.y)}`);\n }\n return parts.join(' ');\n }\n // Rounded mode: interior corners become entry/exit runs joined by a Q arc;\n // the corner point itself is never emitted, collinear points pass through.\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 const inLen = Math.hypot(cur.x - prev.x, cur.y - prev.y);\n const outLen = Math.hypot(next.x - cur.x, next.y - cur.y);\n // Zero-length runs and near-collinear points have no corner to round.\n if (inLen === 0 || outLen === 0) continue;\n const inX = (cur.x - prev.x) / inLen;\n const inY = (cur.y - prev.y) / inLen;\n const outX = (next.x - cur.x) / outLen;\n const outY = (next.y - cur.y) / outLen;\n if (Math.abs(inX * outY - inY * outX) < COLLINEAR_EPSILON) continue;\n const radius = Math.min(cornerRadius, inLen / 2, outLen / 2);\n parts.push(`L ${fmt(cur.x - inX * radius)} ${fmt(cur.y - inY * radius)}`);\n parts.push(`Q ${fmt(cur.x)} ${fmt(cur.y)}, ${fmt(cur.x + outX * radius)} ${fmt(cur.y + outY * radius)}`);\n }\n parts.push(`L ${fmt(last.x)} ${fmt(last.y)}`);\n return parts.join(' ');\n}\n\n/** Formats a cubic bezier segment as an SVG path `d` string using absolute curveto commands. */\nexport function bezierToSvgPath(curve: CubicBezier): string {\n return `M ${fmt(curve.from.x)} ${fmt(curve.from.y)} C ${fmt(curve.c1.x)} ${fmt(curve.c1.y)}, ${fmt(curve.c2.x)} ${fmt(curve.c2.y)}, ${fmt(curve.to.x)} ${fmt(curve.to.y)}`;\n}\n","import { WireConfigError } from './errors.js';\nimport type { Point, PortAnchor, PortSide, Rect } from './types.js';\n\n/**\n * Places a port on `side` of `rect` and returns its world position with the side it faces.\n *\n * `offset` is the 0..1 fraction along the side (0 is the side's lower coordinate,\n * 0.5 the middle). Screen convention applies: `top` is smaller y.\n */\nexport function portAnchor(rect: Rect, side: PortSide, offset = 0.5): PortAnchor {\n if (!Number.isFinite(offset) || offset < 0 || offset > 1) {\n throw new WireConfigError(`Port offset must be a finite number between 0 and 1, received ${String(offset)}.`);\n }\n switch (side) {\n case 'bottom':\n return { side, x: rect.x + rect.width * offset, y: rect.y + rect.height };\n case 'left':\n return { side, x: rect.x, y: rect.y + rect.height * offset };\n case 'right':\n return { side, x: rect.x + rect.width, y: rect.y + rect.height * offset };\n case 'top':\n return { side, x: rect.x + rect.width * offset, y: rect.y };\n }\n}\n\n/**\n * Returns the side of `rect` that faces the point `toward`.\n *\n * The side is chosen by the dominant axis from the rect's center: the larger of\n * `|dx|` and `|dy|` wins. Ties (`|dx| === |dy|`, including the zero vector when\n * `toward` sits exactly on the center) resolve to the horizontal side, with the\n * sign picking `right`/`left` — and `right` for a zero vector, where both signs\n * are absent. Screen convention applies: `top` is smaller y.\n *\n * @throws {@link WireConfigError} when the rect or point has non-finite coordinates.\n */\nexport function floatingSide(rect: Rect, toward: Point): PortSide {\n if (\n !Number.isFinite(rect.x) ||\n !Number.isFinite(rect.y) ||\n !Number.isFinite(rect.width) ||\n !Number.isFinite(rect.height)\n ) {\n throw new WireConfigError(\n `Floating rect must have finite coordinates, received (${rect.x}, ${rect.y}, ${rect.width}, ${rect.height}).`,\n );\n }\n if (!Number.isFinite(toward.x) || !Number.isFinite(toward.y)) {\n throw new WireConfigError(`Floating target must have finite coordinates, received (${toward.x}, ${toward.y}).`);\n }\n const dx = toward.x - (rect.x + rect.width / 2);\n const dy = toward.y - (rect.y + rect.height / 2);\n // Horizontal wins ties, including the zero vector (dx === dy === 0 -> 'right').\n if (Math.abs(dx) >= Math.abs(dy)) {\n return dx >= 0 ? 'right' : 'left';\n }\n return dy > 0 ? 'bottom' : 'top';\n}\n"],"mappings":"A,mFAGA,IAAaC,EAAiD,CAC5D,OAAQ,CAAE,EAAG,EAAG,EAAG,CAAE,EACrB,KAAM,CAAE,EAAG,GAAI,EAAG,CAAE,EACpB,MAAO,CAAE,EAAG,EAAG,EAAG,CAAE,EACpB,IAAK,CAAE,EAAG,EAAG,EAAG,EAAG,CACrB,EAGaC,EAAM,CAAE,KAAM,EAAG,KAAM,EAAG,KAAM,EAAG,MAAO,EAAG,GAAI,CAAE,EAMnDC,EAAuC,EACjDD,EAAI,MAAO,CAAE,EAAG,GAAI,EAAG,CAAE,GACzBA,EAAI,OAAQ,CAAE,EAAG,EAAG,EAAG,CAAE,GACzBA,EAAI,IAAK,CAAE,EAAG,EAAG,EAAG,EAAG,GACvBA,EAAI,MAAO,CAAE,EAAG,EAAG,EAAG,CAAE,CAC3B,EAGaE,EAA6C,CACxD,OAAQF,EAAI,KACZ,KAAMA,EAAI,KACV,MAAOA,EAAI,MACX,IAAKA,EAAI,EACX,EAEaG,EAAyC,EACnDH,EAAI,MAAOA,EAAI,IACfA,EAAI,MAAOA,EAAI,OACfA,EAAI,OAAQA,EAAI,MAChBA,EAAI,IAAKA,EAAI,IAChB,ECpCa,UAAb,cAA+B,KAAM,CACnC,YAAY,EAAiB,EAAqB,C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G5E,EAAK,EAAIA,EAAK,MAAO,EAAGA,EAAK,EAAIA,EAAK,OAAS4E,CAAO,EAC1E,IAAK,MACH,MAAO,CAAE,OAAM,EAAG5E,EAAK,EAAIA,EAAK,MAAQ4E,EAAQ,EAAG5E,EAAK,CAAE,CAC9D,CACF,CAaA,SAAgB,aAAa,EAAY,EAAyB,CAChE,GACE,CAAC,OAAO,SAASA,EAAK,CAAC,GACvB,CAAC,OAAO,SAASA,EAAK,CAAC,GACvB,CAAC,OAAO,SAASA,EAAK,KAAK,GAC3B,CAAC,OAAO,SAASA,EAAK,MAAM,EAE5B,MAAM,IAAI,gBACR,yDAAyDA,EAAK,EAAE,IAAIA,EAAK,EAAE,IAAIA,EAAK,MAAM,IAAIA,EAAK,OAAO,GAC5G,EAEF,GAAI,CAAC,OAAO,SAAS6E,EAAO,CAAC,GAAK,CAAC,OAAO,SAASA,EAAO,CAAC,EACzD,MAAM,IAAI,gBAAgB,2DAA2DA,EAAO,EAAE,IAAIA,EAAO,EAAE,GAAG,EAEhH,IAAMC,EAAKD,EAAO,GAAK7E,EAAK,EAAIA,EAAK,MAAQ,GACvC+E,EAAKF,EAAO,GAAK7E,EAAK,EAAIA,EAAK,OAAS,GAK9C,OAHI,KAAK,IAAI8E,CAAE,GAAK,KAAK,IAAIC,CAAE,EACtBD,GAAM,EAAI,QAAU,OAEtBC,EAAK,EAAI,SAAW,KAC7B,C"}
package/dist/wire.js CHANGED
@@ -53,19 +53,23 @@ var e = {
53
53
  constructor(e, t) {
54
54
  super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
55
55
  }
56
- }, WireGraphError = class extends WireError {}, WireConfigError = class extends WireError {}, a = 40;
56
+ }, WireGraphError = class extends WireError {}, WireConfigError = class extends WireError {}, a = 40, o = 1.5;
57
57
  function bezierRoute(t, n, r = {}) {
58
58
  let i = r.handleLength ?? a;
59
59
  if (!Number.isFinite(i) || i < 0) throw new WireConfigError(`Bezier handleLength must be a finite non-negative number, received ${String(i)}.`);
60
- let o = e[t.side], s = e[n.side];
60
+ let s = e[t.side], c = e[n.side], l = i;
61
+ if (r.selfLoop && t.side === n.side) {
62
+ let e = Math.hypot(n.x - t.x, n.y - t.y);
63
+ l = Math.max(i, e * o);
64
+ }
61
65
  return {
62
66
  c1: {
63
- x: t.x + o.x * i,
64
- y: t.y + o.y * i
67
+ x: t.x + s.x * l,
68
+ y: t.y + s.y * l
65
69
  },
66
70
  c2: {
67
- x: n.x + s.x * i,
68
- y: n.y + s.y * i
71
+ x: n.x + c.x * l,
72
+ y: n.y + c.y * l
69
73
  },
70
74
  from: {
71
75
  x: t.x,
@@ -77,6 +81,172 @@ function bezierRoute(t, n, r = {}) {
77
81
  }
78
82
  };
79
83
  }
84
+ // src/edit.ts
85
+ var s = 10, c = 6, l = 4, u = 64;
86
+ function cubicAt(e, t) {
87
+ let n = 1 - t, r = n * n * n, i = 3 * n * n * t, a = 3 * n * t * t, o = t * t * t;
88
+ return {
89
+ x: r * e.from.x + i * e.c1.x + a * e.c2.x + o * e.to.x,
90
+ y: r * e.from.y + i * e.c1.y + a * e.c2.y + o * e.to.y
91
+ };
92
+ }
93
+ function requirePoint(e, t) {
94
+ if (!Number.isFinite(e.x) || !Number.isFinite(e.y)) throw new WireConfigError(`Wire edit ${t} must have finite coordinates, received (${e.x}, ${e.y}).`);
95
+ }
96
+ function requirePositive(e, t) {
97
+ if (!Number.isFinite(e) || e <= 0) throw new WireConfigError(`Wire edit ${t} must be a finite positive number, received ${String(e)}.`);
98
+ }
99
+ function requireUnitT(e) {
100
+ if (!Number.isFinite(e) || e < 0 || e > 1) throw new WireConfigError(`Wire edit t must be a finite number in [0, 1], received ${String(e)}.`);
101
+ }
102
+ function arrowhead(e, t, n = {}) {
103
+ requirePoint(e, "arrowhead tip"), requirePoint(t, "arrowhead direction");
104
+ let r = Math.hypot(t.x, t.y);
105
+ if (r === 0) throw new WireConfigError("Wire edit arrowhead direction must be non-zero.");
106
+ let i = n.length ?? s, a = n.width ?? c;
107
+ requirePositive(i, "arrowhead length"), requirePositive(a, "arrowhead width");
108
+ let o = t.x / r, l = t.y / r, u = -l, d = o, f = e.x - o * i, p = e.y - l * i, m = a / 2;
109
+ return [
110
+ {
111
+ x: e.x,
112
+ y: e.y
113
+ },
114
+ {
115
+ x: f + u * m,
116
+ y: p + d * m
117
+ },
118
+ {
119
+ x: f - u * m,
120
+ y: p - d * m
121
+ }
122
+ ];
123
+ }
124
+ function polylineLengths(e) {
125
+ let t = Array(e.length);
126
+ t[0] = 0;
127
+ 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);
128
+ return t;
129
+ }
130
+ function pointAtPolylineLength(e, t, n) {
131
+ let r = t[t.length - 1];
132
+ if (r === 0) return {
133
+ x: e[0].x,
134
+ y: e[0].y
135
+ };
136
+ let i = Math.min(Math.max(n, 0), r), a = 1, o = t.length - 1;
137
+ for (; a < o;) {
138
+ let e = a + o >> 1;
139
+ t[e] < i ? a = e + 1 : o = e;
140
+ }
141
+ let s = e[a - 1], c = e[a], l = t[a] - t[a - 1];
142
+ if (l === 0) return {
143
+ x: s.x,
144
+ y: s.y
145
+ };
146
+ let u = (i - t[a - 1]) / l;
147
+ return {
148
+ x: s.x + (c.x - s.x) * u,
149
+ y: s.y + (c.y - s.y) * u
150
+ };
151
+ }
152
+ function bezierTable(e) {
153
+ let t = Array(65), n = Array(65);
154
+ for (let n = 0; n <= u; n++) t[n] = cubicAt(e, n / u);
155
+ n[0] = 0;
156
+ for (let e = 1; e <= u; e++) n[e] = n[e - 1] + Math.hypot(t[e].x - t[e - 1].x, t[e].y - t[e - 1].y);
157
+ return {
158
+ cumulative: n,
159
+ samples: t,
160
+ total: n[u]
161
+ };
162
+ }
163
+ function uAtBezierLength(e, t) {
164
+ let n = Math.min(Math.max(t, 0), e.total), r = 1, i = u;
165
+ for (; r < i;) {
166
+ let t = r + i >> 1;
167
+ e.cumulative[t] < n ? r = t + 1 : i = t;
168
+ }
169
+ let a = e.cumulative[r] - e.cumulative[r - 1], o = a === 0 ? 0 : (n - e.cumulative[r - 1]) / a;
170
+ return (r - 1 + o) / u;
171
+ }
172
+ function sampledLengthAt(e, t) {
173
+ let n = Math.min(Math.max(t, 0), 1) * u, r = Math.min(Math.floor(n), 63), i = n - r;
174
+ return e.cumulative[r] + i * (e.cumulative[r + 1] - e.cumulative[r]);
175
+ }
176
+ function requireCurve(e, t) {
177
+ requirePoint(e.from, `${t} from`), requirePoint(e.c1, `${t} c1`), requirePoint(e.c2, `${t} c2`), requirePoint(e.to, `${t} to`);
178
+ }
179
+ function pointOnPolyline(e, t) {
180
+ if (e.length < 2) throw new WireConfigError(`Wire edit pointOnPolyline requires at least 2 points, received ${e.length}.`);
181
+ for (let t = 0; t < e.length; t++) requirePoint(e[t], `pointOnPolyline points[${t}]`);
182
+ requireUnitT(t);
183
+ let n = polylineLengths(e);
184
+ return pointAtPolylineLength(e, n, t * n[n.length - 1]);
185
+ }
186
+ function pointOnBezier(e, t) {
187
+ requireCurve(e, "pointOnBezier"), requireUnitT(t);
188
+ let n = bezierTable(e);
189
+ return n.total === 0 ? {
190
+ x: e.from.x,
191
+ y: e.from.y
192
+ } : cubicAt(e, uAtBezierLength(n, t * n.total));
193
+ }
194
+ function distanceToSegment(e, t, n) {
195
+ let r = n.x - t.x, i = n.y - t.y, a = r * r + i * i;
196
+ if (a === 0) return {
197
+ distance: Math.hypot(e.x - t.x, e.y - t.y),
198
+ ratio: 0
199
+ };
200
+ 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;
201
+ return {
202
+ distance: Math.hypot(e.x - s, e.y - c),
203
+ ratio: o
204
+ };
205
+ }
206
+ function hitPolyline(e, t, n = {}) {
207
+ if (e.length < 2) throw new WireConfigError(`Wire edit hitPolyline requires at least 2 points, received ${e.length}.`);
208
+ for (let t = 0; t < e.length; t++) requirePoint(e[t], `hitPolyline points[${t}]`);
209
+ requirePoint(t, "hitPolyline point");
210
+ let r = n.threshold ?? l;
211
+ requirePositive(r, "hitPolyline threshold");
212
+ let i = polylineLengths(e), a = i[i.length - 1], o = Infinity, s = 0;
213
+ for (let n = 1; n < e.length; n++) {
214
+ let r = distanceToSegment(t, e[n - 1], e[n]);
215
+ r.distance < o && (o = r.distance, s = i[n - 1] + r.ratio * (i[n] - i[n - 1]));
216
+ }
217
+ return o > r ? null : {
218
+ distance: o,
219
+ t: a === 0 ? 0 : s / a
220
+ };
221
+ }
222
+ function hitBezier(e, t, n = {}) {
223
+ requireCurve(e, "hitBezier"), requirePoint(t, "hitBezier point");
224
+ let r = n.threshold ?? l;
225
+ requirePositive(r, "hitBezier threshold");
226
+ let i = bezierTable(e);
227
+ if (i.total === 0) {
228
+ let n = Math.hypot(t.x - e.from.x, t.y - e.from.y);
229
+ return n <= r ? {
230
+ distance: n,
231
+ t: 0
232
+ } : null;
233
+ }
234
+ let a = 0, o = Infinity;
235
+ for (let e = 0; e <= u; e++) {
236
+ let n = Math.hypot(t.x - i.samples[e].x, t.y - i.samples[e].y);
237
+ n < o && (o = n, a = e);
238
+ }
239
+ let s = Math.max(0, (a - 1) / u), c = Math.min(1, (a + 1) / u);
240
+ for (let n = 0; n < 32; n++) {
241
+ let n = s + (c - s) / 3, r = c - (c - s) / 3, i = cubicAt(e, n), a = cubicAt(e, r);
242
+ Math.hypot(t.x - i.x, t.y - i.y) < Math.hypot(t.x - a.x, t.y - a.y) ? c = r : s = n;
243
+ }
244
+ let d = (s + c) / 2, f = cubicAt(e, d), p = Math.hypot(t.x - f.x, t.y - f.y);
245
+ return p > r ? null : {
246
+ distance: p,
247
+ t: sampledLengthAt(i, d) / i.total
248
+ };
249
+ }
80
250
  // src/_heap.ts
81
251
  var MinHeap = class {
82
252
  items = [];
@@ -188,7 +358,7 @@ function findCyclicGroups(e, t) {
188
358
  return u.sort((e, t) => n.get(e[0]) - n.get(t[0])), u;
189
359
  }
190
360
  // src/orthogonal.ts
191
- var o = 5;
361
+ var d = 5;
192
362
  function padRect(e, t) {
193
363
  return {
194
364
  x0: e.x - t,
@@ -219,74 +389,74 @@ function escapeDistance(e, t, r) {
219
389
  }
220
390
  return a;
221
391
  }
222
- function orthogonalRoute(n, a, s = {}) {
223
- let c = s.padding ?? 8, l = s.bendPenalty ?? 12, u = s.stub ?? 16;
224
- if (!Number.isFinite(c) || c < 0) throw new WireConfigError(`Orthogonal padding must be a finite non-negative number, received ${String(c)}.`);
225
- if (!Number.isFinite(l) || l < 0) throw new WireConfigError(`Bend penalty must be a finite non-negative number, received ${String(l)}.`);
226
- if (!Number.isFinite(u) || u < 0) throw new WireConfigError(`Stub must be a finite non-negative number, received ${String(u)}.`);
227
- let d = {
392
+ function orthogonalRoute(n, a, o = {}) {
393
+ let s = o.padding ?? 8, c = o.bendPenalty ?? 12, l = o.stub ?? 16;
394
+ if (!Number.isFinite(s) || s < 0) throw new WireConfigError(`Orthogonal padding must be a finite non-negative number, received ${String(s)}.`);
395
+ if (!Number.isFinite(c) || c < 0) throw new WireConfigError(`Bend penalty must be a finite non-negative number, received ${String(c)}.`);
396
+ if (!Number.isFinite(l) || l < 0) throw new WireConfigError(`Stub must be a finite non-negative number, received ${String(l)}.`);
397
+ let u = {
228
398
  x: n.x,
229
399
  y: n.y
230
400
  }, f = {
231
401
  x: a.x,
232
402
  y: a.y
233
403
  };
234
- if (d.x === f.x && d.y === f.y) return [d];
235
- let p = (s.obstacles ?? []).map((e) => padRect(e, c)), m = ownersOf(d, p), h = ownersOf(f, p), othersFor = (e) => e.length === 0 ? p : p.filter((t) => !e.includes(t)), g = othersFor(m), _ = othersFor(h), v = r[n.side], y = r[a.side];
236
- if (d.x === f.x || d.y === f.y) {
237
- let e = d.x === f.x ? f.y > d.y ? t.Down : t.Up : f.x > d.x ? t.Right : t.Left, n = u === 0 && m.length === 0 || v === e, r = u === 0 && h.length === 0 || i[y] === e, a = p.filter((e) => !m.includes(e) && !h.includes(e));
238
- if (n && r && !spanBlocked(d, f, a)) return [d, f];
404
+ if (u.x === f.x && u.y === f.y) return [u];
405
+ let p = (o.obstacles ?? []).map((e) => padRect(e, s)), m = ownersOf(u, p), h = ownersOf(f, p), othersFor = (e) => e.length === 0 ? p : p.filter((t) => !e.includes(t)), g = othersFor(m), _ = othersFor(h), v = r[n.side], y = r[a.side];
406
+ if (u.x === f.x || u.y === f.y) {
407
+ let e = u.x === f.x ? f.y > u.y ? t.Down : t.Up : f.x > u.x ? t.Right : t.Left, n = l === 0 && m.length === 0 || v === e, r = l === 0 && h.length === 0 || i[y] === e, a = p.filter((e) => !m.includes(e) && !h.includes(e));
408
+ if (n && r && !spanBlocked(u, f, a)) return [u, f];
239
409
  }
240
410
  let exitTip = (t, n, r, i) => {
241
- let a = e[n], o = Math.max(u, escapeDistance(t, r, i));
411
+ let a = e[n], o = Math.max(l, escapeDistance(t, r, i));
242
412
  return {
243
413
  x: t.x + a.x * o,
244
414
  y: t.y + a.y * o
245
415
  };
246
- }, b = exitTip(d, n.side, v, m), x = exitTip(f, a.side, y, h);
247
- if (spanBlocked(d, b, g) || spanBlocked(f, x, _)) return null;
248
- let S = b, C = x, w = u > 0 || m.length > 0 ? v : t.None, T = u > 0 || h.length > 0 ? y : t.None, E = /* @__PURE__ */ new Set([S.x, C.x]), D = /* @__PURE__ */ new Set([S.y, C.y]);
416
+ }, b = exitTip(u, n.side, v, m), x = exitTip(f, a.side, y, h);
417
+ if (spanBlocked(u, b, g) || spanBlocked(f, x, _)) return null;
418
+ let S = b, C = x, w = l > 0 || m.length > 0 ? v : t.None, T = l > 0 || h.length > 0 ? y : t.None, E = /* @__PURE__ */ new Set([S.x, C.x]), D = /* @__PURE__ */ new Set([S.y, C.y]);
249
419
  for (let e of p) E.add(e.x0), E.add(e.x1), D.add(e.y0), D.add(e.y1);
250
420
  let O = [...E].sort((e, t) => e - t), k = [...D].sort((e, t) => e - t), A = O.length, j = k.length, M = A * j, nodeX = (e) => O[e % A], nodeY = (e) => k[Math.floor(e / A)], nodeAt = (e, t) => k.indexOf(t) * A + O.indexOf(e), N = nodeAt(S.x, S.y), P = nodeAt(C.x, C.y);
251
421
  if (pointBlocked(nodeX(N), nodeY(N), p) || pointBlocked(nodeX(P), nodeY(P), p)) return null;
252
- let F = M * o, I = new Float64Array(F).fill(Infinity), L = new Int32Array(F).fill(-1), R = new Uint8Array(F), heuristic = (e) => Math.abs(nodeX(e) - C.x) + Math.abs(nodeY(e) - C.y), stateId = (e, t) => e * o + t, z = new MinHeap(), B = stateId(N, w);
422
+ let F = M * d, I = new Float64Array(F).fill(Infinity), L = new Int32Array(F).fill(-1), R = new Uint8Array(F), heuristic = (e) => Math.abs(nodeX(e) - C.x) + Math.abs(nodeY(e) - C.y), stateId = (e, t) => e * d + t, z = new MinHeap(), B = stateId(N, w);
253
423
  I[B] = 0, z.push(heuristic(N), B);
254
424
  let V = -1;
255
425
  for (; z.size > 0 && V === -1;) {
256
426
  let e = z.pop();
257
427
  if (R[e]) continue;
258
428
  R[e] = 1;
259
- let n = Math.floor(e / o), r = e % o;
429
+ let n = Math.floor(e / d), r = e % d;
260
430
  if (n === P && (T === t.None || r !== T)) {
261
431
  V = e;
262
432
  break;
263
433
  }
264
- let i = nodeX(n), a = nodeY(n), s = [
434
+ let i = nodeX(n), a = nodeY(n), o = [
265
435
  [t.Left, n - 1],
266
436
  [t.Right, n + 1],
267
437
  [t.Up, n - A],
268
438
  [t.Down, n + A]
269
439
  ];
270
- for (let [o, c] of s) {
271
- if (o === t.Left && n % A === 0 || o === t.Right && n % A === A - 1 || o === t.Up && n < A || o === t.Down && n >= (j - 1) * A) continue;
272
- let s = nodeX(c), u = nodeY(c);
273
- if (pointBlocked(s, u, p) || spanBlocked({
440
+ for (let [s, l] of o) {
441
+ if (s === t.Left && n % A === 0 || s === t.Right && n % A === A - 1 || s === t.Up && n < A || s === t.Down && n >= (j - 1) * A) continue;
442
+ let o = nodeX(l), u = nodeY(l);
443
+ if (pointBlocked(o, u, p) || spanBlocked({
274
444
  x: i,
275
445
  y: a
276
446
  }, {
277
- x: s,
447
+ x: o,
278
448
  y: u
279
449
  }, p)) continue;
280
- let d = Math.abs(s - i) + Math.abs(u - a), f = r !== t.None && r !== o ? l : 0, m = I[e] + d + f, h = stateId(c, o);
281
- m < I[h] && (I[h] = m, L[h] = e, z.push(m + heuristic(c), h));
450
+ let d = Math.abs(o - i) + Math.abs(u - a), f = r !== t.None && r !== s ? c : 0, m = I[e] + d + f, h = stateId(l, s);
451
+ m < I[h] && (I[h] = m, L[h] = e, z.push(m + heuristic(l), h));
282
452
  }
283
453
  }
284
454
  if (V === -1) return null;
285
455
  let H = [];
286
- for (let e = V; e !== -1; e = L[e]) H.push(Math.floor(e / o));
456
+ for (let e = V; e !== -1; e = L[e]) H.push(Math.floor(e / d));
287
457
  H.reverse();
288
458
  let U = [
289
- d,
459
+ u,
290
460
  ...H.filter((e, t) => {
291
461
  if (t === 0 || t === H.length - 1) return !0;
292
462
  let n = H[t - 1], r = H[t + 1];
@@ -309,15 +479,29 @@ function fmt(e) {
309
479
  return Object.is(t, -0) ? "0" : String(t);
310
480
  }
311
481
  // src/path.ts
312
- function polylineToSvgPath(e) {
313
- let t = e[0];
314
- if (!t) return "";
315
- let n = [`M ${fmt(t.x)} ${fmt(t.y)}`];
316
- for (let t = 1; t < e.length; t += 1) {
317
- let r = e[t];
318
- n.push(`L ${fmt(r.x)} ${fmt(r.y)}`);
482
+ var f = 1e-9;
483
+ function polylineToSvgPath(e, t = {}) {
484
+ let n = t.cornerRadius ?? 0;
485
+ if (!Number.isFinite(n) || n < 0) throw new WireConfigError(`Path cornerRadius must be a finite non-negative number, received ${String(n)}.`);
486
+ let r = e[0];
487
+ if (!r) return "";
488
+ let i = e[e.length - 1], a = [`M ${fmt(r.x)} ${fmt(r.y)}`];
489
+ if (n === 0) {
490
+ for (let t = 1; t < e.length; t += 1) {
491
+ let n = e[t];
492
+ a.push(`L ${fmt(n.x)} ${fmt(n.y)}`);
493
+ }
494
+ return a.join(" ");
319
495
  }
320
- return n.join(" ");
496
+ for (let t = 1; t < e.length - 1; t += 1) {
497
+ let r = e[t - 1], i = e[t], o = e[t + 1], s = Math.hypot(i.x - r.x, i.y - r.y), c = Math.hypot(o.x - i.x, o.y - i.y);
498
+ if (s === 0 || c === 0) continue;
499
+ let l = (i.x - r.x) / s, u = (i.y - r.y) / s, d = (o.x - i.x) / c, p = (o.y - i.y) / c;
500
+ if (Math.abs(l * p - u * d) < f) continue;
501
+ let m = Math.min(n, s / 2, c / 2);
502
+ a.push(`L ${fmt(i.x - l * m)} ${fmt(i.y - u * m)}`), a.push(`Q ${fmt(i.x)} ${fmt(i.y)}, ${fmt(i.x + d * m)} ${fmt(i.y + p * m)}`);
503
+ }
504
+ return a.push(`L ${fmt(i.x)} ${fmt(i.y)}`), a.join(" ");
321
505
  }
322
506
  function bezierToSvgPath(e) {
323
507
  return `M ${fmt(e.from.x)} ${fmt(e.from.y)} C ${fmt(e.c1.x)} ${fmt(e.c1.y)}, ${fmt(e.c2.x)} ${fmt(e.c2.y)}, ${fmt(e.to.x)} ${fmt(e.to.y)}`;
@@ -348,6 +532,12 @@ function portAnchor(e, t, n = .5) {
348
532
  };
349
533
  }
350
534
  }
351
- export { WireConfigError, WireError, WireGraphError, bezierRoute, bezierToSvgPath, findCyclicGroups, orthogonalRoute, polylineToSvgPath, portAnchor, topologicalOrder };
535
+ function floatingSide(e, t) {
536
+ if (!Number.isFinite(e.x) || !Number.isFinite(e.y) || !Number.isFinite(e.width) || !Number.isFinite(e.height)) throw new WireConfigError(`Floating rect must have finite coordinates, received (${e.x}, ${e.y}, ${e.width}, ${e.height}).`);
537
+ if (!Number.isFinite(t.x) || !Number.isFinite(t.y)) throw new WireConfigError(`Floating target must have finite coordinates, received (${t.x}, ${t.y}).`);
538
+ let n = t.x - (e.x + e.width / 2), r = t.y - (e.y + e.height / 2);
539
+ return Math.abs(n) >= Math.abs(r) ? n >= 0 ? "right" : "left" : r > 0 ? "bottom" : "top";
540
+ }
541
+ export { WireConfigError, WireError, WireGraphError, arrowhead, bezierRoute, bezierToSvgPath, findCyclicGroups, floatingSide, hitBezier, hitPolyline, orthogonalRoute, pointOnBezier, pointOnPolyline, polylineToSvgPath, portAnchor, topologicalOrder };
352
542
 
353
543
  //# sourceMappingURL=wire.js.map