UNPKG

mermaid

Version:

Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.

8,284 lines • 313 kB
import {
  applyLineJumpsToSvg,
  normalizeLineHops
} from "./chunk-5UF2PZMI.mjs";
import {
  createCommonLayoutRenderer
} from "./chunk-NZQPWTTU.mjs";
import "./chunk-PWRPXRNR.mjs";
import "./chunk-BW5T7TNM.mjs";
import {
  DEFAULT_EDGE_CORNER_RADIUS,
  resolveEdgeCornerRadius
} from "./chunk-236L5HCG.mjs";
import "./chunk-7WTMCWOC.mjs";
import "./chunk-57UP3UTE.mjs";
import "./chunk-46A7OBX7.mjs";
import "./chunk-UIPQR6YN.mjs";
import "./chunk-YMNL5UXF.mjs";
import "./chunk-WJPS3GCF.mjs";
import "./chunk-7CML27B5.mjs";
import "./chunk-DNOZYBWV.mjs";
import "./chunk-VSULCTJ3.mjs";
import {
  isGridHorizontalAlign,
  isGridVerticalAlign,
  validateGridCoordinate
} from "./chunk-L2MXK2W4.mjs";
import {
  log
} from "./chunk-2RP5QIEU.mjs";
import {
  __name
} from "./chunk-42YUCIBL.mjs";

// src/rendering-util/layout-algorithms/layout-utils/geometry.ts
var PIXEL_EPSILON = 1;
function segmentOrientation(a, b, tolerance = PIXEL_EPSILON) {
  const dx = Math.abs(b.x - a.x);
  const dy = Math.abs(b.y - a.y);
  if (dx <= tolerance && dy <= tolerance) {
    return "Z";
  }
  if (dy <= tolerance) {
    return "H";
  }
  return "V";
}
__name(segmentOrientation, "segmentOrientation");
function segmentsFromPoints(points, tolerance = PIXEL_EPSILON) {
  const segments = [];
  for (let i = 0; i < points.length - 1; i++) {
    const a = points[i];
    const b = points[i + 1];
    segments.push({ a, b, orientation: segmentOrientation(a, b, tolerance) });
  }
  return segments;
}
__name(segmentsFromPoints, "segmentsFromPoints");
function mergeCollinear(segments, tolerance = PIXEL_EPSILON) {
  if (segments.length === 0) {
    return [];
  }
  const result = [];
  let current = { ...segments[0] };
  for (let i = 1; i < segments.length; i++) {
    const next = segments[i];
    if (next.orientation === "Z") {
      continue;
    }
    if (current.orientation === "Z") {
      current = { ...next };
      continue;
    }
    if (current.orientation === next.orientation) {
      if (current.orientation === "H" && Math.abs(current.b.y - next.a.y) <= tolerance && Math.abs(current.a.y - next.a.y) <= tolerance) {
        current.b = next.b;
        continue;
      }
      if (current.orientation === "V" && Math.abs(current.b.x - next.a.x) <= tolerance && Math.abs(current.a.x - next.a.x) <= tolerance) {
        current.b = next.b;
        continue;
      }
    }
    if (current.orientation !== "Z") {
      result.push(current);
    }
    current = { ...next };
  }
  if (current.orientation !== "Z") {
    result.push(current);
  }
  return result;
}
__name(mergeCollinear, "mergeCollinear");
function normalizePolyline(points, tolerance = PIXEL_EPSILON) {
  if (points.length < 2) {
    return { points: [...points], segments: [], bends: 0 };
  }
  const rawSegments = segmentsFromPoints(points, tolerance).filter((s) => s.orientation !== "Z");
  const merged = mergeCollinear(rawSegments, tolerance);
  const newPoints = [];
  for (const [i, element] of merged.entries()) {
    if (i === 0) {
      newPoints.push(element.a);
    }
    newPoints.push(element.b);
  }
  let bends = 0;
  for (let i = 1; i < merged.length; i++) {
    if (merged[i - 1].orientation !== merged[i].orientation) {
      bends++;
    }
  }
  return { points: newPoints.length > 0 ? newPoints : [...points], segments: merged, bends };
}
__name(normalizePolyline, "normalizePolyline");
function segmentsCross(s1, s2) {
  if (s1.orientation === "Z" || s2.orientation === "Z") {
    return false;
  }
  if (s1.orientation === s2.orientation) {
    return false;
  }
  const horiz = s1.orientation === "H" ? s1 : s2;
  const vert = s1.orientation === "V" ? s1 : s2;
  const hY = horiz.a.y;
  const hX1 = Math.min(horiz.a.x, horiz.b.x);
  const hX2 = Math.max(horiz.a.x, horiz.b.x);
  const vX = vert.a.x;
  const vY1 = Math.min(vert.a.y, vert.b.y);
  const vY2 = Math.max(vert.a.y, vert.b.y);
  if (vX >= hX1 && vX <= hX2 && hY >= vY1 && hY <= vY2) {
    const TOL = 1e-6;
    const ix = vX;
    const iy = hY;
    const matchesHorizEndpoint = Math.abs(ix - horiz.a.x) < TOL && Math.abs(iy - horiz.a.y) < TOL || Math.abs(ix - horiz.b.x) < TOL && Math.abs(iy - horiz.b.y) < TOL;
    const matchesVertEndpoint = Math.abs(ix - vert.a.x) < TOL && Math.abs(iy - vert.a.y) < TOL || Math.abs(ix - vert.b.x) < TOL && Math.abs(iy - vert.b.y) < TOL;
    if (matchesHorizEndpoint && matchesVertEndpoint) {
      return false;
    }
    return true;
  }
  return false;
}
__name(segmentsCross, "segmentsCross");

// src/rendering-util/layout-algorithms/layout-utils/helpers.ts
function compareCodeUnits(a, b) {
  return a < b ? -1 : a > b ? 1 : 0;
}
__name(compareCodeUnits, "compareCodeUnits");
function rectForNode(node) {
  const cx = node.x ?? 0;
  const cy = node.y ?? 0;
  const w = node.width ?? 40;
  const h = node.height ?? 40;
  return {
    cx,
    cy,
    left: cx - w / 2,
    right: cx + w / 2,
    top: cy - h / 2,
    bottom: cy + h / 2
  };
}
__name(rectForNode, "rectForNode");
function terminalMarkerClearanceRect(points, terminal, length, halfWidth, tolerance = 0) {
  if (points.length < 2) {
    return null;
  }
  const tip = terminal === "end" ? points[points.length - 1] : points[0];
  const inner = terminal === "end" ? points[points.length - 2] : points[1];
  const dx = inner.x - tip.x;
  const dy = inner.y - tip.y;
  if (Math.abs(dx) <= tolerance && Math.abs(dy) <= tolerance) {
    return null;
  }
  if (Math.abs(dy) <= tolerance) {
    const innerX = tip.x + Math.sign(dx) * length;
    const left = Math.min(tip.x, innerX);
    const right = Math.max(tip.x, innerX);
    return {
      cx: (left + right) / 2,
      cy: tip.y,
      left,
      right,
      top: tip.y - halfWidth,
      bottom: tip.y + halfWidth
    };
  }
  if (Math.abs(dx) <= tolerance) {
    const innerY = tip.y + Math.sign(dy) * length;
    const top = Math.min(tip.y, innerY);
    const bottom = Math.max(tip.y, innerY);
    return {
      cx: tip.x,
      cy: (top + bottom) / 2,
      left: tip.x - halfWidth,
      right: tip.x + halfWidth,
      top,
      bottom
    };
  }
  return null;
}
__name(terminalMarkerClearanceRect, "terminalMarkerClearanceRect");
function hasTerminalMarker(edge, terminal) {
  const markerType = terminal === "start" ? edge.arrowTypeStart : edge.arrowTypeEnd;
  if (typeof markerType === "string") {
    const trimmed = markerType.trim();
    if (trimmed.length > 0) {
      return trimmed !== "none" && trimmed !== "arrow_open";
    }
  }
  if (typeof edge.type !== "string") {
    return false;
  }
  if (terminal === "start" && edge.type.startsWith("double_")) {
    return true;
  }
  return terminal === "end" && /arrow_(point|cross|circle|barb)|double_arrow/.test(edge.type);
}
__name(hasTerminalMarker, "hasTerminalMarker");
function approxEqual(a, b, tol = 1e-6) {
  return Math.abs(a - b) <= tol;
}
__name(approxEqual, "approxEqual");
function orthogonalPolylineContainsPoint(points, point, tolerance = 1e-6) {
  for (let index = 1; index < points.length; index++) {
    const a = points[index - 1];
    const b = points[index];
    if (approxEqual(a.y, b.y, tolerance) && !approxEqual(a.x, b.x, tolerance)) {
      if (approxEqual(point.y, a.y, tolerance) && point.x >= Math.min(a.x, b.x) - tolerance && point.x <= Math.max(a.x, b.x) + tolerance) {
        return true;
      }
    } else if (approxEqual(a.x, b.x, tolerance) && !approxEqual(a.y, b.y, tolerance)) {
      if (approxEqual(point.x, a.x, tolerance) && point.y >= Math.min(a.y, b.y) - tolerance && point.y <= Math.max(a.y, b.y) + tolerance) {
        return true;
      }
    }
  }
  return false;
}
__name(orthogonalPolylineContainsPoint, "orthogonalPolylineContainsPoint");
function manhattanLength(points) {
  let total = 0;
  for (let i = 1; i < points.length; i++) {
    const a = points[i - 1];
    const b = points[i];
    total += Math.abs(b.x - a.x) + Math.abs(b.y - a.y);
  }
  return total;
}
__name(manhattanLength, "manhattanLength");
function segmentIntersectsRectInterior(a, b, rect) {
  if (a.x === b.x && a.y === b.y) {
    return false;
  }
  if (a.y === b.y) {
    const y = a.y;
    const x1 = Math.min(a.x, b.x);
    const x2 = Math.max(a.x, b.x);
    const crossesVertically = y >= rect.top && y <= rect.bottom;
    const overlapsHorizontally = Math.max(x1, rect.left) < Math.min(x2, rect.right);
    return crossesVertically && overlapsHorizontally;
  }
  if (a.x === b.x) {
    const x = a.x;
    const y1 = Math.min(a.y, b.y);
    const y2 = Math.max(a.y, b.y);
    const crossesHorizontally = x >= rect.left && x <= rect.right;
    const overlapsVertically = Math.max(y1, rect.top) < Math.min(y2, rect.bottom);
    return crossesHorizontally && overlapsVertically;
  }
  return false;
}
__name(segmentIntersectsRectInterior, "segmentIntersectsRectInterior");
function polylineIntersectsRect(points, rect) {
  for (let i = 1; i < points.length; i++) {
    if (segmentIntersectsRectInterior(points[i - 1], points[i], rect)) {
      return true;
    }
  }
  return false;
}
__name(polylineIntersectsRect, "polylineIntersectsRect");
function clamp(v, lo, hi) {
  return Math.max(lo, Math.min(hi, v));
}
__name(clamp, "clamp");

// src/rendering-util/layout-algorithms/grid/types.ts
var ROOT_CONTAINER_ID = "__grid_root__";
var GRID_LABEL_PREFIX = "edge-label-";
function gridError(code, message, details) {
  const error = new Error(`${code}: ${message}`);
  error.code = code;
  error.details = details;
  return error;
}
__name(gridError, "gridError");
var GRID_DEFAULTS = {
  columns: 0,
  rowGap: 50,
  columnGap: 50,
  cellGap: 20,
  containerPadding: 20,
  titleGap: 8,
  horizontalAlign: "center",
  verticalAlign: "center",
  curve: "rounded",
  edgeCornerRadius: DEFAULT_EDGE_CORNER_RADIUS
};
function isEdgeLabelNode(node) {
  return Boolean(node.isEdgeLabel);
}
__name(isEdgeLabelNode, "isEdgeLabelNode");
function isFinitePositiveNumber(value) {
  return typeof value === "number" && Number.isFinite(value) && value > 0;
}
__name(isFinitePositiveNumber, "isFinitePositiveNumber");

// src/rendering-util/layout-algorithms/grid/labelGeometry.ts
var GRID_LABEL_CLEARANCE = 6;
var GRID_EDGE_END_MARKER_CLEARANCE = 12;
var GRID_LABEL_SPAN_MARGIN = 2;
function gridLabelSpanRequirement(labelNode, orientation) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  const along = orientation === "H" ? labelNode.width : labelNode.height;
  const cross = orientation === "H" ? labelNode.height : labelNode.width;
  const startInset = Math.max(GRID_LABEL_CLEARANCE, GRID_EDGE_END_MARKER_CLEARANCE);
  const endInset = Math.max(GRID_LABEL_CLEARANCE, GRID_EDGE_END_MARKER_CLEARANCE);
  return {
    along,
    cross,
    startInset,
    endInset,
    requiredAlongSpan: along + startInset + endInset + GRID_LABEL_SPAN_MARGIN
  };
}
__name(gridLabelSpanRequirement, "gridLabelSpanRequirement");
function gridLabelRequiredSegmentLength(labelNode, orientation) {
  const along = orientation === "H" ? labelNode.width : labelNode.height;
  return isFinitePositiveNumber(along) ? along + GRID_LABEL_CLEARANCE * 2 : 0;
}
__name(gridLabelRequiredSegmentLength, "gridLabelRequiredSegmentLength");

// src/rendering-util/layout-algorithms/grid/edgeLabels.ts
var LABEL_CLEARANCE = GRID_LABEL_CLEARANCE;
var LABEL_GUTTER = 14;
var LABEL_GUTTER_STEP = 18;
var MAX_GUTTER_STEPS = 16;
var MAX_DETOUR_LINE_CANDIDATES = 128;
var MAX_DETOUR_CENTER_CANDIDATES = 64;
var DEFAULT_MAX_INDEX_WORK = 2e6;
var EDGE_END_MARKER_CLEARANCE = GRID_EDGE_END_MARKER_CLEARANCE;
var LABEL_EPSILON = 1e-6;
var MIN_SELF_PARALLEL_GAP = 7;
var MIN_SELF_PARALLEL_OVERLAP = 8;
var normalizePolyline2 = /* @__PURE__ */ __name((points) => normalizePolyline(points, LABEL_EPSILON), "normalizePolyline");
function rangeOverlapLength(firstStart, firstEnd, secondStart, secondEnd) {
  const start = Math.max(Math.min(firstStart, firstEnd), Math.min(secondStart, secondEnd));
  const end = Math.min(Math.max(firstStart, firstEnd), Math.max(secondStart, secondEnd));
  return Math.max(0, end - start);
}
__name(rangeOverlapLength, "rangeOverlapLength");
function polylineHasSelfConflict(points) {
  const segments = normalizePolyline2([...points]).segments;
  for (let firstIndex = 0; firstIndex < segments.length; firstIndex++) {
    const first = segments[firstIndex];
    for (let secondIndex = firstIndex + 2; secondIndex < segments.length; secondIndex++) {
      const second = segments[secondIndex];
      if (segmentsCross(first, second)) {
        return true;
      }
      if (first.orientation !== second.orientation || first.orientation === "Z") {
        continue;
      }
      const sameAxis = first.orientation === "H" ? Math.abs(first.a.y - second.a.y) <= LABEL_EPSILON : Math.abs(first.a.x - second.a.x) <= LABEL_EPSILON;
      const overlap = first.orientation === "H" ? rangeOverlapLength(first.a.x, first.b.x, second.a.x, second.b.x) : rangeOverlapLength(first.a.y, first.b.y, second.a.y, second.b.y);
      if (sameAxis && overlap > LABEL_EPSILON) {
        return true;
      }
      const gap = first.orientation === "H" ? Math.abs(first.a.y - second.a.y) : Math.abs(first.a.x - second.a.x);
      if (!sameAxis && gap < MIN_SELF_PARALLEL_GAP && overlap >= MIN_SELF_PARALLEL_OVERLAP) {
        return true;
      }
    }
  }
  return false;
}
__name(polylineHasSelfConflict, "polylineHasSelfConflict");
var LabelPlacementSearchExhaustedError = class extends Error {
  constructor(details) {
    super(`Could not place label for edge "${details.edgeId}"`);
    this.details = details;
    this.name = "LabelPlacementSearchExhaustedError";
  }
  static {
    __name(this, "LabelPlacementSearchExhaustedError");
  }
};
var LabelIndexWorkLimitError = class extends Error {
  static {
    __name(this, "LabelIndexWorkLimitError");
  }
  constructor() {
    super("Grid label index work cap exceeded");
    this.name = "LabelIndexWorkLimitError";
  }
};
var LabelIndexWorkBudget = class {
  constructor(limit, metrics) {
    this.limit = limit;
    this.metrics = metrics;
    this.used = 0;
  }
  static {
    __name(this, "LabelIndexWorkBudget");
  }
  charge(units) {
    if (units <= 0) {
      return;
    }
    if (this.used + units > this.limit) {
      throw new LabelIndexWorkLimitError();
    }
    this.used += units;
    incrementMetric(this.metrics, "indexWorkUnits", units);
  }
};
var CompressedBoundsIndex = class {
  constructor(workBudget, metrics) {
    this.workBudget = workBudget;
    this.metrics = metrics;
    this.entriesById = /* @__PURE__ */ new Map();
    this.sortedByLeft = [];
    this.dirty = false;
  }
  static {
    __name(this, "CompressedBoundsIndex");
  }
  upsert(entry) {
    const isNew = !this.entriesById.has(entry.id);
    this.entriesById.set(entry.id, entry);
    this.dirty = true;
    if (isNew && this.metrics) {
      this.metrics.indexCoordinateCount += 4;
    }
  }
  remove(id) {
    if (this.entriesById.delete(id)) {
      this.dirty = true;
    }
  }
  query(bounds) {
    if (this.dirty) {
      const entryCount = this.entriesById.size;
      this.workBudget.charge(entryCount * Math.max(1, Math.ceil(Math.log2(entryCount + 1))));
      this.sortedByLeft = [...this.entriesById.values()].sort(
        (a, b) => a.bounds.left - b.bounds.left || compareCodeUnits(a.id, b.id)
      );
      this.dirty = false;
    }
    const result = [];
    for (const entry of this.sortedByLeft) {
      this.workBudget.charge(1);
      if (entry.bounds.left > bounds.right) {
        break;
      }
      if (boundsOverlap(entry.bounds, bounds)) {
        result.push(entry);
      }
    }
    return result;
  }
};
function rectOverlap(a, b) {
  return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top;
}
__name(rectOverlap, "rectOverlap");
function labelRectAt(node, center) {
  const width = node.width ?? 0;
  const height = node.height ?? 0;
  return {
    cx: center.x,
    cy: center.y,
    left: center.x - width / 2,
    right: center.x + width / 2,
    top: center.y - height / 2,
    bottom: center.y + height / 2
  };
}
__name(labelRectAt, "labelRectAt");
function groupTitleRect(node) {
  const rect = node.groupTitleRect;
  if (!rect) {
    return null;
  }
  return {
    cx: (rect.left + rect.right) / 2,
    cy: (rect.top + rect.bottom) / 2,
    left: rect.left,
    right: rect.right,
    top: rect.top,
    bottom: rect.bottom
  };
}
__name(groupTitleRect, "groupTitleRect");
function incrementMetric(metrics, key, delta = 1) {
  if (metrics) {
    metrics[key] += delta;
  }
}
__name(incrementMetric, "incrementMetric");
function clonePoint(point) {
  return { ...point };
}
__name(clonePoint, "clonePoint");
function boundsForRect(rect) {
  return {
    left: rect.left,
    right: rect.right,
    top: rect.top,
    bottom: rect.bottom
  };
}
__name(boundsForRect, "boundsForRect");
function boundsForSegment(segment) {
  return {
    left: Math.min(segment.a.x, segment.b.x),
    right: Math.max(segment.a.x, segment.b.x),
    top: Math.min(segment.a.y, segment.b.y),
    bottom: Math.max(segment.a.y, segment.b.y)
  };
}
__name(boundsForSegment, "boundsForSegment");
function boundsForPoints(points) {
  if (points.length === 0) {
    return null;
  }
  let left = points[0].x;
  let right = points[0].x;
  let top = points[0].y;
  let bottom = points[0].y;
  for (const point of points.slice(1)) {
    left = Math.min(left, point.x);
    right = Math.max(right, point.x);
    top = Math.min(top, point.y);
    bottom = Math.max(bottom, point.y);
  }
  return { left, right, top, bottom };
}
__name(boundsForPoints, "boundsForPoints");
function mergeBounds(a, b) {
  return {
    left: Math.min(a.left, b.left),
    right: Math.max(a.right, b.right),
    top: Math.min(a.top, b.top),
    bottom: Math.max(a.bottom, b.bottom)
  };
}
__name(mergeBounds, "mergeBounds");
function expandBounds(bounds, padding) {
  return {
    left: bounds.left - padding,
    right: bounds.right + padding,
    top: bounds.top - padding,
    bottom: bounds.bottom + padding
  };
}
__name(expandBounds, "expandBounds");
function boundsOverlap(a, b) {
  return a.left <= b.right && a.right >= b.left && a.top <= b.bottom && a.bottom >= b.top;
}
__name(boundsOverlap, "boundsOverlap");
function candidateSegmentsFromSegments(segments) {
  const indexes = segments.length <= 2 ? segments.map((_, index) => index) : [...segments.slice(1, -1).map((_, index) => index + 1), 0, segments.length - 1];
  return indexes.map((segmentIndex, order) => ({
    segment: segments[segmentIndex],
    segmentIndex,
    order
  }));
}
__name(candidateSegmentsFromSegments, "candidateSegmentsFromSegments");
function markerClearanceRectsFromPoints(edge, points) {
  const terminals = ["start", "end"];
  return terminals.filter((terminal) => hasTerminalMarker(edge, terminal)).map(
    (terminal) => terminalMarkerClearanceRect(points, terminal, EDGE_END_MARKER_CLEARANCE, 7, LABEL_EPSILON)
  ).filter((rect) => rect !== null);
}
__name(markerClearanceRectsFromPoints, "markerClearanceRectsFromPoints");
function buildEdgeGeometry(edge, points) {
  const normalized = normalizePolyline2(points);
  return {
    points: normalized.points,
    segments: normalized.segments,
    candidateSegments: candidateSegmentsFromSegments(normalized.segments),
    markerRects: markerClearanceRectsFromPoints(edge, normalized.points)
  };
}
__name(buildEdgeGeometry, "buildEdgeGeometry");
function segmentLength(segment) {
  return segment.orientation === "H" ? Math.abs(segment.b.x - segment.a.x) : Math.abs(segment.b.y - segment.a.y);
}
__name(segmentLength, "segmentLength");
function borderCutsRect(rect, border) {
  const corners = [
    { x: border.left, y: border.top },
    { x: border.right, y: border.top },
    { x: border.right, y: border.bottom },
    { x: border.left, y: border.bottom }
  ];
  for (let i = 0; i < corners.length; i++) {
    if (segmentIntersectsRectInterior(corners[i], corners[(i + 1) % corners.length], rect)) {
      return true;
    }
  }
  return false;
}
__name(borderCutsRect, "borderCutsRect");
function hasFinitePosition(node) {
  return Number.isFinite(node.x) && Number.isFinite(node.y);
}
__name(hasFinitePosition, "hasFinitePosition");
function pointsForEdge(edge, overrides, context) {
  const overridePoints = overrides?.get(edge.id);
  if (overridePoints) {
    return normalizePolyline2(overridePoints).points;
  }
  const cached = context?.edgeGeometryById.get(edge.id);
  if (cached) {
    return cached.points;
  }
  return normalizePolyline2(edge.points ?? []).points;
}
__name(pointsForEdge, "pointsForEdge");
function markerClearanceRectsForEdge(edge, overrides, context) {
  if (!overrides?.has(edge.id)) {
    const cached = context?.edgeGeometryById.get(edge.id);
    if (cached) {
      return cached.markerRects;
    }
  }
  return markerClearanceRectsFromPoints(edge, pointsForEdge(edge, overrides, context));
}
__name(markerClearanceRectsForEdge, "markerClearanceRectsForEdge");
function rangeOverlaps(aStart, aEnd, bStart, bEnd) {
  return Math.max(Math.min(aStart, aEnd), Math.min(bStart, bEnd)) < Math.min(Math.max(aStart, aEnd), Math.max(bStart, bEnd)) - LABEL_EPSILON;
}
__name(rangeOverlaps, "rangeOverlaps");
function clampInterval(interval, low, high) {
  const start = clamp(Math.min(interval.start, interval.end), low, high);
  const end = clamp(Math.max(interval.start, interval.end), low, high);
  return end - start > LABEL_EPSILON ? { start, end } : null;
}
__name(clampInterval, "clampInterval");
function mergeBlockedLabelIntervals(intervals, low, high) {
  const clamped = intervals.map((interval) => clampInterval(interval, low, high)).filter((interval) => interval !== null).sort((a, b) => a.start - b.start || a.end - b.end);
  if (clamped.length === 0) {
    return [];
  }
  const merged = [clamped[0]];
  for (let index = 1; index < clamped.length; index++) {
    const current = clamped[index];
    const previous = merged[merged.length - 1];
    if (current.start <= previous.end + LABEL_EPSILON) {
      previous.end = Math.max(previous.end, current.end);
    } else {
      merged.push(current);
    }
  }
  return merged;
}
__name(mergeBlockedLabelIntervals, "mergeBlockedLabelIntervals");
function centerCandidatesFromIntervals(low, high, blocked, preferred) {
  if (high - low <= LABEL_EPSILON) {
    return [];
  }
  const allowed = [];
  let cursor = low;
  for (const interval of mergeBlockedLabelIntervals(blocked, low, high)) {
    if (interval.start - cursor > LABEL_EPSILON) {
      allowed.push({ start: cursor, end: interval.start });
    }
    cursor = Math.max(cursor, interval.end);
  }
  if (high - cursor > LABEL_EPSILON) {
    allowed.push({ start: cursor, end: high });
  }
  const candidates = allowed.map((interval) => ({
    value: clamp(preferred, interval.start, interval.end),
    start: interval.start,
    end: interval.end
  }));
  candidates.sort((a, b) => {
    const preferredDelta = Math.abs(a.value - preferred) - Math.abs(b.value - preferred);
    if (Math.abs(preferredDelta) > LABEL_EPSILON) {
      return preferredDelta;
    }
    const widthDelta = b.end - b.start - (a.end - a.start);
    if (Math.abs(widthDelta) > LABEL_EPSILON) {
      return widthDelta;
    }
    return a.value - b.value;
  });
  const seen = /* @__PURE__ */ new Set();
  const values = [];
  for (const candidate of candidates) {
    const rounded = Math.round(candidate.value * 1e6) / 1e6;
    if (seen.has(rounded)) {
      continue;
    }
    seen.add(rounded);
    values.push(candidate.value);
  }
  return values;
}
__name(centerCandidatesFromIntervals, "centerCandidatesFromIntervals");
function obstacleRectForNode(node) {
  if (node.isGroup) {
    return null;
  }
  if (isEdgeLabelNode(node) && !hasFinitePosition(node)) {
    return null;
  }
  return rectForNode(node);
}
__name(obstacleRectForNode, "obstacleRectForNode");
function candidateSegments(edge, context) {
  const cached = context?.edgeGeometryById.get(edge.id);
  if (cached) {
    return cached.candidateSegments;
  }
  return candidateSegmentsFromSegments(normalizePolyline2(edge.points ?? []).segments);
}
__name(candidateSegments, "candidateSegments");
function storeEdgeGeometry(context, edgeId, geometry) {
  const previous = context.edgeGeometryById.get(edgeId);
  if (previous) {
    previous.segments.forEach((_, index) => context.segmentIndex.remove(`${edgeId}:${index}`));
  }
  context.edgeGeometryById.set(edgeId, geometry);
  geometry.segments.forEach((segment, index) => {
    context.segmentIndex.upsert({
      id: `${edgeId}:${index}`,
      edgeId,
      segment,
      bounds: boundsForSegment(segment)
    });
  });
}
__name(storeEdgeGeometry, "storeEdgeGeometry");
function setEdgePoints(context, edge, points) {
  const geometry = buildEdgeGeometry(edge, points);
  edge.points = geometry.points.map(clonePoint);
  storeEdgeGeometry(context, edge.id, geometry);
}
__name(setEdgePoints, "setEdgePoints");
function upsertPlacedLabelObstacle(context, placedLabel) {
  context.placedLabelIndex.upsert({
    id: `label:${placedLabel.nodeId}`,
    nodeId: placedLabel.nodeId,
    rect: placedLabel.rect,
    bounds: boundsForRect(placedLabel.rect)
  });
}
__name(upsertPlacedLabelObstacle, "upsertPlacedLabelObstacle");
function createEdgeLabelContext(data, workBudget, metrics) {
  const context = {
    edgeById: /* @__PURE__ */ new Map(),
    edgeGeometryById: /* @__PURE__ */ new Map(),
    obstacleIndex: new CompressedBoundsIndex(workBudget, metrics),
    placedLabelIndex: new CompressedBoundsIndex(workBudget, metrics),
    groupBorderIndex: new CompressedBoundsIndex(workBudget, metrics),
    segmentIndex: new CompressedBoundsIndex(workBudget, metrics),
    searchBounds: { left: 0, right: 0, top: 0, bottom: 0 },
    metrics
  };
  let aggregateBounds = null;
  const rememberBounds = /* @__PURE__ */ __name((bounds) => {
    aggregateBounds = aggregateBounds ? mergeBounds(aggregateBounds, bounds) : { ...bounds };
  }, "rememberBounds");
  for (const node of data.nodes) {
    if (node.isGroup) {
      const borderRect = rectForNode(node);
      const borderBounds = boundsForRect(borderRect);
      context.groupBorderIndex.upsert({
        id: `border:${node.id}`,
        rect: borderRect,
        bounds: borderBounds
      });
      rememberBounds(borderBounds);
      const titleRect = groupTitleRect(node);
      if (titleRect) {
        const titleBounds = boundsForRect(titleRect);
        context.obstacleIndex.upsert({
          id: `title:${node.id}`,
          rect: titleRect,
          bounds: titleBounds
        });
        rememberBounds(titleBounds);
      }
      continue;
    }
    const obstacleRect = obstacleRectForNode(node);
    if (!obstacleRect) {
      continue;
    }
    const entry = {
      id: `${isEdgeLabelNode(node) ? "label" : "node"}:${node.id}`,
      rect: obstacleRect,
      bounds: boundsForRect(obstacleRect),
      nodeId: node.id
    };
    if (isEdgeLabelNode(node)) {
      context.placedLabelIndex.upsert(entry);
    } else {
      context.obstacleIndex.upsert(entry);
    }
    rememberBounds(entry.bounds);
  }
  for (const edge of data.edges) {
    context.edgeById.set(edge.id, edge);
    const geometry = buildEdgeGeometry(edge, edge.points ?? []);
    storeEdgeGeometry(context, edge.id, geometry);
    const pointBounds = boundsForPoints(geometry.points);
    if (pointBounds) {
      rememberBounds(pointBounds);
    }
  }
  context.searchBounds = expandBounds(
    aggregateBounds ?? { left: 0, right: 0, top: 0, bottom: 0 },
    128
  );
  return context;
}
__name(createEdgeLabelContext, "createEdgeLabelContext");
function queryObstacleEntries(context, bounds, metricKey, options = {}) {
  incrementMetric(context.metrics, metricKey);
  const collected = [];
  const appendEntries = /* @__PURE__ */ __name((entries) => {
    for (const entry of entries) {
      if (entry.nodeId && (entry.nodeId === options.excludeNodeId || options.skipNodeIds?.has(entry.nodeId))) {
        continue;
      }
      collected.push(entry);
    }
  }, "appendEntries");
  appendEntries(context.obstacleIndex.query(bounds));
  appendEntries(context.placedLabelIndex.query(bounds));
  incrementMetric(context.metrics, "obstacleCandidatesVisited", collected.length);
  return collected;
}
__name(queryObstacleEntries, "queryObstacleEntries");
function queryForeignSegments(context, bounds, selfEdgeId, overrides, metricKey) {
  incrementMetric(context.metrics, metricKey);
  const overriddenEdgeIds = overrides ? new Set(overrides.keys()) : void 0;
  const collected = [];
  const indexedEntries = context.segmentIndex.query(bounds);
  for (const entry of indexedEntries) {
    if (entry.edgeId === selfEdgeId || overriddenEdgeIds?.has(entry.edgeId)) {
      continue;
    }
    collected.push(entry);
  }
  let visited = indexedEntries.length;
  if (overrides) {
    for (const [edgeId, points] of overrides) {
      if (edgeId === selfEdgeId) {
        continue;
      }
      const edge = context.edgeById.get(edgeId);
      if (!edge) {
        continue;
      }
      const geometry = buildEdgeGeometry(edge, points);
      geometry.segments.forEach((segment, index) => {
        const segmentBounds = boundsForSegment(segment);
        if (!boundsOverlap(segmentBounds, bounds)) {
          return;
        }
        visited += 1;
        collected.push({
          id: `override:${edgeId}:${index}`,
          edgeId,
          segment,
          bounds: segmentBounds
        });
      });
    }
  }
  incrementMetric(context.metrics, "segmentCandidatesVisited", visited);
  return collected;
}
__name(queryForeignSegments, "queryForeignSegments");
function foreignEdgeIdsIntersectingRect(context, rect, selfEdgeId, overrides) {
  incrementMetric(context.metrics, "foreignEdgeLookups");
  const ids = /* @__PURE__ */ new Set();
  for (const entry of queryForeignSegments(
    context,
    boundsForRect(rect),
    selfEdgeId,
    overrides,
    "segmentRectQueries"
  )) {
    if (segmentIntersectsRectInterior(entry.segment.a, entry.segment.b, rect)) {
      ids.add(entry.edgeId);
    }
  }
  return [...ids].sort(compareCodeUnits);
}
__name(foreignEdgeIdsIntersectingRect, "foreignEdgeIdsIntersectingRect");
function obstacleBandQueryBounds(segment, labelNode) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  if (segment.orientation === "H") {
    return {
      left: Math.min(segment.a.x, segment.b.x) - labelNode.width / 2,
      right: Math.max(segment.a.x, segment.b.x) + labelNode.width / 2,
      top: segment.a.y - labelNode.height / 2,
      bottom: segment.a.y + labelNode.height / 2
    };
  }
  return {
    left: segment.a.x - labelNode.width / 2,
    right: segment.a.x + labelNode.width / 2,
    top: Math.min(segment.a.y, segment.b.y) - labelNode.height / 2,
    bottom: Math.max(segment.a.y, segment.b.y) + labelNode.height / 2
  };
}
__name(obstacleBandQueryBounds, "obstacleBandQueryBounds");
function detourLineQueryBounds(segment, labelNode, searchBounds) {
  if (segment.orientation === "H") {
    const alongPadding2 = (labelNode.width ?? 0) + LABEL_CLEARANCE * 2 + LABEL_GUTTER;
    return {
      left: Math.min(segment.a.x, segment.b.x) - alongPadding2,
      right: Math.max(segment.a.x, segment.b.x) + alongPadding2,
      top: searchBounds.top,
      bottom: searchBounds.bottom
    };
  }
  const alongPadding = (labelNode.height ?? 0) + LABEL_CLEARANCE * 2 + LABEL_GUTTER;
  return {
    left: searchBounds.left,
    right: searchBounds.right,
    top: Math.min(segment.a.y, segment.b.y) - alongPadding,
    bottom: Math.max(segment.a.y, segment.b.y) + alongPadding
  };
}
__name(detourLineQueryBounds, "detourLineQueryBounds");
function rerouteLineQueryBounds(segment, searchBounds) {
  if (segment.orientation === "H") {
    return {
      left: Math.min(segment.a.x, segment.b.x) - LABEL_CLEARANCE,
      right: Math.max(segment.a.x, segment.b.x) + LABEL_CLEARANCE,
      top: searchBounds.top,
      bottom: searchBounds.bottom
    };
  }
  return {
    left: searchBounds.left,
    right: searchBounds.right,
    top: Math.min(segment.a.y, segment.b.y) - LABEL_CLEARANCE,
    bottom: Math.max(segment.a.y, segment.b.y) + LABEL_CLEARANCE
  };
}
__name(rerouteLineQueryBounds, "rerouteLineQueryBounds");
function rectSafeForLabel(rect, edge, labelNodeId, context, overrides, allowedForeignEdgeIds) {
  for (const obstacle of queryObstacleEntries(context, boundsForRect(rect), "obstacleRectQueries", {
    excludeNodeId: labelNodeId
  })) {
    if (rectOverlap(rect, obstacle.rect)) {
      return false;
    }
  }
  for (const border of context.groupBorderIndex.query(boundsForRect(rect))) {
    if (borderCutsRect(rect, border.rect)) {
      return false;
    }
  }
  for (const clearanceRect of markerClearanceRectsForEdge(edge, overrides, context)) {
    if (rectOverlap(rect, clearanceRect)) {
      return false;
    }
  }
  for (const foreignSegment of queryForeignSegments(
    context,
    boundsForRect(rect),
    edge.id,
    overrides,
    "segmentRectQueries"
  )) {
    if (allowedForeignEdgeIds?.has(foreignSegment.edgeId)) {
      continue;
    }
    if (segmentIntersectsRectInterior(foreignSegment.segment.a, foreignSegment.segment.b, rect)) {
      return false;
    }
  }
  return true;
}
__name(rectSafeForLabel, "rectSafeForLabel");
function requiredSegmentLength(node, segment) {
  return segment.orientation === "Z" ? 0 : gridLabelRequiredSegmentLength(node, segment.orientation);
}
__name(requiredSegmentLength, "requiredSegmentLength");
function blockedCenterIntervals(edge, labelNode, segment, context, overrides, includeForeignEdges) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  const labelWidth = labelNode.width;
  const labelHeight = labelNode.height;
  const alongHalf = segment.orientation === "H" ? labelWidth / 2 + LABEL_CLEARANCE : labelHeight / 2 + LABEL_CLEARANCE;
  const low = segment.orientation === "H" ? Math.min(segment.a.x, segment.b.x) + alongHalf : Math.min(segment.a.y, segment.b.y) + alongHalf;
  const high = segment.orientation === "H" ? Math.max(segment.a.x, segment.b.x) - alongHalf : Math.max(segment.a.y, segment.b.y) - alongHalf;
  if (high - low <= LABEL_EPSILON) {
    return null;
  }
  const blocked = [];
  const bandBounds = obstacleBandQueryBounds(segment, labelNode);
  if (!bandBounds) {
    return null;
  }
  const addRect = /* @__PURE__ */ __name((rect) => {
    if (segment.orientation === "H") {
      const bandTop = segment.a.y - labelHeight / 2;
      const bandBottom = segment.a.y + labelHeight / 2;
      if (rangeOverlaps(bandTop, bandBottom, rect.top, rect.bottom)) {
        blocked.push({
          start: rect.left - labelWidth / 2,
          end: rect.right + labelWidth / 2
        });
      }
      return;
    }
    const bandLeft = segment.a.x - labelWidth / 2;
    const bandRight = segment.a.x + labelWidth / 2;
    if (rangeOverlaps(bandLeft, bandRight, rect.left, rect.right)) {
      blocked.push({
        start: rect.top - labelHeight / 2,
        end: rect.bottom + labelHeight / 2
      });
    }
  }, "addRect");
  for (const obstacle of queryObstacleEntries(context, bandBounds, "obstacleBandQueries", {
    excludeNodeId: labelNode.id
  })) {
    addRect(obstacle.rect);
  }
  for (const clearanceRect of markerClearanceRectsForEdge(edge, overrides, context)) {
    addRect(clearanceRect);
  }
  if (includeForeignEdges) {
    for (const foreignSegment of queryForeignSegments(
      context,
      bandBounds,
      edge.id,
      overrides,
      "segmentBandQueries"
    )) {
      const segmentEntry = foreignSegment.segment;
      if (segment.orientation === "H") {
        const bandTop = segment.a.y - labelNode.height / 2;
        const bandBottom = segment.a.y + labelNode.height / 2;
        if (segmentEntry.orientation === "H") {
          if (bandTop < segmentEntry.a.y && bandBottom > segmentEntry.a.y) {
            blocked.push({
              start: Math.min(segmentEntry.a.x, segmentEntry.b.x) - labelNode.width / 2,
              end: Math.max(segmentEntry.a.x, segmentEntry.b.x) + labelNode.width / 2
            });
          }
        } else if (rangeOverlaps(
          bandTop,
          bandBottom,
          Math.min(segmentEntry.a.y, segmentEntry.b.y),
          Math.max(segmentEntry.a.y, segmentEntry.b.y)
        )) {
          blocked.push({
            start: segmentEntry.a.x - labelNode.width / 2,
            end: segmentEntry.a.x + labelNode.width / 2
          });
        }
        continue;
      }
      const bandLeft = segment.a.x - labelNode.width / 2;
      const bandRight = segment.a.x + labelNode.width / 2;
      if (segmentEntry.orientation === "V") {
        if (bandLeft < segmentEntry.a.x && bandRight > segmentEntry.a.x) {
          blocked.push({
            start: Math.min(segmentEntry.a.y, segmentEntry.b.y) - labelNode.height / 2,
            end: Math.max(segmentEntry.a.y, segmentEntry.b.y) + labelNode.height / 2
          });
        }
      } else if (rangeOverlaps(
        bandLeft,
        bandRight,
        Math.min(segmentEntry.a.x, segmentEntry.b.x),
        Math.max(segmentEntry.a.x, segmentEntry.b.x)
      )) {
        blocked.push({
          start: segmentEntry.a.y - labelNode.height / 2,
          end: segmentEntry.a.y + labelNode.height / 2
        });
      }
    }
  }
  return { low, high, blocked };
}
__name(blockedCenterIntervals, "blockedCenterIntervals");
function placementOnExistingSegment(edge, labelNode, segment, context) {
  if (segmentLength(segment) < requiredSegmentLength(labelNode, segment)) {
    return null;
  }
  const intervalData = blockedCenterIntervals(edge, labelNode, segment, context, void 0, true);
  if (!intervalData) {
    return null;
  }
  const preferred = segment.orientation === "H" ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2 : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;
  const candidates = centerCandidatesFromIntervals(
    intervalData.low,
    intervalData.high,
    intervalData.blocked,
    preferred
  );
  for (const candidate of candidates) {
    const center = segment.orientation === "H" ? { x: candidate, y: segment.a.y } : { x: segment.a.x, y: candidate };
    const rect = labelRectAt(labelNode, center);
    if (rectSafeForLabel(rect, edge, labelNode.id, context)) {
      return center;
    }
  }
  return null;
}
__name(placementOnExistingSegment, "placementOnExistingSegment");
function placementOnExistingSegmentWithReroutes(edge, labelNode, segment, context, placedLabelsByEdgeId) {
  const intervalData = blockedCenterIntervals(edge, labelNode, segment, context, void 0, false);
  if (!intervalData) {
    return null;
  }
  const preferred = segment.orientation === "H" ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2 : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;
  const candidates = centerCandidatesFromIntervals(
    intervalData.low,
    intervalData.high,
    intervalData.blocked,
    preferred
  );
  for (const candidate of candidates) {
    const center = segment.orientation === "H" ? { x: candidate, y: segment.a.y } : { x: segment.a.x, y: candidate };
    const rect = labelRectAt(labelNode, center);
    const overrides = /* @__PURE__ */ new Map();
    const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id).map((edgeId) => context.edgeById.get(edgeId)).filter((foreignEdge) => foreignEdge !== void 0);
    let ok = true;
    for (const foreignEdge of foreignEdges) {
      const reroutedPoints = rerouteForeignEdgeAroundRect(
        foreignEdge,
        rect,
        context,
        placedLabelsByEdgeId,
        overrides
      );
      if (!reroutedPoints) {
        ok = false;
        break;
      }
      overrides.set(foreignEdge.id, reroutedPoints);
    }
    if (!ok) {
      continue;
    }
    if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {
      continue;
    }
    for (const [edgeId, points] of overrides) {
      const foreignEdge = context.edgeById.get(edgeId);
      if (foreignEdge) {
        setEdgePoints(context, foreignEdge, points);
      }
    }
    return center;
  }
  return null;
}
__name(placementOnExistingSegmentWithReroutes, "placementOnExistingSegmentWithReroutes");
function polylineHitsProtectedObstacles(points, context, skipNodeIds) {
  for (const segment of normalizePolyline2(points).segments) {
    for (const obstacle of queryObstacleEntries(
      context,
      boundsForSegment(segment),
      "obstaclePolylineQueries",
      { skipNodeIds }
    )) {
      if (segmentIntersectsRectInterior(segment.a, segment.b, obstacle.rect)) {
        return true;
      }
    }
  }
  return false;
}
__name(polylineHitsProtectedObstacles, "polylineHitsProtectedObstacles");
function labelStillAnchored(edgeId, points, placedLabelsByEdgeId) {
  const placed = placedLabelsByEdgeId.get(edgeId);
  return !placed || orthogonalPolylineContainsPoint(points, placed.center, LABEL_EPSILON);
}
__name(labelStillAnchored, "labelStillAnchored");
function detourOffsets(crossHalfSize) {
  const out = [];
  for (let step = 0; step < MAX_GUTTER_STEPS; step++) {
    const offset = crossHalfSize + LABEL_GUTTER + step * LABEL_GUTTER_STEP;
    out.push(-offset, offset);
  }
  return out;
}
__name(detourOffsets, "detourOffsets");
function uniqueSortedCandidates(values, anchor) {
  const rounded = /* @__PURE__ */ new Map();
  for (const value of values) {
    const key = Math.round(value * 1e6) / 1e6;
    if (!rounded.has(key)) {
      rounded.set(key, value);
    }
  }
  return [...rounded.values()].sort((a, b) => {
    const distanceDelta = Math.abs(a - anchor) - Math.abs(b - anchor);
    if (Math.abs(distanceDelta) > LABEL_EPSILON) {
      return distanceDelta;
    }
    return a - b;
  });
}
__name(uniqueSortedCandidates, "uniqueSortedCandidates");
function detourLineCandidates(edge, labelNode, segment, context) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return [];
  }
  const labelWidth = labelNode.width;
  const labelHeight = labelNode.height;
  const anchor = segment.orientation === "H" ? segment.a.y : segment.a.x;
  const crossHalfSize = segment.orientation === "H" ? labelHeight / 2 : labelWidth / 2;
  const candidates = detourOffsets(crossHalfSize).map((offset) => anchor + offset);
  const addRect = /* @__PURE__ */ __name((rect) => {
    if (segment.orientation === "H") {
      candidates.push(rect.top - crossHalfSize - LABEL_GUTTER);
      candidates.push(rect.bottom + crossHalfSize + LABEL_GUTTER);
      return;
    }
    candidates.push(rect.left - crossHalfSize - LABEL_GUTTER);
    candidates.push(rect.right + crossHalfSize + LABEL_GUTTER);
  }, "addRect");
  for (const obstacle of queryObstacleEntries(
    context,
    detourLineQueryBounds(segment, labelNode, context.searchBounds),
    "obstacleBandQueries",
    { excludeNodeId: labelNode.id }
  )) {
    addRect(obstacle.rect);
  }
  for (const clearanceRect of markerClearanceRectsForEdge(edge, void 0, context)) {
    addRect(clearanceRect);
  }
  return uniqueSortedCandidates(candidates, anchor).slice(0, MAX_DETOUR_LINE_CANDIDATES);
}
__name(detourLineCandidates, "detourLineCandidates");
function rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane) {
  const anchor = segment.orientation === "H" ? segment.a.y : segment.a.x;
  const candidates = [];
  for (const offset of detourOffsets(0)) {
    if (segment.orientation === "H") {
      candidates.push(offset < 0 ? blockedRect.top + offset : blockedRect.bottom + offset);
    } else {
      candidates.push(offset < 0 ? blockedRect.left + offset : blockedRect.right + offset);
    }
  }
  const addRect = /* @__PURE__ */ __name((rect) => {
    if (segment.orientation === "H") {
      candidates.push(rect.top - LABEL_GUTTER);
      candidates.push(rect.bottom + LABEL_GUTTER);
      return;
    }
    candidates.push(rect.left - LABEL_GUTTER);
    candidates.push(rect.right + LABEL_GUTTER);
  }, "addRect");
  for (const obstacle of queryObstacleEntries(
    context,
    rerouteLineQueryBounds(segment, context.searchBounds),
    "obstacleBandQueries",
    { skipNodeIds }
  )) {
    addRect(obstacle.rect);
  }
  const sorted = uniqueSortedCandidates(candidates, anchor);
  const sideCandidates = lane?.orientation === segment.orientation ? sorted.filter((candidate) => {
    if (lane.side === "top") {
      return candidate < blockedRect.top;
    }
    if (lane.side === "bottom") {
      return candidate > blockedRect.bottom;
    }
    if (lane.side === "left") {
      return candidate < blockedRect.left;
    }
    return candidate > blockedRect.right;
  }) : sorted;
  return sideCandidates.slice(0, MAX_DETOUR_LINE_CANDIDATES);
}
__name(rerouteLineCandidates, "rerouteLineCandidates");
function detourCenterCandidates(edge, labelNode, segment, detourLineCoord, context) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return [];
  }
  const labelWidth = labelNode.width;
  const labelHeight = labelNode.height;
  const detourSegment = segment.orientation === "H" ? {
    orientation: "H",
    a: { x: segment.a.x, y: detourLineCoord },
    b: { x: segment.b.x, y: detourLineCoord }
  } : {
    orientation: "V",
    a: { x: detourLineCoord, y: segment.a.y },
    b: { x: detourLineCoord, y: segment.b.y }
  };
  const intervalData = blockedCenterIntervals(
    edge,
    labelNode,
    detourSegment,
    context,
    void 0,
    false
  );
  if (!intervalData) {
    const preferred2 = segment.orientation === "H" ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2 : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;
    const candidates = [preferred2];
    const queryBounds = obstacleBandQueryBounds(detourSegment, labelNode);
    const addRect = /* @__PURE__ */ __name((rect) => {
      if (segment.orientation === "H") {
        candidates.push(rect.left - LABEL_GUTTER - labelWidth / 2);
        candidates.push(rect.right + LABEL_GUTTER + labelWidth / 2);
        return;
      }
      candidates.push(rect.top - LABEL_GUTTER - labelHeight / 2);
      candidates.push(rect.bottom + LABEL_GUTTER + labelHeight / 2);
    }, "addRect");
    if (queryBounds) {
      for (const obstacle of queryObstacleEntries(context, queryBounds, "obstacleBandQueries", {
        excludeNodeId: labelNode.id
      })) {
        addRect(obstacle.rect);
      }
    }
    return uniqueSortedCandidates(candidates, preferred2).slice(0, MAX_DETOUR_CENTER_CANDIDATES);
  }
  const preferred = segment.orientation === "H" ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2 : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2;
  return centerCandidatesFromIntervals(
    intervalData.low,
    intervalData.high,
    intervalData.blocked,
    preferred
  );
}
__name(detourCenterCandidates, "detourCenterCandidates");
function detourReturnCoordinate(sourceLine, detourLine, labelHalfSize) {
  const direction = detourLine >= sourceLine ? 1 : -1;
  return detourLine + direction * (labelHalfSize + LABEL_CLEARANCE);
}
__name(detourReturnCoordinate, "detourReturnCoordinate");
var HORIZONTAL_DETOUR_AXIS = {
  along: /* @__PURE__ */ __name((point) => point.x, "along"),
  cross: /* @__PURE__ */ __name((point) => point.y, "cross"),
  point: /* @__PURE__ */ __name((along, cross) => ({ x: along, y: cross }), "point"),
  labelAlongSize: /* @__PURE__ */ __name((labelNode) => labelNode.width ?? 0, "labelAlongSize"),
  labelCrossSize: /* @__PURE__ */ __name((labelNode) => labelNode.height ?? 0, "labelCrossSize")
};
var VERTICAL_DETOUR_AXIS = {
  along: /* @__PURE__ */ __name((point) => point.y, "along"),
  cross: /* @__PURE__ */ __name((point) => point.x, "cross"),
  point: /* @__PURE__ */ __name((along, cross) => ({ x: cross, y: along }), "point"),
  labelAlongSize: /* @__PURE__ */ __name((labelNode) => labelNode.height ?? 0, "labelAlongSize"),
  labelCrossSize: /* @__PURE__ */ __name((labelNode) => labelNode.width ?? 0, "labelCrossSize")
};
function detourAxis(segment) {
  return segment.orientation === "H" ? HORIZONTAL_DETOUR_AXIS : VERTICAL_DETOUR_AXIS;
}
__name(detourAxis, "detourAxis");
function buildLabelDetourPoints(points, segmentIndex, segment, labelNode, centerAlong, detourLineCoord) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  const a = points[segmentIndex];
  const b = points[segmentIndex + 1];
  const axis = detourAxis(segment);
  const sourceLine = axis.cross(segment.a);
  const aAlong = axis.along(a);
  const bAlong = axis.along(b);
  const span = axis.labelAlongSize(labelNode) + LABEL_CLEARANCE * 2;
  const detourStart = centerAlong - span / 2;
  const detourEnd = centerAlong + span / 2;
  const extendsBeforeStart = detourStart < Math.min(aAlong, bAlong) - LABEL_EPSILON;
  const extendsAfterEnd = detourEnd > Math.max(aAlong, bAlong) + LABEL_EPSILON;
  const alongDirection = bAlong >= aAlong ? 1 : -1;
  const segmentInset = Math.max(
    0,
    Math.min(EDGE_END_MARKER_CLEARANCE, Math.abs(bAlong - aAlong) / 2 - LABEL_EPSILON)
  );
  const entryAlong = aAlong + alongDirection * segmentInset;
  const exitAlong = bAlong - alongDirection * segmentInset;
  if (!extendsBeforeStart && !extendsAfterEnd) {
    return normalizePolyline2([
      ...points.slice(0, segmentIndex),
      a,
      axis.point(detourStart, sourceLine),
      axis.point(detourStart, detourLineCoord),
      axis.point(detourEnd, detourLineCoord),
      axis.point(detourEnd, sourceLine),
      b,
      ...points.slice(segmentIndex + 2)
    ]).points;
  }
  const returnLine = detourReturnCoordinate(
    sourceLine,
    detourLineCoord,
    axis.labelCrossSize(labelNode) / 2
  );
  const detourPoints = [...points.slice(0, segmentIndex), a];
  if (extendsBeforeStart) {
    detourPoints.push(
      axis.point(entryAlong, sourceLine),
      axis.point(entryAlong, returnLine),
      axis.point(detourStart, returnLine),
      axis.point(detourStart, detourLineCoord)
    );
  } else {
    detourPoints.push(
      axis.point(detourStart, sourceLine),
      axis.point(detourStart, detourLineCoord)
    );
  }
  detourPoints.push(axis.point(detourEnd, detourLineCoord));
  if (extendsAfterEnd) {
    detourPoints.push(
      axis.point(detourEnd, returnLine),
      axis.point(exitAlong, returnLine),
      axis.point(exitAlong, sourceLine)
    );
  } else {
    detourPoints.push(axis.point(detourEnd, sourceLine));
  }
  detourPoints.push(b, ...points.slice(segmentIndex + 2));
  return normalizePolyline2(detourPoints).points;
}
__name(buildLabelDetourPoints, "buildLabelDetourPoints");
function buildExtendedLabelDetourPoints(points, segmentIndex, segment, labelNode, centerAlong, detourLineCoord, separateEntryAndExit) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  const a = points[segmentIndex];
  const b = points[segmentIndex + 1];
  const insetDivisor = separateEntryAndExit ? 4 : 2;
  const axis = detourAxis(segment);
  const sourceLine = axis.cross(segment.a);
  const aAlong = axis.along(a);
  const bAlong = axis.along(b);
  const span = axis.labelAlongSize(labelNode) + LABEL_CLEARANCE * 2;
  const detourStart = centerAlong - span / 2;
  const detourEnd = centerAlong + span / 2;
  const alongDirection = bAlong >= aAlong ? 1 : -1;
  const segmentInset = Math.max(
    0,
    Math.min(EDGE_END_MARKER_CLEARANCE, Math.abs(bAlong - aAlong) / insetDivisor - LABEL_EPSILON)
  );
  const entryAlong = aAlong + alongDirection * segmentInset;
  const exitAlong = bAlong - alongDirection * segmentInset;
  const returnLine = detourReturnCoordinate(
    sourceLine,
    detourLineCoord,
    axis.labelCrossSize(labelNode) / 2
  );
  return normalizePolyline2([
    ...points.slice(0, segmentIndex),
    a,
    axis.point(entryAlong, sourceLine),
    axis.point(entryAlong, detourLineCoord),
    axis.point(detourStart, detourLineCoord),
    axis.point(detourEnd, detourLineCoord),
    axis.point(detourEnd, returnLine),
    axis.point(exitAlong, returnLine),
    axis.point(exitAlong, sourceLine),
    b,
    ...points.slice(segmentIndex + 2)
  ]).points;
}
__name(buildExtendedLabelDetourPoints, "buildExtendedLabelDetourPoints");
function externalDetourCenterCandidates(segment, labelNode) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return [];
  }
  if (segment.orientation === "H") {
    const minX = Math.min(segment.a.x, segment.b.x);
    const maxX = Math.max(segment.a.x, segment.b.x);
    return [minX - labelNode.width / 2 - LABEL_GUTTER, maxX + labelNode.width / 2 + LABEL_GUTTER];
  }
  const minY = Math.min(segment.a.y, segment.b.y);
  const maxY = Math.max(segment.a.y, segment.b.y);
  return [minY - labelNode.height / 2 - LABEL_GUTTER, maxY + labelNode.height / 2 + LABEL_GUTTER];
}
__name(externalDetourCenterCandidates, "externalDetourCenterCandidates");
function blockedIntersectionScore(points, rect) {
  let count = 0;
  let length = 0;
  for (const segment of normalizePolyline2([...points]).segments) {
    if (!segmentIntersectsRectInterior(segment.a, segment.b, rect)) {
      continue;
    }
    count++;
    if (segment.orientation === "H") {
      length += Math.max(
        0,
        Math.min(Math.max(segment.a.x, segment.b.x), rect.right) - Math.max(Math.min(segment.a.x, segment.b.x), rect.left)
      );
    } else if (segment.orientation === "V") {
      length += Math.max(
        0,
        Math.min(Math.max(segment.a.y, segment.b.y), rect.bottom) - Math.max(Math.min(segment.a.y, segment.b.y), rect.top)
      );
    }
  }
  return { count, length };
}
__name(blockedIntersectionScore, "blockedIntersectionScore");
function reducesBlockedIntersections(candidate, blockedRect, baseline) {
  const score = blockedIntersectionScore(candidate, blockedRect);
  return score.count < baseline.count || score.count === baseline.count && score.length < baseline.length - LABEL_EPSILON;
}
__name(reducesBlockedIntersections, "reducesBlockedIntersections");
function rerouteLane(points, blockedRect, blockingReservations) {
  const segment = normalizePolyline2([...points]).segments.find(
    (candidate) => segmentIntersectsRectInterior(candidate.a, candidate.b, blockedRect)
  );
  if (!segment || segment.orientation === "Z") {
    return null;
  }
  const side = segment.orientation === "H" ? Math.abs(segment.a.y - blockedRect.top) <= Math.abs(blockedRect.bottom - segment.a.y) ? "top" : "bottom" : Math.abs(segment.a.x - blockedRect.left) <= Math.abs(blockedRect.right - segment.a.x) ? "left" : "right";
  const reservationIds = blockingReservations.map((reservation) => reservation.edgeId).sort(compareCodeUnits);
  return {
    key: JSON.stringify([reservationIds, segment.orientation, side]),
    orientation: segment.orientation,
    side
  };
}
__name(rerouteLane, "rerouteLane");
function rerouteSegmentAroundRect(edge, points, segmentIndex, blockedRect, context, placedLabelsByEdgeId, lane) {
  const normalized = normalizePolyline2(points);
  const baselineScore = blockedIntersectionScore(normalized.points, blockedRect);
  const segment = normalized.segments[segmentIndex];
  if (!segment || segment.orientation === "Z") {
    return null;
  }
  const a = normalized.points[segmentIndex];
  const b = normalized.points[segmentIndex + 1];
  const ownLabelNodeId = placedLabelsByEdgeId.get(edge.id)?.nodeId;
  const skipNodeIds = /* @__PURE__ */ new Set();
  if (ownLabelNodeId) {
    skipNodeIds.add(ownLabelNodeId);
  }
  if (segment.orientation === "H") {
    const minX = Math.min(a.x, b.x);
    const maxX = Math.max(a.x, b.x);
    const entry2 = Math.max(minX, blockedRect.left - LABEL_CLEARANCE);
    const exit2 = Math.min(maxX, blockedRect.right + LABEL_CLEARANCE);
    if (exit2 - entry2 <= LABEL_EPSILON) {
      incrementMetric(context.metrics, "rerouteRejectedDegenerateSpan");
      return null;
    }
    for (const y of rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane)) {
      incrementMetric(context.metrics, "rerouteCandidatesEvaluated");
      const candidatePoints = normalizePolyline2([
        ...normalized.points.slice(0, segmentIndex),
        a,
        { x: entry2, y: segment.a.y },
        { x: entry2, y },
        { x: exit2, y },
        { x: exit2, y: segment.a.y },
        b,
        ...normalized.points.slice(segmentIndex + 2)
      ]).points;
      if (polylineIntersectsRect(candidatePoints, blockedRect) && !reducesBlockedIntersections(candidatePoints, blockedRect, baselineScore)) {
        incrementMetric(context.metrics, "rerouteRejectedBlockedRect");
        continue;
      }
      if (polylineIntersectsRect(candidatePoints, blockedRect)) {
        incrementMetric(context.metrics, "reroutePartialProgressCandidates");
      }
      if (polylineHitsProtectedObstacles(candidatePoints, context, skipNodeIds)) {
        incrementMetric(context.metrics, "rerouteRejectedProtectedObstacle");
        continue;
      }
      if (!labelStillAnchored(edge.id, candidatePoints, placedLabelsByEdgeId)) {
        incrementMetric(context.metrics, "rerouteRejectedLabelAnchor");
        continue;
      }
      return candidatePoints;
    }
    return null;
  }
  const minY = Math.min(a.y, b.y);
  const maxY = Math.max(a.y, b.y);
  const entry = Math.max(minY, blockedRect.top - LABEL_CLEARANCE);
  const exit = Math.min(maxY, blockedRect.bottom + LABEL_CLEARANCE);
  if (exit - entry <= LABEL_EPSILON) {
    incrementMetric(context.metrics, "rerouteRejectedDegenerateSpan");
    return null;
  }
  for (const x of rerouteLineCandidates(segment, blockedRect, context, skipNodeIds, lane)) {
    incrementMetric(context.metrics, "rerouteCandidatesEvaluated");
    const candidatePoints = normalizePolyline2([
      ...normalized.points.slice(0, segmentIndex),
      a,
      { x: segment.a.x, y: entry },
      { x, y: entry },
      { x, y: exit },
      { x: segment.a.x, y: exit },
      b,
      ...normalized.points.slice(segmentIndex + 2)
    ]).points;
    if (polylineIntersectsRect(candidatePoints, blockedRect) && !reducesBlockedIntersections(candidatePoints, blockedRect, baselineScore)) {
      incrementMetric(context.metrics, "rerouteRejectedBlockedRect");
      continue;
    }
    if (polylineIntersectsRect(candidatePoints, blockedRect)) {
      incrementMetric(context.metrics, "reroutePartialProgressCandidates");
    }
    if (polylineHitsProtectedObstacles(candidatePoints, context, skipNodeIds)) {
      incrementMetric(context.metrics, "rerouteRejectedProtectedObstacle");
      continue;
    }
    if (!labelStillAnchored(edge.id, candidatePoints, placedLabelsByEdgeId)) {
      incrementMetric(context.metrics, "rerouteRejectedLabelAnchor");
      continue;
    }
    return candidatePoints;
  }
  return null;
}
__name(rerouteSegmentAroundRect, "rerouteSegmentAroundRect");
function rerouteForeignEdgeAroundRect(edge, blockedRect, context, placedLabelsByEdgeId, overrides, lane) {
  let currentPoints = pointsForEdge(edge, overrides, context);
  for (let attempt = 0; attempt < 8; attempt++) {
    if (!polylineIntersectsRect(currentPoints, blockedRect)) {
      return currentPoints;
    }
    const normalized = normalizePolyline2(currentPoints);
    const segmentIndex = normalized.points.findIndex((point, index) => {
      if (index === normalized.points.length - 1) {
        return false;
      }
      return segmentIntersectsRectInterior(point, normalized.points[index + 1], blockedRect);
    });
    if (segmentIndex < 0) {
      return currentPoints;
    }
    const rerouted = rerouteSegmentAroundRect(
      edge,
      normalized.points,
      segmentIndex,
      blockedRect,
      context,
      placedLabelsByEdgeId,
      lane
    );
    if (!rerouted) {
      return null;
    }
    currentPoints = rerouted;
  }
  return polylineIntersectsRect(currentPoints, blockedRect) ? null : currentPoints;
}
__name(rerouteForeignEdgeAroundRect, "rerouteForeignEdgeAroundRect");
function rerouteForeignEdgeAroundLabels(edge, reservations, context, placedLabelsByEdgeId, overrides) {
  const initialPoints = pointsForEdge(edge, overrides, context);
  let currentPoints = initialPoints;
  for (let pass = 0; pass < 2; pass++) {
    let changed = false;
    for (const reservation of reservations) {
      if (!polylineIntersectsRect(currentPoints, reservation.rect)) {
        continue;
      }
      incrementMetric(context.metrics, "individualLabelRerouteAttempts");
      overrides.set(edge.id, currentPoints);
      const rerouted = rerouteForeignEdgeAroundRect(
        edge,
        reservation.rect,
        context,
        placedLabelsByEdgeId,
        overrides
      );
      if (!rerouted) {
        overrides.set(edge.id, initialPoints);
        return null;
      }
      incrementMetric(context.metrics, "individualLabelRerouteSuccesses");
      currentPoints = rerouted;
      changed = true;
    }
    if (reservations.every((reservation) => !polylineIntersectsRect(currentPoints, reservation.rect))) {
      return currentPoints;
    }
    if (!changed) {
      break;
    }
  }
  overrides.set(edge.id, initialPoints);
  return null;
}
__name(rerouteForeignEdgeAroundLabels, "rerouteForeignEdgeAroundLabels");
function labelPlacementWithExtendedDetour(edge, labelNode, segmentCandidate, context, placedLabelsByEdgeId) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  const basePoints = pointsForEdge(edge, void 0, context);
  const segment = segmentCandidate.segment;
  for (const detourLineCoord of detourLineCandidates(edge, labelNode, segment, context)) {
    const centerCandidates = uniqueSortedCandidates(
      externalDetourCenterCandidates(segment, labelNode),
      segment.orientation === "H" ? (Math.min(segment.a.x, segment.b.x) + Math.max(segment.a.x, segment.b.x)) / 2 : (Math.min(segment.a.y, segment.b.y) + Math.max(segment.a.y, segment.b.y)) / 2
    );
    for (const centerAlong of centerCandidates) {
      const candidatePoints = buildExtendedLabelDetourPoints(
        basePoints,
        segmentCandidate.segmentIndex,
        segment,
        labelNode,
        centerAlong,
        detourLineCoord,
        edge.start === edge.end
      );
      if (!candidatePoints) {
        continue;
      }
      if (edge.start === edge.end && polylineHasSelfConflict(candidatePoints)) {
        continue;
      }
      if (polylineHitsProtectedObstacles(candidatePoints, context, /* @__PURE__ */ new Set([labelNode.id]))) {
        continue;
      }
      const center = segment.orientation === "H" ? { x: centerAlong, y: detourLineCoord } : { x: detourLineCoord, y: centerAlong };
      const rect = labelRectAt(labelNode, center);
      const overrides = /* @__PURE__ */ new Map([[edge.id, candidatePoints]]);
      const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id, overrides).map((edgeId) => context.edgeById.get(edgeId)).filter((foreignEdge) => foreignEdge !== void 0);
      let ok = true;
      for (const foreignEdge of foreignEdges) {
        const reroutedPoints = rerouteForeignEdgeAroundRect(
          foreignEdge,
          rect,
          context,
          placedLabelsByEdgeId,
          overrides
        );
        if (!reroutedPoints) {
          ok = false;
          break;
        }
        overrides.set(foreignEdge.id, reroutedPoints);
      }
      if (!ok) {
        continue;
      }
      if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {
        continue;
      }
      setEdgePoints(context, edge, candidatePoints);
      for (const [edgeId, points] of overrides) {
        if (edgeId === edge.id) {
          continue;
        }
        const foreignEdge = context.edgeById.get(edgeId);
        if (foreignEdge) {
          setEdgePoints(context, foreignEdge, points);
        }
      }
      return center;
    }
  }
  return null;
}
__name(labelPlacementWithExtendedDetour, "labelPlacementWithExtendedDetour");
function labelPlacementWithDetour(edge, labelNode, segmentCandidate, context, placedLabelsByEdgeId) {
  if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
    return null;
  }
  const basePoints = pointsForEdge(edge, void 0, context);
  const segment = segmentCandidate.segment;
  for (const detourLineCoord of detourLineCandidates(edge, labelNode, segment, context)) {
    const centerCandidates = detourCenterCandidates(
      edge,
      labelNode,
      segment,
      detourLineCoord,
      context
    );
    for (const centerAlong of centerCandidates) {
      const candidatePoints = buildLabelDetourPoints(
        basePoints,
        segmentCandidate.segmentIndex,
        segment,
        labelNode,
        centerAlong,
        detourLineCoord
      );
      if (!candidatePoints) {
        continue;
      }
      if (edge.start === edge.end && polylineHasSelfConflict(candidatePoints)) {
        continue;
      }
      if (polylineHitsProtectedObstacles(candidatePoints, context, /* @__PURE__ */ new Set([labelNode.id]))) {
        continue;
      }
      const center = segment.orientation === "H" ? { x: centerAlong, y: detourLineCoord } : { x: detourLineCoord, y: centerAlong };
      const rect = labelRectAt(labelNode, center);
      const overrides = /* @__PURE__ */ new Map([[edge.id, candidatePoints]]);
      const foreignEdges = foreignEdgeIdsIntersectingRect(context, rect, edge.id, overrides).map((edgeId) => context.edgeById.get(edgeId)).filter((foreignEdge) => foreignEdge !== void 0);
      let ok = true;
      for (const foreignEdge of foreignEdges) {
        const reroutedPoints = rerouteForeignEdgeAroundRect(
          foreignEdge,
          rect,
          context,
          placedLabelsByEdgeId,
          overrides
        );
        if (!reroutedPoints) {
          ok = false;
          break;
        }
        overrides.set(foreignEdge.id, reroutedPoints);
      }
      if (!ok) {
        continue;
      }
      if (!rectSafeForLabel(rect, edge, labelNode.id, context, overrides)) {
        continue;
      }
      setEdgePoints(context, edge, candidatePoints);
      for (const [edgeId, points] of overrides) {
        if (edgeId === edge.id) {
          continue;
        }
        const foreignEdge = context.edgeById.get(edgeId);
        if (foreignEdge) {
          setEdgePoints(context, foreignEdge, points);
        }
      }
      return center;
    }
  }
  return null;
}
__name(labelPlacementWithDetour, "labelPlacementWithDetour");
function isPreparedLabelNode(node) {
  return Boolean(node && isEdgeLabelNode(node));
}
__name(isPreparedLabelNode, "isPreparedLabelNode");
function parkDegenerateLabel(edge, labelNode, nodeById) {
  const routePoint = edge.points?.find(
    (point) => Number.isFinite(point.x) && Number.isFinite(point.y)
  );
  const source = edge.start ? nodeById.get(edge.start) : void 0;
  const target = edge.end ? nodeById.get(edge.end) : void 0;
  const fallback = routePoint ?? (source && hasFinitePosition(source) ? source : void 0) ?? target;
  if (fallback && Number.isFinite(fallback.x) && Number.isFinite(fallback.y)) {
    labelNode.x = fallback.x;
    labelNode.y = fallback.y;
    return;
  }
  delete labelNode.x;
  delete labelNode.y;
}
__name(parkDegenerateLabel, "parkDegenerateLabel");
function placeLabelAtRouteMidpoint(edge, labelNode, nodeById) {
  let longestSegment;
  for (const segment of normalizePolyline2(edge.points ?? []).segments) {
    if (segment.orientation === "Z") {
      continue;
    }
    if (!longestSegment || segmentLength(segment) > segmentLength(longestSegment)) {
      longestSegment = segment;
    }
  }
  if (!longestSegment) {
    parkDegenerateLabel(edge, labelNode, nodeById);
    return;
  }
  labelNode.x = (longestSegment.a.x + longestSegment.b.x) / 2;
  labelNode.y = (longestSegment.a.y + longestSegment.b.y) / 2;
}
__name(placeLabelAtRouteMidpoint, "placeLabelAtRouteMidpoint");
function preferredGridLabelNodeId(edge) {
  return `${GRID_LABEL_PREFIX}${edge.start ?? ""}-${edge.end ?? ""}-${edge.id}`;
}
__name(preferredGridLabelNodeId, "preferredGridLabelNodeId");
function ensureUniqueGridLabelNodeId(edge, nodeById) {
  const baseId = edge.labelNodeId ?? preferredGridLabelNodeId(edge);
  let candidateId = baseId;
  let suffix = 1;
  while (true) {
    if (!nodeById.has(candidateId)) {
      return candidateId;
    }
    candidateId = `${baseId}-${suffix}`;
    suffix += 1;
  }
}
__name(ensureUniqueGridLabelNodeId, "ensureUniqueGridLabelNodeId");
function prepareGridLayout(data) {
  const nodeById = /* @__PURE__ */ new Map();
  for (const node of data.nodes) {
    nodeById.set(node.id, node);
  }
  const newNodes = [];
  for (const edge of data.edges) {
    if (!edge.label || edge.label.length === 0) {
      continue;
    }
    const sourceNode = edge.start ? nodeById.get(edge.start) : void 0;
    const existingHelper = edge.labelNodeId ? nodeById.get(edge.labelNodeId) : void 0;
    if (isPreparedLabelNode(existingHelper)) {
      existingHelper.label = edge.label;
      existingHelper.labelStyle = Array.isArray(edge.labelStyle) ? edge.labelStyle[0] : edge.labelStyle ?? "";
      existingHelper.edgeStart = edge.start ?? "";
      existingHelper.edgeEnd = edge.end ?? "";
      if (sourceNode?.dir) {
        existingHelper.dir = sourceNode.dir;
      }
      edge.label = void 0;
      edge.text = void 0;
      continue;
    }
    const labelNodeId = ensureUniqueGridLabelNodeId(edge, nodeById);
    const labelNode = {
      id: labelNodeId,
      label: edge.label,
      edgeStart: edge.start ?? "",
      edgeEnd: edge.end ?? "",
      shape: "labelRect",
      width: 0,
      height: 0,
      isEdgeLabel: true,
      isDummy: true,
      isGroup: false,
      parentId: void 0,
      labelStyle: Array.isArray(edge.labelStyle) ? edge.labelStyle[0] : edge.labelStyle ?? "",
      ...sourceNode?.dir ? { dir: sourceNode.dir } : {}
    };
    newNodes.push(labelNode);
    nodeById.set(labelNodeId, labelNode);
    edge.labelNodeId = labelNodeId;
    edge.label = void 0;
    edge.text = void 0;
  }
  data.nodes.push(...newNodes);
}
__name(prepareGridLayout, "prepareGridLayout");
function positionGridEdgeLabels(data, instrumentation, routingInstrumentation, options = {}) {
  const nodeById = /* @__PURE__ */ new Map();
  for (const node of data.nodes) {
    nodeById.set(node.id, node);
  }
  const labelNodes = data.nodes.filter(isEdgeLabelNode);
  const baseLabelPositions = new Map(
    labelNodes.map((labelNode) => [labelNode.id, { x: labelNode.x, y: labelNode.y }])
  );
  for (const labelNode of labelNodes) {
    delete labelNode.x;
    delete labelNode.y;
  }
  const preparedLabels = data.edges.map((edge, sourceIndex) => {
    if (!edge.labelNodeId) {
      return null;
    }
    const labelNode = nodeById.get(edge.labelNodeId);
    if (!labelNode) {
      return null;
    }
    if (!isFinitePositiveNumber(labelNode.width) || !isFinitePositiveNumber(labelNode.height)) {
      incrementMetric(instrumentation, "unmeasuredLabelsSkipped");
      return null;
    }
    return { edge, labelNode, sourceIndex };
  }).filter((entry) => entry !== null);
  if (preparedLabels.length === 0) {
    return;
  }
  const baseEdgePoints = new Map(
    data.edges.map((edge) => [edge.id, edge.points?.map((point) => ({ ...point }))])
  );
  const restoreBaseEdgePoints = /* @__PURE__ */ __name(() => {
    for (const edge of data.edges) {
      const points = baseEdgePoints.get(edge.id);
      if (points) {
        edge.points = points.map((point) => ({ ...point }));
      } else {
        delete edge.points;
      }
    }
  }, "restoreBaseEdgePoints");
  const restoreBaseState = /* @__PURE__ */ __name(() => {
    restoreBaseEdgePoints();
    for (const labelNode of labelNodes) {
      const position = baseLabelPositions.get(labelNode.id);
      if (position && Number.isFinite(position.x) && Number.isFinite(position.y)) {
        labelNode.x = position.x;
        labelNode.y = position.y;
      } else {
        delete labelNode.x;
        delete labelNode.y;
      }
    }
  }, "restoreBaseState");
  const workItems = preparedLabels.filter(({ edge, labelNode }) => {
    if (normalizePolyline2(edge.points ?? []).segments.length > 0) {
      return true;
    }
    parkDegenerateLabel(edge, labelNode, nodeById);
    incrementMetric(instrumentation, "degenerateLabelRoutesSkipped");
    return false;
  }).sort((a, b) => a.sourceIndex - b.sourceIndex || compareCodeUnits(a.edge.id, b.edge.id));
  if (workItems.length === 0) {
    return;
  }
  const placeLabelsAtRouteMidpoints = /* @__PURE__ */ __name(() => {
    restoreBaseEdgePoints();
    for (const { edge, labelNode } of workItems) {
      placeLabelAtRouteMidpoint(edge, labelNode, nodeById);
    }
  }, "placeLabelsAtRouteMidpoints");
  const configuredIndexWork = options.maxIndexWork ?? DEFAULT_MAX_INDEX_WORK;
  const indexWorkLimit = Number.isFinite(configuredIndexWork) && configuredIndexWork >= 0 ? Math.floor(configuredIndexWork) : DEFAULT_MAX_INDEX_WORK;
  const indexWorkBudget = new LabelIndexWorkBudget(indexWorkLimit, instrumentation);
  const placementFailures = [];
  for (let pass = 1; pass <= 2; pass++) {
    incrementMetric(instrumentation, "labelPasses");
    const context = createEdgeLabelContext(data, indexWorkBudget, instrumentation);
    const placedLabelsByEdgeId = /* @__PURE__ */ new Map();
    const allowedOverlapsByLabelEdgeId = /* @__PURE__ */ new Map();
    const passStartPoints = new Map(
      data.edges.map((edge) => [edge.id, pointsForEdge(edge, void 0, context).map(clonePoint)])
    );
    const proposedOwnerRoutes = /* @__PURE__ */ new Map();
    try {
      for (const { edge, labelNode } of workItems) {
        const segments = [...candidateSegments(edge, context)].sort((a, b) => {
          const lengthDelta = segmentLength(b.segment) - segmentLength(a.segment);
          if (Math.abs(lengthDelta) > LABEL_EPSILON) {
            return lengthDelta;
          }
          return a.order - b.order;
        });
        let labelCenter = null;
        for (const segmentCandidate of segments) {
          labelCenter = placementOnExistingSegment(
            edge,
            labelNode,
            segmentCandidate.segment,
            context
          );
          if (labelCenter) {
            break;
          }
        }
        if (!labelCenter) {
          for (const segmentCandidate of segments) {
            labelCenter = placementOnExistingSegmentWithReroutes(
              edge,
              labelNode,
              segmentCandidate.segment,
              context,
              placedLabelsByEdgeId
            );
            if (labelCenter) {
              break;
            }
          }
        }
        if (pass === 2 && !labelCenter) {
          for (const segmentCandidate of segments) {
            labelCenter = labelPlacementWithDetour(
              edge,
              labelNode,
              segmentCandidate,
              context,
              placedLabelsByEdgeId
            );
            if (labelCenter) {
              break;
            }
          }
        }
        if (pass === 2 && !labelCenter) {
          for (const segmentCandidate of segments) {
            labelCenter = labelPlacementWithExtendedDetour(
              edge,
              labelNode,
              segmentCandidate,
              context,
              placedLabelsByEdgeId
            );
            if (labelCenter) {
              break;
            }
          }
        }
        if (!labelCenter) {
          throw new LabelPlacementSearchExhaustedError({
            edgeId: edge.id,
            labelNodeId: labelNode.id,
            labelWidth: labelNode.width,
            labelHeight: labelNode.height,
            pointCount: edge.points?.length ?? 0,
            points: edge.points?.map((point) => ({ ...point })) ?? [],
            segments: segments.map(({ segment }) => ({
              orientation: segment.orientation,
              length: segmentLength(segment),
              a: { ...segment.a },
              b: { ...segment.b }
            }))
          });
        }
        labelNode.x = labelCenter.x;
        labelNode.y = labelCenter.y;
        const placedLabel = {
          edgeId: edge.id,
          nodeId: labelNode.id,
          center: labelCenter,
          rect: labelRectAt(labelNode, labelCenter)
        };
        placedLabelsByEdgeId.set(edge.id, placedLabel);
        upsertPlacedLabelObstacle(context, placedLabel);
      }
      const frozenLabels = [...placedLabelsByEdgeId.values()];
      incrementMetric(instrumentation, "frozenReservations", frozenLabels.length);
      if (routingInstrumentation) {
        routingInstrumentation.labelOverlayBuilds++;
        routingInstrumentation.labelOverlayVertices += frozenLabels.length * 4;
      }
      for (const edge of data.edges) {
        const passStart = passStartPoints.get(edge.id) ?? [];
        const proposed = pointsForEdge(edge, void 0, context);
        if (JSON.stringify(proposed) !== JSON.stringify(passStart)) {
          proposedOwnerRoutes.set(edge.id, proposed.map(clonePoint));
        }
        setEdgePoints(context, edge, passStart.map(clonePoint));
      }
      for (const [edgeId, points] of proposedOwnerRoutes) {
        if (!placedLabelsByEdgeId.has(edgeId)) {
          continue;
        }
        const owner = context.edgeById.get(edgeId);
        if (owner) {
          setEdgePoints(context, owner, points);
        }
      }
      const impacted = new Set(proposedOwnerRoutes.keys());
      for (const edge of data.edges) {
        const ownLabel = placedLabelsByEdgeId.get(edge.id);
        const points = pointsForEdge(edge, void 0, context);
        for (const reservation of frozenLabels) {
          if (reservation.edgeId !== edge.id && polylineIntersectsRect(points, reservation.rect)) {
            impacted.add(edge.id);
          }
        }
        if (ownLabel && !labelStillAnchored(edge.id, points, placedLabelsByEdgeId)) {
          impacted.add(edge.id);
        }
      }
      const rerouteLaneOrdinals = /* @__PURE__ */ new Map();
      for (const edge of data.edges) {
        if (!impacted.has(edge.id)) {
          continue;
        }
        let points = pointsForEdge(edge, void 0, context);
        const overrides = /* @__PURE__ */ new Map([[edge.id, points]]);
        const blockingReservations = frozenLabels.filter(
          (reservation) => reservation.edgeId !== edge.id && polylineIntersectsRect(points, reservation.rect)
        );
        if (blockingReservations.length > 0) {
          const combinedRect = blockingReservations.slice(1).reduce(
            (combined, reservation) => ({
              cx: (Math.min(combined.left, reservation.rect.left) + Math.max(combined.right, reservation.rect.right)) / 2,
              cy: (Math.min(combined.top, reservation.rect.top) + Math.max(combined.bottom, reservation.rect.bottom)) / 2,
              left: Math.min(combined.left, reservation.rect.left),
              right: Math.max(combined.right, reservation.rect.right),
              top: Math.min(combined.top, reservation.rect.top),
              bottom: Math.max(combined.bottom, reservation.rect.bottom)
            }),
            { ...blockingReservations[0].rect }
          );
          const lane = rerouteLane(points, combinedRect, blockingReservations);
          const rerouteOrdinal = lane ? rerouteLaneOrdinals.get(lane.key) ?? 0 : 0;
          const lanePadding = (rerouteOrdinal + 2) * 12;
          const blockedRect = {
            cx: combinedRect.cx,
            cy: combinedRect.cy,
            left: combinedRect.left - lanePadding,
            right: combinedRect.right + lanePadding,
            top: combinedRect.top - lanePadding,
            bottom: combinedRect.bottom + lanePadding
          };
          let rerouted = rerouteForeignEdgeAroundRect(
            edge,
            blockedRect,
            context,
            placedLabelsByEdgeId,
            overrides,
            lane ?? void 0
          );
          const usedScopedLane = rerouted !== null;
          rerouted ??= rerouteForeignEdgeAroundLabels(
            edge,
            blockingReservations,
            context,
            placedLabelsByEdgeId,
            overrides
          );
          if (rerouted) {
            points = rerouted;
            overrides.set(edge.id, points);
            if (lane && usedScopedLane) {
              rerouteLaneOrdinals.set(lane.key, rerouteOrdinal + 1);
            }
          } else {
            incrementMetric(instrumentation, "labelOverlapFallbacks");
            for (const reservation of blockingReservations) {
              if (!polylineIntersectsRect(points, reservation.rect)) {
                continue;
              }
              const allowedEdges = allowedOverlapsByLabelEdgeId.get(reservation.edgeId) ?? /* @__PURE__ */ new Set();
              if (!allowedEdges.has(edge.id)) {
                incrementMetric(instrumentation, "labelOverlapReservations");
              }
              allowedEdges.add(edge.id);
              allowedOverlapsByLabelEdgeId.set(reservation.edgeId, allowedEdges);
            }
          }
        }
        if (!labelStillAnchored(edge.id, points, placedLabelsByEdgeId)) {
          throw gridError("GRID_ROUTE_NOT_FOUND", `Label anchor was lost for edge "${edge.id}"`, {
            edgeId: edge.id,
            pass
          });
        }
        if (placedLabelsByEdgeId.has(edge.id)) {
          incrementMetric(instrumentation, "preservedAnchors");
        }
        setEdgePoints(context, edge, points);
        incrementMetric(instrumentation, "impactedEdgeReroutes");
      }
      for (const { edge, labelNode } of workItems) {
        const reservation = placedLabelsByEdgeId.get(edge.id);
        if (!reservation || !labelStillAnchored(
          edge.id,
          pointsForEdge(edge, void 0, context),
          placedLabelsByEdgeId
        ) || !rectSafeForLabel(
          reservation.rect,
          edge,
          labelNode.id,
          context,
          void 0,
          allowedOverlapsByLabelEdgeId.get(edge.id)
        )) {
          throw gridError("GRID_ROUTE_NOT_FOUND", `Label pass ${pass} did not validate`, {
            edgeId: edge.id,
            pass
          });
        }
      }
      return;
    } catch (error) {
      if (error instanceof LabelIndexWorkLimitError) {
        placeLabelsAtRouteMidpoints();
        incrementMetric(instrumentation, "indexWorkLimitFallbacks");
        if (routingInstrumentation) {
          routingInstrumentation.resourceLimitFallbacks++;
          routingInstrumentation.fallbackReasons.label_index_work_cap++;
        }
        return;
      }
      if (!(error instanceof LabelPlacementSearchExhaustedError)) {
        restoreBaseState();
        incrementMetric(instrumentation, "rollbacks");
        throw error;
      }
      placementFailures.push(error);
      restoreBaseEdgePoints();
      for (const { labelNode } of workItems) {
        delete labelNode.x;
        delete labelNode.y;
      }
    }
  }
  placeLabelsAtRouteMidpoints();
  incrementMetric(instrumentation, "placementSearchFallbacks");
  if (routingInstrumentation) {
    routingInstrumentation.fallbackReasons.label_placement_exhausted++;
  }
  log.warn(
    "[grid]",
    "Label placement search exhausted; using route midpoints. Labels may overlap.",
    {
      reason: "label_placement_exhausted",
      edgeIds: workItems.map(({ edge }) => edge.id),
      failures: placementFailures.map(({ details }) => details)
    }
  );
}
__name(positionGridEdgeLabels, "positionGridEdgeLabels");

// src/rendering-util/layout-algorithms/grid/groups.ts
function asGroup(node) {
  return node.isGroup ? node : void 0;
}
__name(asGroup, "asGroup");
function buildGridForest(nodes) {
  const nodeById = /* @__PURE__ */ new Map();
  const groupById = /* @__PURE__ */ new Map();
  const helperNodeIds = /* @__PURE__ */ new Set();
  for (const node of nodes) {
    if (node.id === ROOT_CONTAINER_ID) {
      throw gridError(
        "GRID_INVALID_CONTAINMENT",
        `Node id "${ROOT_CONTAINER_ID}" is reserved for the grid layout root`,
        { traversedIds: [node.id] }
      );
    }
    if (nodeById.has(node.id)) {
      throw gridError("GRID_INVALID_CONTAINMENT", `Duplicate node id "${node.id}"`, {
        traversedIds: [node.id]
      });
    }
    nodeById.set(node.id, node);
    if (isEdgeLabelNode(node)) {
      helperNodeIds.add(node.id);
      continue;
    }
    const group = asGroup(node);
    if (group) {
      groupById.set(group.id, group);
    }
  }
  const childrenByParent = /* @__PURE__ */ new Map();
  childrenByParent.set(ROOT_CONTAINER_ID, []);
  for (const node of nodes) {
    if (helperNodeIds.has(node.id)) {
      continue;
    }
    const parentId = node.parentId ?? ROOT_CONTAINER_ID;
    if (parentId !== ROOT_CONTAINER_ID) {
      const parent = groupById.get(parentId);
      if (!parent) {
        throw gridError(
          "GRID_INVALID_CONTAINMENT",
          `Missing parent "${parentId}" for "${node.id}"`,
          {
            traversedIds: [node.id, parentId]
          }
        );
      }
    }
    if (!childrenByParent.has(parentId)) {
      childrenByParent.set(parentId, []);
    }
    childrenByParent.get(parentId).push(node);
  }
  const state = /* @__PURE__ */ new Map();
  const postOrderGroups = [];
  const directChildGroups = /* @__PURE__ */ __name((groupId) => (childrenByParent.get(groupId) ?? []).map((child) => asGroup(child)).filter((group) => group !== void 0), "directChildGroups");
  const visit = /* @__PURE__ */ __name((startGroupId) => {
    const currentState = state.get(startGroupId) ?? 0;
    if (currentState === 1) {
      throw gridError("GRID_INVALID_CONTAINMENT", `Containment cycle at "${startGroupId}"`, {
        traversedIds: [startGroupId]
      });
    }
    if (currentState === 2) {
      return;
    }
    state.set(startGroupId, 1);
    const stack = [
      {
        groupId: startGroupId,
        childGroups: directChildGroups(startGroupId),
        nextChildIndex: 0
      }
    ];
    while (stack.length > 0) {
      const frame = stack[stack.length - 1];
      const child = frame.childGroups[frame.nextChildIndex];
      if (child) {
        frame.nextChildIndex += 1;
        const childState = state.get(child.id) ?? 0;
        if (childState === 1) {
          throw gridError("GRID_INVALID_CONTAINMENT", `Containment cycle at "${child.id}"`, {
            traversedIds: [...stack.map((item) => item.groupId), child.id]
          });
        }
        if (childState === 2) {
          continue;
        }
        state.set(child.id, 1);
        stack.push({
          groupId: child.id,
          childGroups: directChildGroups(child.id),
          nextChildIndex: 0
        });
        continue;
      }
      stack.pop();
      state.set(frame.groupId, 2);
      const group = groupById.get(frame.groupId);
      if (group) {
        postOrderGroups.push(group);
      }
    }
  }, "visit");
  for (const rootChild of childrenByParent.get(ROOT_CONTAINER_ID) ?? []) {
    const group = asGroup(rootChild);
    if (group) {
      visit(group.id);
    }
  }
  for (const groupId of groupById.keys()) {
    if ((state.get(groupId) ?? 0) === 0) {
      visit(groupId);
    }
  }
  return {
    nodeById,
    groupById,
    childrenByParent,
    rootChildren: childrenByParent.get(ROOT_CONTAINER_ID) ?? [],
    postOrderGroups,
    helperNodeIds
  };
}
__name(buildGridForest, "buildGridForest");
function isAncestorGroup(ancestorId, node, nodeById) {
  let current = node;
  const seen = /* @__PURE__ */ new Set();
  while (current?.parentId) {
    if (current.parentId === ancestorId) {
      return true;
    }
    if (seen.has(current.parentId)) {
      return false;
    }
    seen.add(current.parentId);
    current = nodeById.get(current.parentId);
  }
  return false;
}
__name(isAncestorGroup, "isAncestorGroup");

// src/rendering-util/layout-algorithms/grid/labelSpacing.ts
function buildGridLabelRequirements(data, forest, metrics) {
  const byContainer = /* @__PURE__ */ new Map();
  const selfLoops = /* @__PURE__ */ new Map();
  for (const edge of data.edges) {
    if (!edge.start || !edge.end || !edge.labelNodeId) {
      continue;
    }
    if (metrics) {
      metrics.labelSpacingEdgesExamined++;
    }
    const labelNode = forest.nodeById.get(edge.labelNodeId);
    const source = forest.nodeById.get(edge.start);
    const target = forest.nodeById.get(edge.end);
    if (!labelNode || !source || !target) {
      continue;
    }
    if (edge.start === edge.end) {
      const horizontal = gridLabelSpanRequirement(labelNode, "H");
      if (horizontal) {
        selfLoops.set(edge.id, horizontal);
      }
      continue;
    }
    const sourceContainer = source.parentId ?? ROOT_CONTAINER_ID;
    const targetContainer = target.parentId ?? ROOT_CONTAINER_ID;
    if (sourceContainer !== targetContainer) {
      continue;
    }
    const entries = byContainer.get(sourceContainer);
    if (entries) {
      entries.push({ edge, labelNode });
    } else {
      byContainer.set(sourceContainer, [{ edge, labelNode }]);
    }
  }
  return { byContainer, selfLoops };
}
__name(buildGridLabelRequirements, "buildGridLabelRequirements");
function trackOrigins(tracks, sizes, gap) {
  const origins = /* @__PURE__ */ new Map();
  let cursor = 0;
  for (const track of tracks) {
    origins.set(track, cursor);
    cursor += (sizes.get(track) ?? 0) + gap;
  }
  return origins;
}
__name(trackOrigins, "trackOrigins");
function crossAxisFits(track, crossSize, tracks, sizes, gap) {
  const origins = trackOrigins(tracks, sizes, gap);
  const origin = origins.get(track);
  const size = sizes.get(track);
  if (origin === void 0 || size === void 0) {
    return false;
  }
  const center = origin + size / 2;
  const low = center - crossSize / 2;
  const high = center + crossSize / 2;
  return tracks.every((other) => {
    if (other === track) {
      return true;
    }
    const otherOrigin = origins.get(other);
    const otherEnd = otherOrigin + (sizes.get(other) ?? 0);
    return high <= otherOrigin || low >= otherEnd;
  });
}
__name(crossAxisFits, "crossAxisFits");
function placementByNodeId(cells) {
  const placements = /* @__PURE__ */ new Map();
  for (const cell of cells.values()) {
    for (const placement of cell.items) {
      placements.set(placement.item.id, placement);
    }
  }
  return placements;
}
__name(placementByNodeId, "placementByNodeId");
function areConsecutive(first, second, tracks) {
  const low = Math.min(first, second);
  const high = Math.max(first, second);
  const index = tracks.indexOf(low);
  return index >= 0 && tracks[index + 1] === high;
}
__name(areConsecutive, "areConsecutive");
function addGapRequirement(gaps, track, required) {
  gaps.set(track, Math.max(gaps.get(track) ?? 0, required));
}
__name(addGapRequirement, "addGapRequirement");
function deriveGridContainerLabelGaps(entries, cells, rowHeights, columnWidths, sortedRows, sortedColumns, configuredRowGap, configuredColumnGap, metrics) {
  const rowGapAfter = /* @__PURE__ */ new Map();
  const columnGapAfter = /* @__PURE__ */ new Map();
  const placements = placementByNodeId(cells);
  const requirementFor = /* @__PURE__ */ __name((entry, orientation) => gridLabelSpanRequirement(entry.labelNode, orientation), "requirementFor");
  for (const entry of entries) {
    const source = entry.edge.start ? placements.get(entry.edge.start) : void 0;
    const target = entry.edge.end ? placements.get(entry.edge.end) : void 0;
    if (!source || !target) {
      continue;
    }
    if (source.row === target.row && areConsecutive(source.column, target.column, sortedColumns)) {
      const requirement = requirementFor(entry, "H");
      if (requirement && crossAxisFits(source.row, requirement.cross, sortedRows, rowHeights, configuredRowGap)) {
        if (metrics) {
          metrics.labelSpacingEligibleEdges++;
        }
        addGapRequirement(
          columnGapAfter,
          Math.min(source.column, target.column),
          requirement.requiredAlongSpan
        );
      }
      continue;
    }
    if (source.column === target.column && areConsecutive(source.row, target.row, sortedRows)) {
      const requirement = requirementFor(entry, "V");
      if (requirement && crossAxisFits(
        source.column,
        requirement.cross,
        sortedColumns,
        columnWidths,
        configuredColumnGap
      )) {
        if (metrics) {
          metrics.labelSpacingEligibleEdges++;
        }
        addGapRequirement(
          rowGapAfter,
          Math.min(source.row, target.row),
          requirement.requiredAlongSpan
        );
      }
    }
  }
  return { rowGapAfter, columnGapAfter };
}
__name(deriveGridContainerLabelGaps, "deriveGridContainerLabelGaps");

// src/rendering-util/layout-algorithms/grid/placement.ts
var GRID_LOG_PREFIX = "[grid]";
var GRID_CURVES = /* @__PURE__ */ new Set([
  "basis",
  "bumpX",
  "bumpY",
  "cardinal",
  "catmullRom",
  "linear",
  "monotoneX",
  "monotoneY",
  "natural",
  "step",
  "stepAfter",
  "stepBefore",
  "rounded"
]);
function isObjectRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
__name(isObjectRecord, "isObjectRecord");
function ownPlacementFrom(value) {
  if (!isObjectRecord(value)) {
    return {};
  }
  const placement = {};
  if (Object.hasOwn(value, "row")) {
    placement.row = value.row;
  }
  if (Object.hasOwn(value, "column")) {
    placement.column = value.column;
  }
  if (isGridHorizontalAlign(value.horizontalAlign)) {
    placement.horizontalAlign = value.horizontalAlign;
  }
  if (isGridVerticalAlign(value.verticalAlign)) {
    placement.verticalAlign = value.verticalAlign;
  }
  return placement;
}
__name(ownPlacementFrom, "ownPlacementFrom");
function buildGridSourceOrder(nodes) {
  const order = /* @__PURE__ */ new Map();
  let index = 0;
  for (const node of nodes) {
    if (!order.has(node.id)) {
      order.set(node.id, index++);
    }
  }
  return order;
}
__name(buildGridSourceOrder, "buildGridSourceOrder");
function readGridConfig(data) {
  const raw = isObjectRecord(data.config?.grid) ? data.config.grid : {};
  const placementsRaw = isObjectRecord(raw.placements) ? raw.placements : {};
  const placements = /* @__PURE__ */ new Map();
  for (const key of Object.keys(placementsRaw)) {
    const value = placementsRaw[key];
    const occurrencePlacements = Array.isArray(value) ? value : [value];
    placements.set(
      key,
      occurrencePlacements.map((placement) => ownPlacementFrom(placement))
    );
  }
  return {
    placements,
    columns: typeof raw.columns === "number" && Number.isFinite(raw.columns) && raw.columns >= 0 ? Math.trunc(raw.columns) : GRID_DEFAULTS.columns,
    rowGap: typeof raw.rowGap === "number" && Number.isFinite(raw.rowGap) && raw.rowGap >= 0 ? raw.rowGap : GRID_DEFAULTS.rowGap,
    columnGap: typeof raw.columnGap === "number" && Number.isFinite(raw.columnGap) && raw.columnGap >= 0 ? raw.columnGap : GRID_DEFAULTS.columnGap,
    cellGap: typeof raw.cellGap === "number" && Number.isFinite(raw.cellGap) && raw.cellGap >= 0 ? raw.cellGap : GRID_DEFAULTS.cellGap,
    containerPadding: typeof raw.containerPadding === "number" && Number.isFinite(raw.containerPadding) && raw.containerPadding >= 0 ? raw.containerPadding : GRID_DEFAULTS.containerPadding,
    titleGap: typeof raw.titleGap === "number" && Number.isFinite(raw.titleGap) && raw.titleGap >= 0 ? raw.titleGap : GRID_DEFAULTS.titleGap,
    horizontalAlign: isGridHorizontalAlign(raw.horizontalAlign) ? raw.horizontalAlign : GRID_DEFAULTS.horizontalAlign,
    verticalAlign: isGridVerticalAlign(raw.verticalAlign) ? raw.verticalAlign : GRID_DEFAULTS.verticalAlign,
    // Normalize rendering options with placement so every routed edge receives one stable style.
    curve: typeof raw.curve === "string" && GRID_CURVES.has(raw.curve) ? raw.curve : GRID_DEFAULTS.curve,
    edgeCornerRadius: resolveEdgeCornerRadius(raw.edgeCornerRadius)
  };
}
__name(readGridConfig, "readGridConfig");
function validateGridPlacementMap(items, config) {
  const knownIdCounts = /* @__PURE__ */ new Map();
  for (const item of items) {
    const placementId = item.placementId ?? item.id;
    knownIdCounts.set(placementId, (knownIdCounts.get(placementId) ?? 0) + 1);
  }
  for (const [key, placements] of config.placements) {
    const matchingItems = knownIdCounts.get(key) ?? 0;
    if (matchingItems === 0) {
      log.warn(GRID_LOG_PREFIX, `Ignoring grid placement for unknown target "${key}"`);
      continue;
    }
    if (placements.length > matchingItems) {
      log.warn(
        GRID_LOG_PREFIX,
        `Ignoring ${placements.length - matchingItems} extra grid placement occurrence(s) for target "${key}"; found ${matchingItems} matching node(s)`
      );
    }
  }
}
__name(validateGridPlacementMap, "validateGridPlacementMap");
function itemComparator(sourceOrder) {
  return (a, b) => {
    const aOrder = sourceOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
    const bOrder = sourceOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
    if (aOrder !== bOrder) {
      return aOrder - bOrder;
    }
    return compareCodeUnits(a.id, b.id);
  };
}
__name(itemComparator, "itemComparator");
function resolveItemPlacement(item, sourceOrder, config, occurrenceIndex) {
  const authoredPlacementId = item.placementId ?? item.id;
  const configPlacement = config.placements.get(authoredPlacementId)?.[occurrenceIndex] ?? {};
  const metadataPlacement = ownPlacementFrom(item.metadata);
  for (const field of ["row", "column", "horizontalAlign", "verticalAlign"]) {
    if (Object.hasOwn(configPlacement, field) && Object.hasOwn(metadataPlacement, field) && configPlacement[field] !== metadataPlacement[field]) {
      log.debug(GRID_LOG_PREFIX, "metadata overrides placement map", {
        nodeId: item.id,
        field,
        metadata: metadataPlacement[field],
        config: configPlacement[field]
      });
    }
  }
  const row = Object.hasOwn(metadataPlacement, "row") ? metadataPlacement.row : configPlacement.row;
  const column = Object.hasOwn(metadataPlacement, "column") ? metadataPlacement.column : configPlacement.column;
  validateGridCoordinate(authoredPlacementId, "row", row, item.id);
  validateGridCoordinate(authoredPlacementId, "column", column, item.id);
  return {
    item,
    row: row ?? 0,
    column: column ?? 0,
    horizontalAlign: metadataPlacement.horizontalAlign ?? configPlacement.horizontalAlign ?? config.horizontalAlign,
    verticalAlign: metadataPlacement.verticalAlign ?? configPlacement.verticalAlign ?? config.verticalAlign,
    sourceOrder: sourceOrder.get(item.id) ?? Number.MAX_SAFE_INTEGER,
    explicitRow: row !== void 0,
    explicitColumn: column !== void 0,
    explicitCell: row !== void 0 && column !== void 0
  };
}
__name(resolveItemPlacement, "resolveItemPlacement");
function nextFreeColumn(row, occupied, startColumn) {
  let column = startColumn;
  while (occupied.has(`${row}:${column}`)) {
    column++;
  }
  return column;
}
__name(nextFreeColumn, "nextFreeColumn");
function nextFreeRow(column, occupied, startRow) {
  let row = startRow;
  while (occupied.has(`${row}:${column}`)) {
    row++;
  }
  return row;
}
__name(nextFreeRow, "nextFreeRow");
function nextAutoCell(occupied, candidateColumns, startIndex) {
  let index = startIndex;
  for (; ; ) {
    const row = Math.floor(index / candidateColumns) + 1;
    const column = index % candidateColumns + 1;
    index++;
    if (!occupied.has(`${row}:${column}`)) {
      return { row, column, nextIndex: index };
    }
  }
}
__name(nextAutoCell, "nextAutoCell");
function resolveGridPlacements(items, sourceOrder, config) {
  const sortedItems = [...items].sort(itemComparator(sourceOrder));
  const occurrenceByPlacementId = /* @__PURE__ */ new Map();
  const resolved = sortedItems.map((item) => {
    const placementId = item.placementId ?? item.id;
    const occurrenceIndex = occurrenceByPlacementId.get(placementId) ?? 0;
    occurrenceByPlacementId.set(placementId, occurrenceIndex + 1);
    return resolveItemPlacement(item, sourceOrder, config, occurrenceIndex);
  });
  const cells = /* @__PURE__ */ new Map();
  const occupied = /* @__PURE__ */ new Set();
  for (const placement of resolved) {
    if (!placement.explicitCell) {
      continue;
    }
    const key = `${placement.row}:${placement.column}`;
    occupied.add(key);
    const existing = cells.get(key);
    if (existing) {
      if (existing.verticalAlign !== placement.verticalAlign) {
        throw gridError(
          "GRID_CELL_ALIGNMENT_CONFLICT",
          `Conflicting vertical alignment in cell (${placement.row}, ${placement.column})`,
          {
            containerId: placement.item.parentId ?? "root",
            row: placement.row,
            column: placement.column,
            itemIds: [...existing.items.map((item) => item.item.id), placement.item.id],
            values: [...existing.items.map((item) => item.verticalAlign), placement.verticalAlign]
          }
        );
      }
      existing.items.push(placement);
    } else {
      cells.set(key, {
        row: placement.row,
        column: placement.column,
        items: [placement],
        width: 0,
        height: 0,
        verticalAlign: placement.verticalAlign
      });
    }
  }
  const candidateColumns = config.columns > 0 ? config.columns : Math.max(1, Math.ceil(Math.sqrt(sortedItems.length)));
  let nextAutoIndex = 0;
  const nextColumnByRow = /* @__PURE__ */ new Map();
  const nextRowByColumn = /* @__PURE__ */ new Map();
  for (const placement of resolved) {
    if (placement.explicitCell) {
      continue;
    }
    if (placement.explicitRow) {
      const column = nextFreeColumn(
        placement.row,
        occupied,
        nextColumnByRow.get(placement.row) ?? 1
      );
      placement.column = column;
      nextColumnByRow.set(placement.row, column + 1);
    } else if (placement.explicitColumn) {
      const row = nextFreeRow(
        placement.column,
        occupied,
        nextRowByColumn.get(placement.column) ?? 1
      );
      placement.row = row;
      nextRowByColumn.set(placement.column, row + 1);
    } else {
      const next = nextAutoCell(occupied, candidateColumns, nextAutoIndex);
      placement.row = next.row;
      placement.column = next.column;
      nextAutoIndex = next.nextIndex;
    }
    const key = `${placement.row}:${placement.column}`;
    occupied.add(key);
    cells.set(key, {
      row: placement.row,
      column: placement.column,
      items: [placement],
      width: 0,
      height: 0,
      verticalAlign: placement.verticalAlign
    });
  }
  return { placements: resolved, cells };
}
__name(resolveGridPlacements, "resolveGridPlacements");

// src/rendering-util/layout-algorithms/grid/routerErrors.ts
var GridRoutingResourceLimitError = class extends Error {
  constructor(reason, message, searchStateScope) {
    super(message);
    this.reason = reason;
    this.searchStateScope = searchStateScope;
    this.name = "GridRoutingResourceLimitError";
  }
  static {
    __name(this, "GridRoutingResourceLimitError");
  }
};

// src/rendering-util/layout-algorithms/grid/routerTopology.ts
var ROUTE_CLEARANCE_PX = 6;
var EDGE_CLEARANCE_PX = 24;
var DEFAULT_MAX_VERTICES = 5e4;
var MAX_VISIBILITY_ADJACENCY_PER_VERTEX = 4;
var DEFAULT_MAX_ROUTING_ESTIMATED_BYTES = 64 * 1024 * 1024;
var CompressedIntervalIndex = class {
  constructor(bands, strictBoundaryIntervals) {
    this.bands = bands;
    this.strictBoundaryIntervals = strictBoundaryIntervals;
    this.byLow = /* @__PURE__ */ new Map();
    this.byHigh = /* @__PURE__ */ new Map();
    this.coordinateCount = new Set(bands.flatMap(({ low, high }) => [low, high])).size;
    let intervalCount = bands.reduce((total, band) => total + band.intervals.length, 0);
    for (const intervals of strictBoundaryIntervals.values()) {
      intervalCount += intervals.length;
    }
    this.intervalCount = intervalCount;
    for (const band of bands) {
      this.byLow.set(band.low, band);
      this.byHigh.set(band.high, band);
    }
    Object.freeze(this.bands);
    Object.freeze(this);
  }
  static {
    __name(this, "CompressedIntervalIndex");
  }
  containingBand(coordinate) {
    let low = 0;
    let high = this.bands.length - 1;
    while (low <= high) {
      const middle = low + high >>> 1;
      const band = this.bands[middle];
      if (coordinate <= band.low) {
        high = middle - 1;
      } else if (coordinate >= band.high) {
        low = middle + 1;
      } else {
        return band;
      }
    }
    return void 0;
  }
  overlaps(intervals, low, high) {
    let left = 0;
    let right = intervals.length;
    while (left < right) {
      const middle = left + right >>> 1;
      if (intervals[middle][1] <= low) {
        left = middle + 1;
      } else {
        right = middle;
      }
    }
    return left < intervals.length && intervals[left][0] < high;
  }
  intersects(coordinate, intervalStart, intervalEnd) {
    const low = Math.min(intervalStart, intervalEnd);
    const high = Math.max(intervalStart, intervalEnd);
    const before = this.byHigh.get(coordinate);
    const after = this.byLow.get(coordinate);
    const containing = before || after ? void 0 : this.containingBand(coordinate);
    if (containing) {
      return this.overlaps(containing.intervals, low, high);
    }
    if (!before || !after) {
      return false;
    }
    let beforeIndex = 0;
    let afterIndex = 0;
    while (beforeIndex < before.intervals.length && afterIndex < after.intervals.length) {
      const overlapLow = Math.max(
        low,
        before.intervals[beforeIndex][0],
        after.intervals[afterIndex][0]
      );
      const overlapHigh = Math.min(
        high,
        before.intervals[beforeIndex][1],
        after.intervals[afterIndex][1]
      );
      if (overlapLow < overlapHigh) {
        return true;
      }
      if (before.intervals[beforeIndex][1] < after.intervals[afterIndex][1]) {
        beforeIndex++;
      } else {
        afterIndex++;
      }
    }
    return false;
  }
  contains(coordinate, varying) {
    const intervals = this.strictBoundaryIntervals.get(coordinate) ?? this.containingBand(coordinate)?.intervals;
    if (!intervals) {
      return false;
    }
    let low = 0;
    let high = intervals.length;
    while (low < high) {
      const middle = low + high >>> 1;
      if (intervals[middle][0] < varying) {
        low = middle + 1;
      } else {
        high = middle;
      }
    }
    return low > 0 && varying < intervals[low - 1][1];
  }
  nearestBoundary(coordinate, origin, direction) {
    const intervals = this.strictBoundaryIntervals.get(coordinate) ?? this.containingBand(coordinate)?.intervals;
    if (!intervals) {
      return void 0;
    }
    if (direction < 0) {
      let low2 = 0;
      let high2 = intervals.length;
      while (low2 < high2) {
        const middle = low2 + high2 >>> 1;
        if (intervals[middle][1] <= origin) {
          low2 = middle + 1;
        } else {
          high2 = middle;
        }
      }
      return low2 > 0 ? intervals[low2 - 1][1] : void 0;
    }
    let low = 0;
    let high = intervals.length;
    while (low < high) {
      const middle = low + high >>> 1;
      if (intervals[middle][0] < origin) {
        low = middle + 1;
      } else {
        high = middle;
      }
    }
    return low < intervals.length ? intervals[low][0] : void 0;
  }
};
var _a;
var ImmutableMap = class {
  constructor(backing) {
    this.backing = backing;
    this[_a] = "ImmutableMap";
    Object.freeze(this);
  }
  static {
    __name(this, "ImmutableMap");
  }
  get size() {
    return this.backing.size;
  }
  entries() {
    return this.backing.entries();
  }
  forEach(callbackfn, thisArg) {
    for (const [key, value] of this.backing) {
      callbackfn.call(thisArg, value, key, this);
    }
  }
  get(key) {
    return this.backing.get(key);
  }
  has(key) {
    return this.backing.has(key);
  }
  keys() {
    return this.backing.keys();
  }
  values() {
    return this.backing.values();
  }
  [(_a = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
};
var _a2;
var OverlayMap = class {
  constructor(base, overrides) {
    this.base = base;
    this.overrides = overrides;
    this[_a2] = "OverlayMap";
  }
  static {
    __name(this, "OverlayMap");
  }
  get size() {
    let added = 0;
    for (const key of this.overrides.keys()) {
      if (!this.base.has(key)) {
        added++;
      }
    }
    return this.base.size + added;
  }
  materialize() {
    return new Map([...this.base, ...this.overrides]);
  }
  entries() {
    return this.materialize().entries();
  }
  forEach(callbackfn, thisArg) {
    for (const [key, value] of this) {
      callbackfn.call(thisArg, value, key, this);
    }
  }
  get(key) {
    return this.overrides.get(key) ?? this.base.get(key);
  }
  has(key) {
    return this.overrides.has(key) || this.base.has(key);
  }
  keys() {
    return this.materialize().keys();
  }
  values() {
    return this.materialize().values();
  }
  [(_a2 = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
};
function overlayArray(base, additions) {
  return new Proxy([], {
    get(_target, property) {
      if (property === "length") {
        return base.length + additions.length;
      }
      if (property === Symbol.iterator) {
        return function* () {
          yield* base;
          yield* additions;
        };
      }
      if (typeof property === "string" && /^\d+$/.test(property)) {
        const index = Number(property);
        return index < base.length ? base[index] : additions[index - base.length];
      }
      return Reflect.get(Array.prototype, property);
    }
  });
}
__name(overlayArray, "overlayArray");
function overrideArray(base, overrides, length) {
  return new Proxy([], {
    get(_target, property) {
      if (property === "length") {
        return length;
      }
      if (property === Symbol.iterator) {
        return function* () {
          for (let index = 0; index < length; index++) {
            yield overrides.get(index) ?? base[index];
          }
        };
      }
      if (typeof property === "string" && /^\d+$/.test(property)) {
        const index = Number(property);
        return overrides.get(index) ?? base[index];
      }
      return Reflect.get(Array.prototype, property);
    }
  });
}
__name(overrideArray, "overrideArray");
var EndpointOverlayScratch = class {
  constructor(base) {
    this.base = base;
    // One scratch object belongs to one base topology. The undo log clears only overridden base
    // vertices, keeping reset cost proportional to the previous overlay rather than the whole graph.
    this.addedVertices = [];
    this.adjacencyOverrides = /* @__PURE__ */ new Map();
    this.searchAdjacencyOverrides = /* @__PURE__ */ new Map();
    this.pointOverrides = /* @__PURE__ */ new Map();
    this.undoLog = [];
    this.resetCount = 0;
  }
  static {
    __name(this, "EndpointOverlayScratch");
  }
  reset(base) {
    if (base !== this.base) {
      throw new Error("Endpoint overlay scratch cannot be shared across base topologies");
    }
    for (const id of this.undoLog) {
      this.adjacencyOverrides.delete(id);
      this.searchAdjacencyOverrides.delete(id);
    }
    this.undoLog.length = 0;
    this.addedVertices.length = 0;
    this.pointOverrides.clear();
    this.resetCount++;
  }
  setArcs(id, arcs) {
    if (!this.adjacencyOverrides.has(id)) {
      this.undoLog.push(id);
    }
    this.adjacencyOverrides.set(id, arcs);
    this.searchAdjacencyOverrides.set(id, searchArcs(arcs));
  }
};
function normalizeCoordinate(value) {
  return Object.is(value, -0) ? 0 : value;
}
__name(normalizeCoordinate, "normalizeCoordinate");
function normalizeRect(rect) {
  const values = [rect.left, rect.right, rect.top, rect.bottom];
  if (!values.every(Number.isFinite)) {
    throw new Error("Grid routing geometry must contain only finite coordinates");
  }
  const left = normalizeCoordinate(Math.min(rect.left, rect.right));
  const right = normalizeCoordinate(Math.max(rect.left, rect.right));
  const top = normalizeCoordinate(Math.min(rect.top, rect.bottom));
  const bottom = normalizeCoordinate(Math.max(rect.top, rect.bottom));
  if (left === right || top === bottom) {
    throw new Error("Grid routing rectangles must have positive area");
  }
  return { left, right, top, bottom };
}
__name(normalizeRect, "normalizeRect");
function inflateAndClip(input, domain) {
  const bounds = normalizeRect(input.bounds);
  const obstacle = {
    id: input.id,
    left: Math.max(domain.left, bounds.left - ROUTE_CLEARANCE_PX),
    right: Math.min(domain.right, bounds.right + ROUTE_CLEARANCE_PX),
    top: Math.max(domain.top, bounds.top - ROUTE_CLEARANCE_PX),
    bottom: Math.min(domain.bottom, bounds.bottom + ROUTE_CLEARANCE_PX)
  };
  return obstacle.left < obstacle.right && obstacle.top < obstacle.bottom ? obstacle : void 0;
}
__name(inflateAndClip, "inflateAndClip");
function mergeObstacleIntervals(intervals) {
  const sorted = [...intervals].sort(
    (a, b) => a.low - b.low || a.high - b.high || compareCodeUnits(a.id, b.id)
  );
  const merged = [];
  for (const interval of sorted) {
    const previous = merged.at(-1);
    if (!previous || interval.low > previous.high) {
      merged.push({ ...interval });
      continue;
    }
    previous.high = Math.max(previous.high, interval.high);
    if (compareCodeUnits(interval.id, previous.id) < 0) {
      previous.id = interval.id;
    }
  }
  return merged;
}
__name(mergeObstacleIntervals, "mergeObstacleIntervals");
function unionObstacles(obstacles) {
  const events = /* @__PURE__ */ new Map();
  for (const obstacle of obstacles) {
    const start = events.get(obstacle.left) ?? { starts: [], ends: [] };
    start.starts.push(obstacle);
    events.set(obstacle.left, start);
    const end = events.get(obstacle.right) ?? { starts: [], ends: [] };
    end.ends.push(obstacle);
    events.set(obstacle.right, end);
  }
  const xCoordinates = [...events.keys()].sort((a, b) => a - b);
  const active = /* @__PURE__ */ new Set();
  const slabs = [];
  let previousByInterval = /* @__PURE__ */ new Map();
  for (let index = 0; index < xCoordinates.length - 1; index++) {
    const left = xCoordinates[index];
    const right = xCoordinates[index + 1];
    const event = events.get(left);
    for (const obstacle of event.ends) {
      active.delete(obstacle);
    }
    for (const obstacle of event.starts) {
      active.add(obstacle);
    }
    const nextByInterval = /* @__PURE__ */ new Map();
    for (const interval of mergeObstacleIntervals(
      [...active].map((obstacle) => ({
        low: obstacle.top,
        high: obstacle.bottom,
        id: obstacle.id
      }))
    )) {
      const key = `${interval.low}:${interval.high}`;
      const previous = previousByInterval.get(key);
      if (previous) {
        previous.right = right;
        if (compareCodeUnits(interval.id, previous.id) < 0) {
          previous.id = interval.id;
        }
      } else {
        const slab = {
          id: interval.id,
          left,
          right,
          top: interval.low,
          bottom: interval.high
        };
        slabs.push(slab);
        nextByInterval.set(key, slab);
        continue;
      }
      nextByInterval.set(key, previous);
    }
    previousByInterval = nextByInterval;
  }
  return slabs.sort(
    (a, b) => a.top - b.top || a.left - b.left || a.bottom - b.bottom || a.right - b.right || compareCodeUnits(a.id, b.id)
  );
}
__name(unionObstacles, "unionObstacles");
function routingPointKey(point) {
  return `${normalizeCoordinate(point.x)}:${normalizeCoordinate(point.y)}`;
}
__name(routingPointKey, "routingPointKey");
function topologySideOrdinal(side) {
  return side === "left" ? 0 : side === "right" ? 1 : side === "top" ? 2 : side === "bottom" ? 3 : 4;
}
__name(topologySideOrdinal, "topologySideOrdinal");
function vertexRecordOrder(a, b) {
  return compareCodeUnits(a.kind, b.kind) || topologySideOrdinal(a.side) - topologySideOrdinal(b.side) || a.point.x - b.point.x || a.point.y - b.point.y || compareCodeUnits(a.ownerId ?? "", b.ownerId ?? "");
}
__name(vertexRecordOrder, "vertexRecordOrder");
function canonicalRecords(records) {
  const byPoint = /* @__PURE__ */ new Map();
  for (const record of [...records].sort(vertexRecordOrder)) {
    const normalized = {
      ...record,
      point: {
        x: normalizeCoordinate(record.point.x),
        y: normalizeCoordinate(record.point.y)
      }
    };
    const key = routingPointKey(normalized.point);
    if (!byPoint.has(key)) {
      byPoint.set(key, normalized);
    }
  }
  return [...byPoint.values()];
}
__name(canonicalRecords, "canonicalRecords");
function cornerRecords(bounds, ownerId, kind = "corner") {
  return [
    { point: { x: bounds.left, y: bounds.top }, kind, ownerId },
    { point: { x: bounds.right, y: bounds.top }, kind, ownerId },
    { point: { x: bounds.left, y: bounds.bottom }, kind, ownerId },
    { point: { x: bounds.right, y: bounds.bottom }, kind, ownerId }
  ];
}
__name(cornerRecords, "cornerRecords");
function portalRecords(range, bounds) {
  const coordinate = range.coordinate ?? (range.side === "left" ? bounds.left : range.side === "right" ? bounds.right : range.side === "top" ? bounds.top : bounds.bottom);
  const points = range.side === "left" || range.side === "right" ? [
    { x: coordinate, y: range.low },
    { x: coordinate, y: range.high }
  ] : [
    { x: range.low, y: coordinate },
    { x: range.high, y: coordinate }
  ];
  return points.map((value) => ({
    point: value,
    kind: "portal",
    ownerId: range.ownerId,
    side: range.side
  }));
}
__name(portalRecords, "portalRecords");
function rayHit(point, side, bounds, horizontalIntervals, verticalIntervals) {
  if (side === "left" || side === "right") {
    const hit2 = horizontalIntervals.nearestBoundary(point.y, point.x, side === "left" ? -1 : 1) ?? (side === "left" ? bounds.left : bounds.right);
    return { x: hit2, y: point.y };
  }
  const hit = verticalIntervals.nearestBoundary(point.x, point.y, side === "top" ? -1 : 1) ?? (side === "top" ? bounds.top : bounds.bottom);
  return { x: point.x, y: hit };
}
__name(rayHit, "rayHit");
function createIntervalIndex(obstacles, orientation, budget) {
  const coordinates = [
    ...new Set(
      obstacles.flatMap(
        (obstacle) => orientation === "H" ? [obstacle.top, obstacle.bottom] : [obstacle.left, obstacle.right]
      )
    )
  ].sort((a, b) => a - b);
  const bands = [];
  const strictBoundaryIntervals = /* @__PURE__ */ new Map();
  const starts = /* @__PURE__ */ new Map();
  const ends = /* @__PURE__ */ new Map();
  for (const obstacle of obstacles) {
    const start = orientation === "H" ? obstacle.top : obstacle.left;
    const end = orientation === "H" ? obstacle.bottom : obstacle.right;
    const startEvents = starts.get(start) ?? [];
    startEvents.push(obstacle);
    starts.set(start, startEvents);
    const endEvents = ends.get(end) ?? [];
    endEvents.push(obstacle);
    ends.set(end, endEvents);
  }
  const active = /* @__PURE__ */ new Set();
  const activeIntervals = /* @__PURE__ */ __name(() => mergeObstacleIntervals(
    [...active].map(
      (obstacle) => orientation === "H" ? { low: obstacle.left, high: obstacle.right, id: obstacle.id } : { low: obstacle.top, high: obstacle.bottom, id: obstacle.id }
    )
  ), "activeIntervals");
  const freezeIntervals = /* @__PURE__ */ __name((intervals) => {
    const intervalCount = budget.intervalCount + intervals.length;
    enforceCap(
      estimatedTopologyBytes(0, 0, obstacles.length, intervalCount),
      budget.maxEstimatedBytes,
      "estimated_memory_cap"
    );
    budget.intervalCount = intervalCount;
    return Object.freeze(
      intervals.map((interval) => Object.freeze([interval.low, interval.high]))
    );
  }, "freezeIntervals");
  for (let index = 0; index < coordinates.length; index++) {
    const coordinate = coordinates[index];
    for (const obstacle of ends.get(coordinate) ?? []) {
      active.delete(obstacle);
    }
    strictBoundaryIntervals.set(coordinate, freezeIntervals(activeIntervals()));
    for (const obstacle of starts.get(coordinate) ?? []) {
      active.add(obstacle);
    }
    const high = coordinates[index + 1];
    if (high === void 0) {
      continue;
    }
    const intervals = activeIntervals();
    if (intervals.length > 0) {
      bands.push({
        low: coordinate,
        high,
        intervals: freezeIntervals(intervals)
      });
    }
  }
  return new CompressedIntervalIndex(
    Object.freeze(bands),
    new ImmutableMap(strictBoundaryIntervals)
  );
}
__name(createIntervalIndex, "createIntervalIndex");
function estimatedTopologyBytes(vertices, adjacencyEntries, obstacles, intervals) {
  return vertices * 64 + adjacencyEntries * 56 + obstacles * 48 + intervals * 24;
}
__name(estimatedTopologyBytes, "estimatedTopologyBytes");
function enforceCap(actual, maximum, reason) {
  if (actual > maximum) {
    throw new GridRoutingResourceLimitError(
      reason,
      `Grid routing ${reason} exceeded: ${actual} > ${maximum}`
    );
  }
}
__name(enforceCap, "enforceCap");
function indexVertexLines(vertices, orientation) {
  const lines = /* @__PURE__ */ new Map();
  for (const vertex of vertices) {
    const fixed = orientation === "H" ? vertex.point.y : vertex.point.x;
    const line = lines.get(fixed) ?? [];
    line.push(vertex);
    lines.set(fixed, line);
  }
  for (const line of lines.values()) {
    line.sort(
      (a, b) => orientation === "H" ? a.point.x - b.point.x || a.id - b.id : a.point.y - b.point.y || a.id - b.id
    );
    Object.freeze(line);
  }
  return new ImmutableMap(lines);
}
__name(indexVertexLines, "indexVertexLines");
function searchArcs(arcs) {
  return Object.freeze(
    arcs.map(
      (arc) => Object.freeze({
        to: arc.to,
        orientationOrdinal: arc.orientation === "H" ? 1 : 2,
        length: arc.length,
        boundaryTransitions: arc.kind === "portal" ? 1 : 0
      })
    )
  );
}
__name(searchArcs, "searchArcs");
function buildVisibilityGraph(records, horizontalIntervals, verticalIntervals, caps) {
  const canonical = canonicalRecords(records).sort(vertexRecordOrder);
  const vertexCap = caps.maxVertices ?? DEFAULT_MAX_VERTICES;
  enforceCap(canonical.length, vertexCap, "vertex_cap");
  const vertices = canonical.map(
    (record, id) => Object.freeze({ id, ...record, point: Object.freeze({ ...record.point }) })
  );
  const adjacency = new Map(
    vertices.map((vertex) => [vertex.id, []])
  );
  const addArcPair = /* @__PURE__ */ __name((a, b, orientation) => {
    const length = Math.abs(a.point.x - b.point.x) + Math.abs(a.point.y - b.point.y);
    if (length === 0) {
      return;
    }
    const intervalStart = orientation === "H" ? Math.min(a.point.x, b.point.x) : Math.min(a.point.y, b.point.y);
    const intervalEnd = intervalStart + length;
    for (const [from, to] of [
      [a, b],
      [b, a]
    ]) {
      adjacency.get(from.id).push({
        from: from.id,
        to: to.id,
        orientation,
        length,
        kind: "visibility",
        intervalStart,
        intervalEnd
      });
    }
  }, "addArcPair");
  for (const orientation of ["H", "V"]) {
    const lines = /* @__PURE__ */ new Map();
    for (const vertex of vertices) {
      const coordinate = orientation === "H" ? vertex.point.y : vertex.point.x;
      const line = lines.get(coordinate) ?? [];
      line.push(vertex);
      lines.set(coordinate, line);
    }
    for (const [fixed, line] of lines) {
      line.sort(
        (a, b) => orientation === "H" ? a.point.x - b.point.x || a.id - b.id : a.point.y - b.point.y || a.id - b.id
      );
      for (let index = 1; index < line.length; index++) {
        const a = line[index - 1];
        const b = line[index];
        const start = orientation === "H" ? a.point.x : a.point.y;
        const end = orientation === "H" ? b.point.x : b.point.y;
        const intervalIndex = orientation === "H" ? horizontalIntervals : verticalIntervals;
        if (!intervalIndex.intersects(fixed, start, end)) {
          addArcPair(a, b, orientation);
        }
      }
    }
  }
  const arcKindOrder = {
    visibility: 0,
    terminal: 1,
    portal: 2,
    lane: 3
  };
  let adjacencyEntries = 0;
  const immutableAdjacency = /* @__PURE__ */ new Map();
  for (const vertex of vertices) {
    const arcs = adjacency.get(vertex.id);
    arcs.sort(
      (a, b) => arcKindOrder[a.kind] - arcKindOrder[b.kind] || compareCodeUnits(a.orientation, b.orientation) || vertices[a.to].point.x - vertices[b.to].point.x || vertices[a.to].point.y - vertices[b.to].point.y || a.to - b.to
    );
    const unique = arcs.filter(
      (arc, index) => index === 0 || arc.to !== arcs[index - 1].to || arc.orientation !== arcs[index - 1].orientation || arc.kind !== arcs[index - 1].kind
    );
    adjacencyEntries += unique.length;
    immutableAdjacency.set(vertex.id, Object.freeze(unique.map((arc) => Object.freeze(arc))));
  }
  enforceCap(
    adjacencyEntries,
    // Each vertex has at most one immediate visible neighbor in each cardinal direction. The
    // override remains a test seam for exercising adjacency-cap fallback behavior.
    caps.maxAdjacencyEntries ?? vertexCap * MAX_VISIBILITY_ADJACENCY_PER_VERTEX,
    "adjacency_cap"
  );
  return {
    vertices: Object.freeze(vertices),
    adjacency: new ImmutableMap(immutableAdjacency),
    adjacencyEntries
  };
}
__name(buildVisibilityGraph, "buildVisibilityGraph");
function derivePortalRanges(ownerId, rawBounds, rawTitle) {
  const bounds = normalizeRect(rawBounds);
  const title = rawTitle ? normalizeRect(rawTitle) : void 0;
  const verticalLow = Math.max(
    bounds.top + ROUTE_CLEARANCE_PX,
    (title?.bottom ?? -Infinity) + ROUTE_CLEARANCE_PX
  );
  const verticalHigh = bounds.bottom - ROUTE_CLEARANCE_PX;
  const horizontalLow = bounds.left + ROUTE_CLEARANCE_PX;
  const horizontalHigh = bounds.right - ROUTE_CLEARANCE_PX;
  const ranges = [];
  if (verticalLow <= verticalHigh) {
    ranges.push(
      { ownerId, side: "left", low: verticalLow, high: verticalHigh },
      { ownerId, side: "right", low: verticalLow, high: verticalHigh }
    );
  }
  if (horizontalLow <= horizontalHigh) {
    ranges.push({ ownerId, side: "bottom", low: horizontalLow, high: horizontalHigh });
    if (!title || title.bottom + ROUTE_CLEARANCE_PX <= bounds.top) {
      ranges.push({ ownerId, side: "top", low: horizontalLow, high: horizontalHigh });
    }
  }
  return ranges;
}
__name(derivePortalRanges, "derivePortalRanges");
function buildPairedPortal(ownerId, bounds, title, side, tangentialCoordinate2) {
  const range = derivePortalRanges(ownerId, bounds, title).find((entry) => entry.side === side);
  if (!range || tangentialCoordinate2 < range.low || tangentialCoordinate2 > range.high) {
    throw new Error(`Illegal ${side} portal for "${ownerId}" at ${tangentialCoordinate2}`);
  }
  const boundary = side === "left" ? bounds.left : side === "right" ? bounds.right : side === "top" ? bounds.top : bounds.bottom;
  const inward = side === "left" || side === "top" ? boundary + ROUTE_CLEARANCE_PX : boundary - ROUTE_CLEARANCE_PX;
  const outward = side === "left" || side === "top" ? boundary - ROUTE_CLEARANCE_PX : boundary + ROUTE_CLEARANCE_PX;
  const interior = side === "left" || side === "right" ? { x: inward, y: tangentialCoordinate2 } : { x: tangentialCoordinate2, y: inward };
  const exterior = side === "left" || side === "right" ? { x: outward, y: tangentialCoordinate2 } : { x: tangentialCoordinate2, y: outward };
  return {
    ownerId,
    side,
    tangentialCoordinate: tangentialCoordinate2,
    interior,
    exterior,
    transition: {
      from: interior,
      to: exterior,
      orientation: side === "left" || side === "right" ? "H" : "V",
      length: ROUTE_CLEARANCE_PX * 2,
      kind: "portal"
    }
  };
}
__name(buildPairedPortal, "buildPairedPortal");
function buildContainerRoutingTopology(input, options = {}) {
  const bounds = normalizeRect(input.bounds);
  const inflated = [...input.obstacles, ...input.titleExclusions ?? []].map((obstacle) => inflateAndClip(obstacle, bounds)).filter((obstacle) => Boolean(obstacle));
  const obstacles = unionObstacles(inflated);
  const portalRanges = [...input.portalRanges ?? []].sort(
    (a, b) => topologySideOrdinal(a.side) - topologySideOrdinal(b.side) || a.low - b.low || a.high - b.high || compareCodeUnits(a.ownerId, b.ownerId)
  );
  const seeds = canonicalRecords([
    ...cornerRecords(bounds, input.containerId),
    ...obstacles.flatMap((obstacle) => cornerRecords(obstacle, obstacle.id)),
    ...portalRanges.flatMap((range) => portalRecords(range, bounds))
  ]);
  const intervalBudget = {
    intervalCount: 0,
    maxEstimatedBytes: options.caps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES
  };
  enforceCap(
    estimatedTopologyBytes(0, 0, obstacles.length, 0),
    intervalBudget.maxEstimatedBytes,
    "estimated_memory_cap"
  );
  const horizontalIntervals = createIntervalIndex(obstacles, "H", intervalBudget);
  const verticalIntervals = createIntervalIndex(obstacles, "V", intervalBudget);
  const projections = [];
  const sides = ["left", "right", "top", "bottom"];
  for (const seed of seeds) {
    for (const side of sides) {
      const hit = rayHit(seed.point, side, bounds, horizontalIntervals, verticalIntervals);
      if (hit.x !== seed.point.x || hit.y !== seed.point.y) {
        projections.push({ point: hit, kind: "projection", side });
      }
    }
  }
  const { vertices, adjacency, adjacencyEntries } = buildVisibilityGraph(
    [...seeds, ...projections],
    horizontalIntervals,
    verticalIntervals,
    options.caps ?? {}
  );
  const estimatedBytes = estimatedTopologyBytes(
    vertices.length,
    adjacencyEntries,
    obstacles.length,
    horizontalIntervals.intervalCount + verticalIntervals.intervalCount
  );
  enforceCap(
    estimatedBytes,
    options.caps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES,
    "estimated_memory_cap"
  );
  if (options.metrics) {
    options.metrics.containersBuilt++;
    options.metrics.baseTopologyBuilds++;
    options.metrics.baseVertices += vertices.length;
    options.metrics.baseAdjacencyEntries += adjacencyEntries;
    options.metrics.buildSweepEvents += seeds.length * 4 + obstacles.length * 4;
    options.metrics.estimatedBytes += estimatedBytes;
  }
  return Object.freeze({
    containerId: input.containerId,
    bounds: Object.freeze(bounds),
    obstacles: Object.freeze(obstacles.map((obstacle) => Object.freeze(obstacle))),
    vertices: Object.freeze(vertices),
    pointVertexIds: new ImmutableMap(
      new Map(vertices.map(({ id, point }) => [routingPointKey(point), id]))
    ),
    horizontalVertexLines: indexVertexLines(vertices, "H"),
    verticalVertexLines: indexVertexLines(vertices, "V"),
    adjacency,
    adjacencyByVertex: Object.freeze(vertices.map(({ id }) => adjacency.get(id) ?? [])),
    searchAdjacencyByVertex: Object.freeze(
      vertices.map(({ id }) => searchArcs(adjacency.get(id) ?? []))
    ),
    adjacencyEntries,
    horizontalIntervals,
    verticalIntervals,
    portalRanges: Object.freeze(portalRanges.map((range) => Object.freeze(range))),
    seedCount: seeds.length,
    estimatedBytes
  });
}
__name(buildContainerRoutingTopology, "buildContainerRoutingTopology");
function pointInsideObstacle(point, horizontalIntervals) {
  return horizontalIntervals.contains(point.y, point.x);
}
__name(pointInsideObstacle, "pointInsideObstacle");
function buildEndpointRoutingOverlay(base, source, target, metrics, reusableScratch, lanePoints = []) {
  const scratch = reusableScratch ?? new EndpointOverlayScratch(base);
  scratch.reset(base);
  const endpointRecords = [
    { point: source, kind: "endpoint", ownerId: "source" },
    { point: target, kind: "endpoint", ownerId: "target" },
    ...lanePoints.filter((point) => !pointInsideObstacle(point, base.horizontalIntervals)).map((point) => ({ point, kind: "lane" }))
  ];
  for (const point of [
    { x: source.x, y: target.y },
    { x: target.x, y: source.y }
  ]) {
    if (!pointInsideObstacle(point, base.horizontalIntervals)) {
      endpointRecords.push({ point, kind: "projection" });
    }
  }
  for (const record of endpointRecords.slice(0, 2)) {
    for (const side of ["left", "right", "top", "bottom"]) {
      const hit = rayHit(
        record.point,
        side,
        base.bounds,
        base.horizontalIntervals,
        base.verticalIntervals
      );
      if (hit.x !== record.point.x || hit.y !== record.point.y) {
        endpointRecords.push({ point: hit, kind: "projection", side });
      }
    }
  }
  const additions = canonicalRecords(endpointRecords).filter(({ point }) => !base.pointVertexIds.has(routingPointKey(point))).sort(vertexRecordOrder);
  enforceCap(additions.length, 32, "vertex_cap");
  scratch.addedVertices.push(
    ...additions.map(
      (record, index) => Object.freeze({
        id: base.vertices.length + index,
        ...record,
        point: Object.freeze({ ...record.point })
      })
    )
  );
  const vertices = overlayArray(base.vertices, scratch.addedVertices);
  const vertexAt = /* @__PURE__ */ __name((id) => id < base.vertices.length ? base.vertices[id] : scratch.addedVertices[id - base.vertices.length], "vertexAt");
  const adjacency = /* @__PURE__ */ new Map();
  const mutableArcs = /* @__PURE__ */ __name((id) => {
    let arcs = adjacency.get(id);
    if (!arcs) {
      arcs = [...base.adjacency.get(id) ?? []];
      adjacency.set(id, arcs);
    }
    return arcs;
  }, "mutableArcs");
  for (const vertex of scratch.addedVertices) {
    adjacency.set(vertex.id, []);
  }
  const addedIds = new Set(scratch.addedVertices.map(({ id }) => id));
  const addedArcKeys = /* @__PURE__ */ new Set();
  const connect = /* @__PURE__ */ __name((a, b, orientation) => {
    const length = Math.abs(a.point.x - b.point.x) + Math.abs(a.point.y - b.point.y);
    if (length === 0) {
      return;
    }
    const intervalStart = orientation === "H" ? Math.min(a.point.x, b.point.x) : Math.min(a.point.y, b.point.y);
    const intervalEnd = intervalStart + length;
    for (const [from, to] of [
      [a, b],
      [b, a]
    ]) {
      const key = `${from.id}:${to.id}:${orientation}:visibility`;
      if (addedArcKeys.has(key) || (base.adjacency.get(from.id) ?? []).some(
        (arc) => arc.to === to.id && arc.orientation === orientation && arc.kind === "visibility"
      )) {
        continue;
      }
      addedArcKeys.add(key);
      mutableArcs(from.id).push({
        from: from.id,
        to: to.id,
        orientation,
        length,
        kind: "visibility",
        intervalStart,
        intervalEnd
      });
    }
  }, "connect");
  for (const orientation of ["H", "V"]) {
    const baseLines = orientation === "H" ? base.horizontalVertexLines : base.verticalVertexLines;
    const affected = new Set(
      scratch.addedVertices.map(({ point }) => orientation === "H" ? point.y : point.x)
    );
    for (const fixed of affected) {
      const line = [
        ...baseLines.get(fixed) ?? [],
        ...scratch.addedVertices.filter(
          ({ point }) => (orientation === "H" ? point.y : point.x) === fixed
        )
      ];
      line.sort(
        (a, b) => orientation === "H" ? a.point.x - b.point.x || a.id - b.id : a.point.y - b.point.y || a.id - b.id
      );
      for (let index = 1; index < line.length; index++) {
        const a = line[index - 1];
        const b = line[index];
        if (!addedIds.has(a.id) && !addedIds.has(b.id)) {
          continue;
        }
        const start = orientation === "H" ? a.point.x : a.point.y;
        const end = orientation === "H" ? b.point.x : b.point.y;
        const intervalIndex = orientation === "H" ? base.horizontalIntervals : base.verticalIntervals;
        if (!intervalIndex.intersects(fixed, start, end)) {
          connect(a, b, orientation);
        }
      }
    }
  }
  for (const [id, arcs] of adjacency) {
    arcs.sort(
      (a, b) => compareCodeUnits(a.kind, b.kind) || compareCodeUnits(a.orientation, b.orientation) || vertexAt(a.to).point.x - vertexAt(b.to).point.x || vertexAt(a.to).point.y - vertexAt(b.to).point.y || a.to - b.to
    );
    const immutableArcs = Object.freeze(arcs.map((arc) => Object.freeze(arc)));
    scratch.setArcs(id, immutableArcs);
  }
  const adjacencyEntries = base.adjacencyEntries + addedArcKeys.size;
  enforceCap(adjacencyEntries, base.adjacencyEntries + 64, "adjacency_cap");
  const addedVertices = additions.length;
  const estimatedBytes = base.estimatedBytes + addedVertices * 64 + (adjacencyEntries - base.adjacencyEntries) * 56;
  if (metrics) {
    metrics.endpointOverlayBuilds++;
    metrics.endpointOverlayVertices += addedVertices;
    metrics.estimatedBytes = Math.max(metrics.estimatedBytes, estimatedBytes);
  }
  const vertexCount = base.vertices.length + scratch.addedVertices.length;
  const adjacencyByVertex = overrideArray(
    base.adjacencyByVertex,
    scratch.adjacencyOverrides,
    vertexCount
  );
  const searchAdjacencyByVertex = overrideArray(
    base.searchAdjacencyByVertex,
    scratch.searchAdjacencyOverrides,
    vertexCount
  );
  for (const vertex of scratch.addedVertices) {
    scratch.pointOverrides.set(routingPointKey(vertex.point), vertex.id);
  }
  return Object.freeze({
    ...base,
    vertices,
    pointVertexIds: new OverlayMap(base.pointVertexIds, scratch.pointOverrides),
    adjacency: new OverlayMap(base.adjacency, scratch.adjacencyOverrides),
    adjacencyByVertex,
    searchAdjacencyByVertex,
    adjacencyEntries,
    estimatedBytes,
    vertexCount,
    getVertex: vertexAt,
    getSearchArcs: /* @__PURE__ */ __name((id) => scratch.searchAdjacencyOverrides.get(id) ?? base.searchAdjacencyByVertex[id] ?? [], "getSearchArcs")
  });
}
__name(buildEndpointRoutingOverlay, "buildEndpointRoutingOverlay");

// src/rendering-util/layout-algorithms/grid/routerPlanning.ts
var MIN_PORT_SEPARATION_PX = 4;
var TERMINAL_APPROACH_PX = 20;
var LANE_SEPARATION_PX = 8;
function ownerGroupTitle(node) {
  return Boolean(node.groupTitleRect);
}
__name(ownerGroupTitle, "ownerGroupTitle");
function ownerSideKey(ownerId, side) {
  return JSON.stringify([ownerId, side]);
}
__name(ownerSideKey, "ownerSideKey");
function preferredSide(node, toward) {
  const rect = rectForNode(node);
  const dx = toward.x - rect.cx;
  const dy = toward.y - rect.cy;
  const avoidTop = node.isGroup && ownerGroupTitle(node);
  if (Math.abs(dx) >= Math.abs(dy)) {
    return dx >= 0 ? "right" : "left";
  }
  if (dy >= 0) {
    return "bottom";
  }
  if (avoidTop) {
    return dx >= 0 ? "right" : "left";
  }
  return "top";
}
__name(preferredSide, "preferredSide");
function containerChain(node, nodeById) {
  const chain = [];
  let currentParent = node.parentId ?? ROOT_CONTAINER_ID;
  const seen = /* @__PURE__ */ new Set();
  while (true) {
    chain.push(currentParent);
    if (currentParent === ROOT_CONTAINER_ID) {
      break;
    }
    if (seen.has(currentParent)) {
      break;
    }
    seen.add(currentParent);
    currentParent = nodeById.get(currentParent)?.parentId ?? ROOT_CONTAINER_ID;
  }
  return chain;
}
__name(containerChain, "containerChain");
function commonContainerId(source, target, nodeById) {
  if (source.isGroup && isAncestorGroup(source.id, target, nodeById)) {
    return source.parentId ?? ROOT_CONTAINER_ID;
  }
  if (target.isGroup && isAncestorGroup(target.id, source, nodeById)) {
    return target.parentId ?? ROOT_CONTAINER_ID;
  }
  const targetContainers = new Set(containerChain(target, nodeById));
  for (const containerId of containerChain(source, nodeById)) {
    if (targetContainers.has(containerId)) {
      return containerId;
    }
  }
  return ROOT_CONTAINER_ID;
}
__name(commonContainerId, "commonContainerId");
function oppositeCoordFor(rect, side) {
  return side === "left" || side === "right" ? rect.cy : rect.cx;
}
__name(oppositeCoordFor, "oppositeCoordFor");
function sideMidpoint(rect, side) {
  return side === "left" || side === "right" ? { x: side === "left" ? rect.left : rect.right, y: rect.cy } : { x: rect.cx, y: side === "top" ? rect.top : rect.bottom };
}
__name(sideMidpoint, "sideMidpoint");
function tangentialCoordinate(point, side) {
  return side === "left" || side === "right" ? point.y : point.x;
}
__name(tangentialCoordinate, "tangentialCoordinate");
function buildEndpointPlan(endpoint, other, lcaContainerId, nodeById, edgeId, role) {
  const chain = [];
  const endpointRect = rectForNode(endpoint);
  const otherRect = rectForNode(other);
  const otherCenter = { x: other.x ?? 0, y: other.y ?? 0 };
  let current = endpoint;
  for (; ; ) {
    const parentId = current.parentId ?? ROOT_CONTAINER_ID;
    const parent = nodeById.get(parentId);
    const currentCenter = { x: current.x ?? 0, y: current.y ?? 0 };
    const dx = otherCenter.x - currentCenter.x;
    const dy = otherCenter.y - currentCenter.y;
    const titleAvoidanceTie = dy < 0 && Math.abs(dx) <= PIXEL_EPSILON && Boolean((current.isGroup ? current.groupTitleRect : void 0) ?? parent?.groupTitleRect);
    const directSideCandidates = [];
    if (Math.abs(Math.abs(dx) - Math.abs(dy)) <= PIXEL_EPSILON && Math.abs(dx) > PIXEL_EPSILON) {
      directSideCandidates.push(dx >= 0 ? "right" : "left", dy >= 0 ? "bottom" : "top");
    }
    const topBlocked = Boolean(
      (current.isGroup ? current.groupTitleRect : void 0) ?? parent?.groupTitleRect
    );
    const ambiguousSides = (titleAvoidanceTie ? ["left", "right"] : directSideCandidates).filter((candidate) => candidate !== "top" || !topBlocked);
    let side = preferredSide(current, otherCenter);
    if (side === "top" && parent?.groupTitleRect) {
      side = dx >= 0 ? "right" : "left";
    }
    chain.push({
      ownerId: current.id,
      side,
      demandKey: JSON.stringify([edgeId, role, current.id, side]),
      oppositeCoord: oppositeCoordFor(otherRect, side),
      preferredCoord: oppositeCoordFor(endpointRect, side),
      compactPortal: current.id !== endpoint.id,
      ambiguousSides: ambiguousSides.length > 1 ? ambiguousSides : void 0,
      inner: chain.length ? { demandKey: chain[chain.length - 1].demandKey, side: chain[chain.length - 1].side } : void 0
    });
    if (current.isGroup && current.id === lcaContainerId && isAncestorGroup(current.id, other, nodeById)) {
      return { chain, finalKind: "boundary" };
    }
    if (parentId === lcaContainerId) {
      return { chain, finalKind: "item" };
    }
    if (!parent?.isGroup) {
      throw gridError("GRID_INVALID_CONTAINMENT", `Missing parent group "${parentId}"`, {
        traversedIds: chain.map((entry) => entry.ownerId)
      });
    }
    current = parent;
  }
}
__name(buildEndpointPlan, "buildEndpointPlan");
function buildPairLanes(edges) {
  const byPair = /* @__PURE__ */ new Map();
  for (const edge of edges) {
    if (!edge.start || !edge.end) {
      continue;
    }
    const pairKey = edge.start < edge.end ? `${edge.start}|${edge.end}` : `${edge.end}|${edge.start}`;
    if (!byPair.has(pairKey)) {
      byPair.set(pairKey, []);
    }
    byPair.get(pairKey).push(edge);
  }
  const out = /* @__PURE__ */ new Map();
  for (const [pairKey, entries] of byPair) {
    entries.sort(
      (a, b) => compareCodeUnits(`${a.start}|${a.end}`, `${b.start}|${b.end}`) || compareCodeUnits(a.id, b.id)
    );
    entries.forEach(
      (edge, index) => out.set(edge.id, {
        index,
        size: entries.length,
        offset: (index - (entries.length - 1) / 2) * LANE_SEPARATION_PX,
        pairKey
      })
    );
  }
  return out;
}
__name(buildPairLanes, "buildPairLanes");
function resolveAmbiguousEndpointSides(plans, result) {
  const reserved = /* @__PURE__ */ new Map();
  const reservationKey = /* @__PURE__ */ __name((ownerId, side) => ownerSideKey(ownerId, side), "reservationKey");
  for (const plan of plans) {
    for (const entry of [...plan.source.chain, ...plan.target.chain]) {
      if (!entry.ambiguousSides) {
        const key = reservationKey(entry.ownerId, entry.side);
        reserved.set(key, (reserved.get(key) ?? 0) + 1);
      }
    }
  }
  const resolveEndpoint = /* @__PURE__ */ __name((plan, endpoint, role) => {
    const ambiguous = endpoint.chain.filter(({ ambiguousSides }) => ambiguousSides);
    if (ambiguous.length === 0) {
      return;
    }
    const legalSides = ["right", "bottom", "left", "top"].filter(
      (side) => ambiguous.every((entry) => entry.ambiguousSides?.includes(side)) && ambiguous.every((entry) => {
        const owner = result.forest.nodeById.get(entry.ownerId);
        return owner !== void 0 && sideInterval(owner, side) !== void 0;
      })
    );
    const selected = legalSides.sort(
      (a, b) => ambiguous.reduce(
        (count, entry) => count + (reserved.get(reservationKey(entry.ownerId, a)) ?? 0),
        0
      ) - ambiguous.reduce(
        (count, entry) => count + (reserved.get(reservationKey(entry.ownerId, b)) ?? 0),
        0
      ) || Number(a !== ambiguous[0].side) - Number(b !== ambiguous[0].side)
    )[0];
    if (!selected) {
      return;
    }
    for (const entry of ambiguous) {
      entry.side = selected;
      const key = reservationKey(entry.ownerId, selected);
      reserved.set(key, (reserved.get(key) ?? 0) + 1);
      const owner = result.forest.nodeById.get(entry.ownerId);
      if (owner) {
        entry.preferredCoord = oppositeCoordFor(rectForNode(owner), selected);
      }
    }
    for (const [index, entry] of endpoint.chain.entries()) {
      entry.demandKey = JSON.stringify([plan.edge.id, role, entry.ownerId, entry.side]);
      entry.inner = index > 0 ? {
        demandKey: endpoint.chain[index - 1].demandKey,
        side: endpoint.chain[index - 1].side
      } : void 0;
    }
  }, "resolveEndpoint");
  const endpoints = plans.flatMap((plan) => [
    { plan, endpoint: plan.source, role: "source" },
    { plan, endpoint: plan.target, role: "target" }
  ]).sort(
    (a, b) => compareCodeUnits(
      `${a.plan.edge.start ?? ""}|${a.plan.edge.end ?? ""}|${a.plan.edge.id}|${a.role}`,
      `${b.plan.edge.start ?? ""}|${b.plan.edge.end ?? ""}|${b.plan.edge.id}|${b.role}`
    )
  );
  for (const { plan, endpoint, role } of endpoints) {
    resolveEndpoint(plan, endpoint, role);
  }
  for (const plan of plans) {
    const sourceFinal = plan.source.chain.at(-1);
    const targetFinal = plan.target.chain.at(-1);
    const sourceOwner = sourceFinal ? result.forest.nodeById.get(sourceFinal.ownerId) : void 0;
    const targetOwner = targetFinal ? result.forest.nodeById.get(targetFinal.ownerId) : void 0;
    if (!sourceFinal || !targetFinal || !sourceOwner || !targetOwner) {
      continue;
    }
    const sourcePoint = sideMidpoint(rectForNode(sourceOwner), sourceFinal.side);
    const targetPoint = sideMidpoint(rectForNode(targetOwner), targetFinal.side);
    for (const entry of plan.source.chain) {
      entry.oppositeCoord = tangentialCoordinate(targetPoint, entry.side);
    }
    for (const entry of plan.target.chain) {
      entry.oppositeCoord = tangentialCoordinate(sourcePoint, entry.side);
    }
  }
}
__name(resolveAmbiguousEndpointSides, "resolveAmbiguousEndpointSides");
function collectRoutePlans(layout, result) {
  const nodeById = result.forest.nodeById;
  const pairLanes = buildPairLanes(layout.edges);
  const plans = layout.edges.map((edge) => {
    const source = edge.start ? nodeById.get(edge.start) : void 0;
    const target = edge.end ? nodeById.get(edge.end) : void 0;
    if (!source || !target) {
      throw gridError("GRID_MISSING_ENDPOINT", `Missing endpoint for edge "${edge.id}"`, {
        edgeId: edge.id,
        start: edge.start,
        end: edge.end
      });
    }
    const lcaContainerId = commonContainerId(source, target, nodeById);
    const pairLane = pairLanes.get(edge.id) ?? {
      index: 0,
      size: 1,
      offset: 0,
      pairKey: endpointPairKey(edge)
    };
    return {
      edge,
      lcaContainerId,
      source: buildEndpointPlan(source, target, lcaContainerId, nodeById, edge.id, "source"),
      target: buildEndpointPlan(target, source, lcaContainerId, nodeById, edge.id, "target"),
      laneIndex: pairLane.index,
      laneOffset: pairLane.offset,
      bundleSize: pairLane.size,
      pairKey: pairLane.pairKey
    };
  });
  resolveAmbiguousEndpointSides(plans, result);
  return plans;
}
__name(collectRoutePlans, "collectRoutePlans");
function assignCompactPortalCoordinates(desired, low, high) {
  const coordinates = [];
  for (const [index, coordinate] of desired.entries()) {
    coordinates.push(
      index === 0 ? coordinate : Math.max(coordinate, coordinates[index - 1] + MIN_PORT_SEPARATION_PX)
    );
  }
  for (let index = coordinates.length - 1; index >= 0; index--) {
    coordinates[index] = Math.min(
      coordinates[index],
      index === coordinates.length - 1 ? high : coordinates[index + 1] - MIN_PORT_SEPARATION_PX
    );
  }
  const averageDesired = desired.reduce((sum, coordinate) => sum + coordinate, 0) / desired.length;
  const averageAssigned = coordinates.reduce((sum, coordinate) => sum + coordinate, 0) / coordinates.length;
  const minimumShift = low - coordinates[0];
  const maximumShift = high - coordinates[coordinates.length - 1];
  const shift = clamp(averageDesired - averageAssigned, minimumShift, maximumShift);
  return coordinates.map((coordinate) => coordinate + shift);
}
__name(assignCompactPortalCoordinates, "assignCompactPortalCoordinates");
function assignDemandCoordinates(plans, result, endpointIncidentCounts) {
  const nodeById = result.forest.nodeById;
  const planByEdgeId = new Map(plans.map((plan) => [plan.edge.id, plan]));
  const demandByKey = /* @__PURE__ */ new Map();
  for (const plan of plans) {
    if (plan.edge.start === plan.edge.end) {
      continue;
    }
    for (const entry of [...plan.source.chain, ...plan.target.chain]) {
      if (!demandByKey.has(entry.demandKey)) {
        demandByKey.set(entry.demandKey, {
          ownerId: entry.ownerId,
          side: entry.side,
          edgeId: plan.edge.id,
          demandKey: entry.demandKey,
          oppositeCoord: entry.oppositeCoord,
          preferredCoord: entry.preferredCoord,
          compactPortal: entry.compactPortal,
          inner: entry.inner
        });
      }
    }
  }
  const byOwnerSide = /* @__PURE__ */ new Map();
  for (const demand of demandByKey.values()) {
    const key = ownerSideKey(demand.ownerId, demand.side);
    const group = byOwnerSide.get(key) ?? {
      ownerId: demand.ownerId,
      side: demand.side,
      demands: []
    };
    group.demands.push(demand);
    byOwnerSide.set(key, group);
  }
  const depthOf = /* @__PURE__ */ __name((ownerId) => {
    const owner = nodeById.get(ownerId);
    return owner ? containerChain(owner, nodeById).length : 0;
  }, "depthOf");
  const orderedOwnerSides = [...byOwnerSide.values()].sort(
    (a, b) => Number(a.demands.every((d) => d.compactPortal)) - Number(b.demands.every((d) => d.compactPortal)) || depthOf(b.ownerId) - depthOf(a.ownerId)
  );
  const assigned = /* @__PURE__ */ new Map();
  for (const { ownerId, side, demands } of orderedOwnerSides) {
    const owner = nodeById.get(ownerId);
    if (!owner) {
      continue;
    }
    const rect = rectForNode(owner);
    let low = side === "left" || side === "right" ? rect.top + ROUTE_CLEARANCE_PX : rect.left + ROUTE_CLEARANCE_PX;
    const high = side === "left" || side === "right" ? rect.bottom - ROUTE_CLEARANCE_PX : rect.right - ROUTE_CLEARANCE_PX;
    if ((side === "left" || side === "right") && owner.groupTitleRect) {
      low = Math.max(low, owner.groupTitleRect.bottom + ROUTE_CLEARANCE_PX);
    }
    const span = Math.max(0, high - low);
    demands.sort(
      (a, b) => a.oppositeCoord - b.oppositeCoord || compareCodeUnits(a.edgeId, b.edgeId)
    );
    const demandPlans = demands.map((demand) => planByEdgeId.get(demand.edgeId));
    const pairKeys = new Set(demandPlans.map((plan) => plan?.pairKey));
    const compactHierarchyPortals = owner.isGroup && demands.every(({ compactPortal }) => compactPortal);
    if (!(compactHierarchyPortals && demands.length === 1) && pairKeys.size === 1 && demandPlans.every(
      (plan) => plan && plan.bundleSize === demands.length && endpointIncidentCounts.get(plan.edge.start) === plan.bundleSize && endpointIncidentCounts.get(plan.edge.end) === plan.bundleSize
    )) {
      const center = (low + high) / 2;
      const coordinates = demandPlans.map((plan) => center + plan.laneOffset);
      if (coordinates.every((coordinate) => coordinate >= low && coordinate <= high)) {
        demands.forEach((demand, index) => assigned.set(demand.demandKey, coordinates[index]));
        continue;
      }
    }
    if (compactHierarchyPortals) {
      const container = result.containers.get(owner.id);
      const corridorCoordinates = side === "left" || side === "right" ? container?.horizontalCorridors : container?.verticalCorridors;
      const innerCoordinate = /* @__PURE__ */ __name((demand) => {
        const inner = demand.inner ? demandByKey.get(demand.inner.demandKey) : void 0;
        const innerOwner = inner ? nodeById.get(inner.ownerId) : void 0;
        const coordinate = inner ? assigned.get(inner.demandKey) : void 0;
        if (!inner || !innerOwner || coordinate === void 0) {
          return demand.preferredCoord;
        }
        const point = sideMidpoint(rectForNode(innerOwner), inner.side);
        if (inner.side === "left" || inner.side === "right") {
          point.y = coordinate;
        } else {
          point.x = coordinate;
        }
        return tangentialCoordinate(point, side);
      }, "innerCoordinate");
      const preferredCoordinate = /* @__PURE__ */ __name((demand) => {
        const innerCoord = demand.inner ? assigned.get(demand.inner.demandKey) : void 0;
        const alignedWithInner = demand.inner !== void 0 && innerCoord !== void 0 && (demand.inner.side === "left" || demand.inner.side === "right") === (side === "left" || side === "right");
        const clamped = clamp(alignedWithInner ? innerCoord : demand.preferredCoord, low, high);
        const nearest = corridorCoordinates?.reduce(
          (best, coordinate) => Math.abs(coordinate - clamped) < Math.abs(best - clamped) ? coordinate : best,
          corridorCoordinates[0]
        );
        return nearest !== void 0 && Math.abs(nearest - clamped) <= PIXEL_EPSILON ? nearest : clamped;
      }, "preferredCoordinate");
      if (demands.length === 1) {
        assigned.set(demands[0].demandKey, preferredCoordinate(demands[0]));
        continue;
      }
      if (span >= MIN_PORT_SEPARATION_PX * (demands.length - 1)) {
        demands.sort(
          (a, b) => innerCoordinate(a) - innerCoordinate(b) || a.oppositeCoord - b.oppositeCoord || compareCodeUnits(a.edgeId, b.edgeId)
        );
        const desired = demands.map(preferredCoordinate);
        const coordinates = assignCompactPortalCoordinates(desired, low, high);
        demands.forEach((demand, index) => assigned.set(demand.demandKey, coordinates[index]));
        continue;
      }
    }
    if (demands.length === 1 || span <= 0) {
      assigned.set(demands[0].demandKey, (low + high) / 2);
      continue;
    }
    const step = span / (demands.length - 1);
    demands.forEach((demand, index) => {
      assigned.set(demand.demandKey, low + step * index);
    });
  }
  for (const plan of plans) {
    if (plan.bundleSize !== 1) {
      continue;
    }
    const sourceFinal = plan.source.chain.at(-1);
    const targetFinal = plan.target.chain.at(-1);
    if (!sourceFinal || !targetFinal) {
      continue;
    }
    const verticalSide = /* @__PURE__ */ __name((side) => side === "left" || side === "right", "verticalSide");
    if (verticalSide(sourceFinal.side) !== verticalSide(targetFinal.side)) {
      continue;
    }
    const sourceCoord = assigned.get(sourceFinal.demandKey);
    const targetCoord = assigned.get(targetFinal.demandKey);
    if (sourceCoord === void 0 || targetCoord === void 0 || Math.abs(sourceCoord - targetCoord) > PIXEL_EPSILON) {
      continue;
    }
    const entries = [...plan.source.chain, ...plan.target.chain];
    if (entries.some((entry) => verticalSide(entry.side) !== verticalSide(sourceFinal.side))) {
      continue;
    }
    const alignedCoord = [sourceCoord, targetCoord].find(
      (coordinate) => entries.every((entry) => {
        const owner = nodeById.get(entry.ownerId);
        const interval = owner ? sideInterval(owner, entry.side) : void 0;
        return interval !== void 0 && coordinate >= interval.low - PIXEL_EPSILON && coordinate <= interval.high + PIXEL_EPSILON;
      })
    );
    if (alignedCoord !== void 0) {
      entries.forEach((entry) => assigned.set(entry.demandKey, alignedCoord));
    }
  }
  return assigned;
}
__name(assignDemandCoordinates, "assignDemandCoordinates");
function sideOrder(side) {
  return side === "right" ? 0 : side === "bottom" ? 1 : side === "left" ? 2 : 3;
}
__name(sideOrder, "sideOrder");
function sideInterval(owner, side) {
  const rect = rectForNode(owner);
  if (side === "top" && owner.groupTitleRect) {
    return void 0;
  }
  let low = side === "left" || side === "right" ? rect.top + ROUTE_CLEARANCE_PX : rect.left + ROUTE_CLEARANCE_PX;
  const high = side === "left" || side === "right" ? rect.bottom - ROUTE_CLEARANCE_PX : rect.right - ROUTE_CLEARANCE_PX;
  if ((side === "left" || side === "right") && owner.groupTitleRect) {
    low = Math.max(low, owner.groupTitleRect.bottom + ROUTE_CLEARANCE_PX);
  }
  return low <= high ? { low, high } : void 0;
}
__name(sideInterval, "sideInterval");
function endpointPairKey(edge) {
  const start = edge.start ?? "";
  const end = edge.end ?? "";
  return start < end ? `${start}|${end}` : `${end}|${start}`;
}
__name(endpointPairKey, "endpointPairKey");
function compareEndpointDemands(a, b, side) {
  const aRect = rectForNode(a.opposite);
  const bRect = rectForNode(b.opposite);
  const aCoord = side === "left" || side === "right" ? aRect.cy : aRect.cx;
  const bCoord = side === "left" || side === "right" ? bRect.cy : bRect.cx;
  return aCoord - bCoord || compareCodeUnits(endpointPairKey(a.plan.edge), endpointPairKey(b.plan.edge)) || compareCodeUnits(
    `${a.plan.edge.start}|${a.plan.edge.end}`,
    `${b.plan.edge.start}|${b.plan.edge.end}`
  ) || compareCodeUnits(a.plan.edge.id, b.plan.edge.id) || compareCodeUnits(a.role, b.role);
}
__name(compareEndpointDemands, "compareEndpointDemands");
function endpointDemandKey(demand) {
  return `${demand.plan.edge.id}:${demand.role}`;
}
__name(endpointDemandKey, "endpointDemandKey");
function compareEndpointDemandIdentity(a, b) {
  return compareCodeUnits(endpointPairKey(a.plan.edge), endpointPairKey(b.plan.edge)) || compareCodeUnits(
    `${a.plan.edge.start}|${a.plan.edge.end}`,
    `${b.plan.edge.start}|${b.plan.edge.end}`
  ) || compareCodeUnits(a.plan.edge.id, b.plan.edge.id) || compareCodeUnits(a.role, b.role);
}
__name(compareEndpointDemandIdentity, "compareEndpointDemandIdentity");
function preferredEndpointCoordinates(owner, side, demands) {
  const interval = sideInterval(owner, side);
  if (!interval || demands.length === 0) {
    return /* @__PURE__ */ new Map();
  }
  const sorted = [...demands].sort((a, b) => compareEndpointDemands(a, b, side));
  if (sorted.length === 1) {
    const rect = rectForNode(owner);
    const center = side === "left" || side === "right" ? rect.cy : rect.cx;
    return /* @__PURE__ */ new Map([[sorted[0], clamp(center, interval.low, interval.high)]]);
  }
  if ((interval.high - interval.low) / (sorted.length - 1) < MIN_PORT_SEPARATION_PX) {
    return new Map(
      sorted.map((demand, index) => [
        demand,
        interval.low + index * (interval.high - interval.low) / (sorted.length - 1)
      ])
    );
  }
  const desired = sorted.map(({ opposite }) => {
    const rect = rectForNode(opposite);
    const coordinate = side === "left" || side === "right" ? rect.cy : rect.cx;
    return clamp(coordinate, interval.low, interval.high);
  });
  const coordinates = assignCompactPortalCoordinates(desired, interval.low, interval.high);
  return new Map(sorted.map((demand, index) => [demand, coordinates[index]]));
}
__name(preferredEndpointCoordinates, "preferredEndpointCoordinates");
function endpointSideCapacity(owner, side) {
  const interval = sideInterval(owner, side);
  if (!interval) {
    return 0;
  }
  return 1 + Math.floor((interval.high - interval.low) / MIN_PORT_SEPARATION_PX);
}
__name(endpointSideCapacity, "endpointSideCapacity");
function endpointSidePreferences(owner, demand) {
  const oppositeRect = rectForNode(demand.opposite);
  const preferred = preferredSide(owner, { x: oppositeRect.cx, y: oppositeRect.cy });
  return ["right", "bottom", "left", "top"].filter((side) => endpointSideCapacity(owner, side) > 0).sort((a, b) => {
    if (a === preferred) {
      return -1;
    }
    if (b === preferred) {
      return 1;
    }
    const ownerRect = rectForNode(owner);
    const aPoint = sideMidpoint(ownerRect, a);
    const bPoint = sideMidpoint(ownerRect, b);
    const aDistance = Math.abs(aPoint.x - oppositeRect.cx) + Math.abs(aPoint.y - oppositeRect.cy);
    const bDistance = Math.abs(bPoint.x - oppositeRect.cx) + Math.abs(bPoint.y - oppositeRect.cy);
    return aDistance - bDistance || sideOrder(a) - sideOrder(b);
  });
}
__name(endpointSidePreferences, "endpointSidePreferences");
function isAxisAlignedDemand(owner, demand) {
  const ownerRect = rectForNode(owner);
  const oppositeRect = rectForNode(demand.opposite);
  return Math.abs(ownerRect.cx - oppositeRect.cx) <= PIXEL_EPSILON || Math.abs(ownerRect.cy - oppositeRect.cy) <= PIXEL_EPSILON;
}
__name(isAxisAlignedDemand, "isAxisAlignedDemand");
function placePortsBesideFixed(owner, side, fixed, movable) {
  const interval = sideInterval(owner, side);
  if (!interval) {
    return void 0;
  }
  const placed = [...fixed];
  const placements = /* @__PURE__ */ new Map();
  for (const demand of movable) {
    const opposite = rectForNode(demand.opposite);
    const desired = clamp(
      side === "left" || side === "right" ? opposite.cy : opposite.cx,
      interval.low,
      interval.high
    );
    const candidates = [
      desired,
      interval.low,
      interval.high,
      ...placed.flatMap((coordinate) => [
        coordinate - EDGE_CLEARANCE_PX,
        coordinate + EDGE_CLEARANCE_PX
      ])
    ].filter(
      (coordinate) => coordinate >= interval.low - PIXEL_EPSILON && coordinate <= interval.high + PIXEL_EPSILON && placed.every((other) => Math.abs(coordinate - other) >= EDGE_CLEARANCE_PX - PIXEL_EPSILON)
    ).sort((a, b) => Math.abs(a - desired) - Math.abs(b - desired) || a - b);
    if (candidates.length === 0) {
      return void 0;
    }
    placements.set(demand, candidates[0]);
    placed.push(candidates[0]);
  }
  return placements;
}
__name(placePortsBesideFixed, "placePortsBesideFixed");
function allocateEndpointSlots(owner, demands) {
  const assignedBySide = /* @__PURE__ */ new Map();
  const capacities = new Map(
    ["right", "bottom", "left", "top"].map((side) => [
      side,
      endpointSideCapacity(owner, side)
    ])
  );
  const orderedDemands = [...demands].sort(compareEndpointDemandIdentity);
  const alignedDemands = orderedDemands.filter((demand) => isAxisAlignedDemand(owner, demand));
  const unalignedDemands = orderedDemands.filter((demand) => !isAxisAlignedDemand(owner, demand));
  const reservedSides = /* @__PURE__ */ new Set();
  const alignedCoordinates = /* @__PURE__ */ new Map();
  const sharedPlacements = /* @__PURE__ */ new Map();
  const hasCapacity = /* @__PURE__ */ __name((candidate) => (assignedBySide.get(candidate)?.length ?? 0) < (capacities.get(candidate) ?? 0), "hasCapacity");
  const record = /* @__PURE__ */ __name((demand, side) => {
    const assigned = assignedBySide.get(side) ?? [];
    assigned.push(demand);
    assignedBySide.set(side, assigned);
  }, "record");
  const assignAligned = /* @__PURE__ */ __name((demand) => {
    const side = endpointSidePreferences(owner, demand).find(hasCapacity);
    if (side) {
      record(demand, side);
      reservedSides.add(side);
    }
  }, "assignAligned");
  const tryShareReservedSide = /* @__PURE__ */ __name((demand, side) => {
    const shared = sharedPlacements.get(side) ?? /* @__PURE__ */ new Map();
    const placements = placePortsBesideFixed(
      owner,
      side,
      [...alignedCoordinates.get(side) ?? [], ...shared.values()],
      [demand]
    );
    if (!placements) {
      return false;
    }
    shared.set(demand, placements.get(demand));
    sharedPlacements.set(side, shared);
    record(demand, side);
    return true;
  }, "tryShareReservedSide");
  const assignUnaligned = /* @__PURE__ */ __name((demand) => {
    const preferences = endpointSidePreferences(owner, demand).filter(hasCapacity);
    const unreserved = preferences.find((candidate) => !reservedSides.has(candidate));
    const sharable = preferences.find(
      (candidate) => (unreserved === void 0 || preferences.indexOf(candidate) < preferences.indexOf(unreserved)) && reservedSides.has(candidate) && tryShareReservedSide(demand, candidate)
    );
    if (sharable) {
      return;
    }
    const side = unreserved ?? preferences[0];
    if (side) {
      record(demand, side);
    }
  }, "assignUnaligned");
  for (const demand of alignedDemands) {
    assignAligned(demand);
  }
  for (const [side, assigned] of assignedBySide) {
    alignedCoordinates.set(side, [...preferredEndpointCoordinates(owner, side, assigned).values()]);
  }
  for (const demand of unalignedDemands) {
    assignUnaligned(demand);
  }
  const assignments = /* @__PURE__ */ new Map();
  for (const [side, assigned] of assignedBySide) {
    const interval = sideInterval(owner, side);
    if (!interval) {
      continue;
    }
    const shared = sharedPlacements.get(side);
    const fixedDemands = shared ? assigned.filter((demand) => !shared.has(demand)) : assigned;
    const preferredCoordinates = new Map([
      ...preferredEndpointCoordinates(owner, side, fixedDemands),
      ...shared ?? []
    ]);
    const sorted = [...assigned].sort((a, b) => compareEndpointDemands(a, b, side));
    for (const [index, demand] of sorted.entries()) {
      const coordinate = preferredCoordinates.get(demand) ?? (sorted.length === 1 ? (interval.low + interval.high) / 2 : interval.low + index * (interval.high - interval.low) / (sorted.length - 1));
      assignments.set(endpointDemandKey(demand), { side, coordinate });
    }
  }
  return assignments;
}
__name(allocateEndpointSlots, "allocateEndpointSlots");
function endpointCandidates(plan, role, demandsByOwner, assignmentsByOwner, coordinatedOwnerIds, result) {
  const ownerId = role === "source" ? plan.edge.start : plan.edge.end;
  const oppositeId = role === "source" ? plan.edge.end : plan.edge.start;
  const owner = result.forest.nodeById.get(ownerId);
  const opposite = result.forest.nodeById.get(oppositeId);
  if (!owner || !opposite) {
    throw gridError("GRID_MISSING_ENDPOINT", `Missing endpoint for edge "${plan.edge.id}"`);
  }
  const oppositeRect = rectForNode(opposite);
  const candidates = [];
  const candidateKeys = /* @__PURE__ */ new Set();
  const assignment = assignmentsByOwner.get(ownerId)?.get(`${plan.edge.id}:${role}`);
  const trackAssignedSide = coordinatedOwnerIds.has(ownerId) && assignment !== void 0;
  const addCandidate = /* @__PURE__ */ __name((side, coordinate, rank) => {
    const interval = sideInterval(owner, side);
    if (!interval || coordinate < interval.low || coordinate > interval.high) {
      return;
    }
    const rect = rectForNode(owner);
    const port = side === "left" || side === "right" ? { x: side === "left" ? rect.left : rect.right, y: coordinate } : { x: coordinate, y: side === "top" ? rect.top : rect.bottom };
    const key = `${side}:${routingPointKey(port)}`;
    if (candidateKeys.has(key)) {
      return;
    }
    candidateKeys.add(key);
    candidates.push({
      ownerId,
      side,
      port,
      connect: {
        x: port.x + (side === "left" ? -TERMINAL_APPROACH_PX : side === "right" ? TERMINAL_APPROACH_PX : 0),
        y: port.y + (side === "top" ? -TERMINAL_APPROACH_PX : side === "bottom" ? TERMINAL_APPROACH_PX : 0)
      },
      rank,
      onAssignedSide: trackAssignedSide ? side === assignment.side : void 0
    });
  }, "addCandidate");
  if (assignment && plan.bundleSize === 1) {
    addCandidate(assignment.side, assignment.coordinate, -2);
  }
  if (plan.bundleSize > 1) {
    const side = preferredSide(owner, { x: oppositeRect.cx, y: oppositeRect.cy });
    const ownerRect = rectForNode(owner);
    const center = side === "left" || side === "right" ? ownerRect.cy : ownerRect.cx;
    addCandidate(side, center + plan.laneOffset, -1);
  }
  const ownerDemands = [...demandsByOwner.get(ownerId) ?? []];
  for (const side of ["right", "bottom", "left", "top"]) {
    const interval = sideInterval(owner, side);
    if (!interval) {
      continue;
    }
    const coordinates = preferredEndpointCoordinates(owner, side, ownerDemands);
    const demand = ownerDemands.find((entry) => entry.plan === plan && entry.role === role);
    const coordinate = demand ? coordinates.get(demand) : void 0;
    if (coordinate === void 0) {
      continue;
    }
    const rect = rectForNode(owner);
    const port = side === "left" || side === "right" ? { x: side === "left" ? rect.left : rect.right, y: coordinate } : { x: coordinate, y: side === "top" ? rect.top : rect.bottom };
    const distance = Math.abs(port.x - oppositeRect.cx) + Math.abs(port.y - oppositeRect.cy);
    addCandidate(side, coordinate, distance);
  }
  candidates.sort((a, b) => a.rank - b.rank || sideOrder(a.side) - sideOrder(b.side));
  candidates.forEach((candidate, index) => {
    candidate.rank = index;
  });
  return candidates;
}
__name(endpointCandidates, "endpointCandidates");
function prepareEdgeRoutes(layout, result) {
  const plans = collectRoutePlans(layout, result);
  const pairCounts = /* @__PURE__ */ new Map();
  const endpointIncidentCounts = /* @__PURE__ */ new Map();
  for (const plan of plans) {
    const key = endpointPairKey(plan.edge);
    pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1);
    if (plan.edge.start) {
      endpointIncidentCounts.set(
        plan.edge.start,
        (endpointIncidentCounts.get(plan.edge.start) ?? 0) + 1
      );
    }
    if (plan.edge.end && plan.edge.end !== plan.edge.start) {
      endpointIncidentCounts.set(
        plan.edge.end,
        (endpointIncidentCounts.get(plan.edge.end) ?? 0) + 1
      );
    }
  }
  const eligiblePlans = plans.filter(
    (plan) => plan.edge.start !== plan.edge.end && plan.source.chain.length === 1 && plan.target.chain.length === 1 && plan.source.finalKind === "item" && plan.target.finalKind === "item"
  );
  const endpointDemandsByOwner = /* @__PURE__ */ new Map();
  for (const plan of eligiblePlans) {
    const source = result.forest.nodeById.get(plan.edge.start);
    const target = result.forest.nodeById.get(plan.edge.end);
    if (!source || !target) {
      continue;
    }
    const sourceDemands = endpointDemandsByOwner.get(source.id) ?? [];
    sourceDemands.push({ plan, role: "source", opposite: target });
    endpointDemandsByOwner.set(source.id, sourceDemands);
    const targetDemands = endpointDemandsByOwner.get(target.id) ?? [];
    targetDemands.push({ plan, role: "target", opposite: source });
    endpointDemandsByOwner.set(target.id, targetDemands);
  }
  const endpointAssignmentsByOwner = new Map(
    [...endpointDemandsByOwner].map(([ownerId, demands]) => {
      const owner = result.forest.nodeById.get(ownerId);
      return [ownerId, owner ? allocateEndpointSlots(owner, demands) : /* @__PURE__ */ new Map()];
    })
  );
  const coordinatedEndpointIds = /* @__PURE__ */ new Set();
  const coordinatedOwnerIds = /* @__PURE__ */ new Set();
  for (const [ownerId, demands] of endpointDemandsByOwner) {
    const owner = result.forest.nodeById.get(ownerId);
    if (!owner) {
      continue;
    }
    const hasAligned = demands.some((demand) => isAxisAlignedDemand(owner, demand));
    const hasUnaligned = demands.some((demand) => !isAxisAlignedDemand(owner, demand));
    if (hasAligned && hasUnaligned) {
      coordinatedOwnerIds.add(ownerId);
      for (const demand of demands) {
        if (!isAxisAlignedDemand(owner, demand)) {
          coordinatedEndpointIds.add(demand.plan.edge.id);
        }
      }
    }
  }
  const endpointCandidatesByEdge = new Map(
    eligiblePlans.map((plan) => [
      plan.edge.id,
      {
        sources: endpointCandidates(
          plan,
          "source",
          endpointDemandsByOwner,
          endpointAssignmentsByOwner,
          coordinatedOwnerIds,
          result
        ),
        targets: endpointCandidates(
          plan,
          "target",
          endpointDemandsByOwner,
          endpointAssignmentsByOwner,
          coordinatedOwnerIds,
          result
        )
      }
    ])
  );
  const endpointCandidateProducts = new Map(
    [...endpointCandidatesByEdge].map(([edgeId, candidates]) => [
      edgeId,
      candidates.sources.length * candidates.targets.length
    ])
  );
  const routeClass = /* @__PURE__ */ __name((plan) => {
    const source = result.forest.nodeById.get(plan.edge.start);
    const target = result.forest.nodeById.get(plan.edge.end);
    if (plan.edge.start === plan.edge.end) {
      return 0;
    }
    if (source?.isGroup && target && isAncestorGroup(source.id, target, result.forest.nodeById) || target?.isGroup && source && isAncestorGroup(target.id, source, result.forest.nodeById)) {
      return 1;
    }
    if ((source?.parentId ?? ROOT_CONTAINER_ID) !== (target?.parentId ?? ROOT_CONTAINER_ID)) {
      return 2;
    }
    return pairCounts.get(endpointPairKey(plan.edge)) > 1 ? 3 : 4;
  }, "routeClass");
  const orderedPlans = [...plans].sort((a, b) => {
    const aUnordered = endpointPairKey(a.edge);
    const bUnordered = endpointPairKey(b.edge);
    const aDirected = `${a.edge.start ?? ""}|${a.edge.end ?? ""}`;
    const bDirected = `${b.edge.start ?? ""}|${b.edge.end ?? ""}`;
    const aBoundaryCount = a.source.chain.length + a.target.chain.length - 2;
    const bBoundaryCount = b.source.chain.length + b.target.chain.length - 2;
    return routeClass(a) - routeClass(b) || bBoundaryCount - aBoundaryCount || (endpointCandidateProducts.get(a.edge.id) ?? 0) - (endpointCandidateProducts.get(b.edge.id) ?? 0) || compareCodeUnits(aUnordered, bUnordered) || compareCodeUnits(aDirected, bDirected) || compareCodeUnits(a.edge.id, b.edge.id);
  });
  return {
    plans,
    eligiblePlans,
    eligibleIds: new Set(eligiblePlans.map(({ edge }) => edge.id)),
    orderedPlans,
    demandCoords: assignDemandCoordinates(orderedPlans, result, endpointIncidentCounts),
    endpointCandidatesByEdge,
    endpointIncidentCounts,
    coordinatedEndpointIds
  };
}
__name(prepareEdgeRoutes, "prepareEdgeRoutes");

// src/rendering-util/layout-algorithms/grid/routerConstraint.ts
function isPairSeparationError(error) {
  if (!(error instanceof Error) || !("details" in error)) {
    return false;
  }
  const details = error.details;
  return typeof details === "object" && details !== null && "reason" in details && details.reason === "pair-separation";
}
__name(isPairSeparationError, "isPairSeparationError");
function routerRect(node) {
  const rect = rectForNode(node);
  return { left: rect.left, right: rect.right, top: rect.top, bottom: rect.bottom };
}
__name(routerRect, "routerRect");
function canonicalizeOrthogonalPolyline(points) {
  if (points.length < 2 || points.some(({ x, y }) => !Number.isFinite(x) || !Number.isFinite(y))) {
    return void 0;
  }
  const collapsed = [{ ...points[0] }];
  for (let index = 1; index < points.length; index++) {
    const point = points[index];
    const previous = collapsed.at(-1);
    const isNearDuplicate = Math.abs(point.x - previous.x) <= PIXEL_EPSILON && Math.abs(point.y - previous.y) <= PIXEL_EPSILON;
    if (!isNearDuplicate) {
      collapsed.push({ ...point });
      continue;
    }
    if (index !== points.length - 1) {
      continue;
    }
    while (collapsed.length > 1) {
      const beforePrevious = collapsed.at(-2);
      if (Math.abs(point.x - beforePrevious.x) > PIXEL_EPSILON || Math.abs(point.y - beforePrevious.y) > PIXEL_EPSILON) {
        break;
      }
      collapsed.pop();
    }
    if (collapsed.length === 1) {
      return void 0;
    }
    collapsed[collapsed.length - 1] = { ...point };
  }
  if (collapsed.length < 2) {
    return void 0;
  }
  const orientations = [];
  for (let index = 0; index < collapsed.length - 1; index++) {
    const a = collapsed[index];
    const b = collapsed[index + 1];
    const dx = Math.abs(b.x - a.x);
    const dy = Math.abs(b.y - a.y);
    if (dy <= PIXEL_EPSILON) {
      orientations.push("H");
    } else if (dx <= PIXEL_EPSILON) {
      orientations.push("V");
    } else {
      return void 0;
    }
  }
  const canonical = collapsed.map((point) => ({ ...point }));
  for (let start = 0; start < orientations.length; ) {
    const orientation = orientations[start];
    let end = start + 1;
    while (end < orientations.length && orientations[end] === orientation) {
      end++;
    }
    const axis = orientation === "H" ? "y" : "x";
    if (start === 0 && end === collapsed.length - 1 && collapsed[start][axis] !== collapsed[end][axis]) {
      return void 0;
    }
    const coordinate = end === collapsed.length - 1 ? collapsed[end][axis] : collapsed[start][axis];
    for (let pointIndex = start; pointIndex <= end; pointIndex++) {
      if (Math.abs(collapsed[pointIndex][axis] - coordinate) > PIXEL_EPSILON) {
        return void 0;
      }
      canonical[pointIndex][axis] = coordinate;
    }
    start = end;
  }
  return canonical;
}
__name(canonicalizeOrthogonalPolyline, "canonicalizeOrthogonalPolyline");
function segmentEntersRect(a, b, rect) {
  if (a.y === b.y) {
    return a.y > rect.top && a.y < rect.bottom && Math.max(a.x, b.x) > rect.left && Math.min(a.x, b.x) < rect.right;
  }
  if (a.x === b.x) {
    return a.x > rect.left && a.x < rect.right && Math.max(a.y, b.y) > rect.top && Math.min(a.y, b.y) < rect.bottom;
  }
  return true;
}
__name(segmentEntersRect, "segmentEntersRect");
function inflatedRect(node) {
  const rect = routerRect(node);
  return {
    left: rect.left - ROUTE_CLEARANCE_PX,
    right: rect.right + ROUTE_CLEARANCE_PX,
    top: rect.top - ROUTE_CLEARANCE_PX,
    bottom: rect.bottom + ROUTE_CLEARANCE_PX
  };
}
__name(inflatedRect, "inflatedRect");
function validateSameContainerRoute(points, source, target, containerId, result) {
  const canonical = canonicalizeOrthogonalPolyline(points);
  if (!canonical) {
    return false;
  }
  const normalized = normalizePolyline(canonical);
  if (normalized.points.length < 2) {
    return false;
  }
  if (normalized.segments.length > 1 && (Math.abs(normalized.segments[0].a.x - normalized.segments[0].b.x) + Math.abs(normalized.segments[0].a.y - normalized.segments[0].b.y) < TERMINAL_APPROACH_PX || Math.abs(normalized.segments.at(-1).a.x - normalized.segments.at(-1).b.x) + Math.abs(normalized.segments.at(-1).a.y - normalized.segments.at(-1).b.y) < TERMINAL_APPROACH_PX)) {
    return false;
  }
  const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(
    (node) => !isEdgeLabelNode(node)
  );
  for (const obstacle of children) {
    const rect = inflatedRect(obstacle);
    for (let index = 0; index < normalized.points.length - 1; index++) {
      const terminalObstacle = obstacle.id === source.id && index === 0 || obstacle.id === target.id && index === normalized.points.length - 2;
      if (terminalObstacle) {
        if (segmentEntersRect(
          normalized.points[index],
          normalized.points[index + 1],
          routerRect(obstacle)
        )) {
          return false;
        }
        continue;
      }
      if (segmentEntersRect(normalized.points[index], normalized.points[index + 1], rect)) {
        return false;
      }
    }
  }
  return true;
}
__name(validateSameContainerRoute, "validateSameContainerRoute");
function validateContainerSegment(points, startOwnerId, endOwnerId, containerId, result) {
  const canonical = canonicalizeOrthogonalPolyline(points);
  if (!canonical) {
    return false;
  }
  const normalized = normalizePolyline(canonical);
  if (normalized.points.length < 2) {
    return false;
  }
  const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(
    (node) => !isEdgeLabelNode(node)
  );
  for (const obstacle of children) {
    const rect = inflatedRect(obstacle);
    for (let index = 0; index < normalized.points.length - 1; index++) {
      const terminalObstacle = obstacle.id === startOwnerId && index === 0 || obstacle.id === endOwnerId && index === normalized.points.length - 2;
      if (terminalObstacle) {
        if (segmentEntersRect(
          normalized.points[index],
          normalized.points[index + 1],
          routerRect(obstacle)
        )) {
          return false;
        }
        continue;
      }
      if (segmentEntersRect(normalized.points[index], normalized.points[index + 1], rect)) {
        return false;
      }
    }
  }
  return true;
}
__name(validateContainerSegment, "validateContainerSegment");
function segmentSpan(segment) {
  return segment.orientation === "H" ? { low: Math.min(segment.a.x, segment.b.x), high: Math.max(segment.a.x, segment.b.x) } : { low: Math.min(segment.a.y, segment.b.y), high: Math.max(segment.a.y, segment.b.y) };
}
__name(segmentSpan, "segmentSpan");
function nonterminalSegments(points) {
  const segments = normalizePolyline([...points]).segments.filter((segment) => segment.orientation !== "Z").map((segment) => ({
    a: { ...segment.a },
    b: { ...segment.b },
    orientation: segment.orientation
  }));
  if (segments.length === 0) {
    return [];
  }
  if (segments.length === 1 && Math.abs(segments[0].a.x - segments[0].b.x) + Math.abs(segments[0].a.y - segments[0].b.y) <= TERMINAL_APPROACH_PX * 2) {
    return [];
  }
  const trim = /* @__PURE__ */ __name((segment, atStart) => {
    if (segment.orientation === "H") {
      const direction = Math.sign(segment.b.x - segment.a.x);
      if (atStart) {
        segment.a.x += direction * TERMINAL_APPROACH_PX;
      } else {
        segment.b.x -= direction * TERMINAL_APPROACH_PX;
      }
    } else {
      const direction = Math.sign(segment.b.y - segment.a.y);
      if (atStart) {
        segment.a.y += direction * TERMINAL_APPROACH_PX;
      } else {
        segment.b.y -= direction * TERMINAL_APPROACH_PX;
      }
    }
  }, "trim");
  trim(segments[0], true);
  trim(segments[segments.length - 1], false);
  return segments.filter(({ a, b }) => a.x !== b.x || a.y !== b.y);
}
__name(nonterminalSegments, "nonterminalSegments");
function pairSegmentsConflict(candidate, committed) {
  if (candidate.orientation !== committed.orientation) {
    return false;
  }
  const first = segmentSpan(candidate);
  const second = segmentSpan(committed);
  const overlap = Math.max(0, Math.min(first.high, second.high) - Math.max(first.low, second.low));
  if (overlap <= 0) {
    return false;
  }
  const separation = candidate.orientation === "H" ? Math.abs(candidate.a.y - committed.a.y) : Math.abs(candidate.a.x - committed.a.x);
  return separation === 0 && overlap >= LANE_SEPARATION_PX || separation > 0 && separation < LANE_SEPARATION_PX;
}
__name(pairSegmentsConflict, "pairSegmentsConflict");
function routeSatisfiesPairConstraints(points, pairRoutes) {
  const normalized = normalizePolyline([...points]).points;
  const candidatePorts = [normalized[0], normalized.at(-1)];
  const candidateSegments2 = nonterminalSegments(normalized);
  return pairRoutes.every((route) => {
    const committed = normalizePolyline([...route]).points;
    const committedPorts = [committed[0], committed.at(-1)];
    if (candidatePorts.some(
      (port) => committedPorts.some((other) => port.x === other.x && port.y === other.y)
    )) {
      return false;
    }
    return candidateSegments2.every(
      (candidate) => nonterminalSegments(committed).every(
        (committedSegment) => !pairSegmentsConflict(candidate, committedSegment)
      )
    );
  });
}
__name(routeSatisfiesPairConstraints, "routeSatisfiesPairConstraints");
function routeHasDistinctPairPorts(points, pairRoutes) {
  const normalized = normalizePolyline([...points]).points;
  const candidatePorts = [normalized[0], normalized.at(-1)];
  return pairRoutes.every((route) => {
    const committed = normalizePolyline([...route]).points;
    const committedPorts = [committed[0], committed.at(-1)];
    return !candidatePorts.some(
      (port) => committedPorts.some((other) => port.x === other.x && port.y === other.y)
    );
  });
}
__name(routeHasDistinctPairPorts, "routeHasDistinctPairPorts");
function pairArcAllowed(from, to, pairRoutes) {
  const orientation = from.y === to.y ? "H" : "V";
  const candidate = { a: from, b: to, orientation };
  return pairRoutes.every(
    (route) => nonterminalSegments(route).every(
      (committedSegment) => !pairSegmentsConflict(candidate, committedSegment)
    )
  );
}
__name(pairArcAllowed, "pairArcAllowed");
function endpointPairLowerBound(source, target) {
  const sourceOrientation = source.side === "left" || source.side === "right" ? "H" : "V";
  const targetOrientation = target.side === "left" || target.side === "right" ? "H" : "V";
  const dx = Math.abs(source.connect.x - target.connect.x);
  const dy = Math.abs(source.connect.y - target.connect.y);
  let bends;
  if (dx === 0 && dy === 0) {
    bends = Number(sourceOrientation !== targetOrientation);
  } else if (dx === 0 || dy === 0) {
    const pathOrientation = dx === 0 ? "V" : "H";
    bends = Number(sourceOrientation !== pathOrientation) + Number(targetOrientation !== pathOrientation);
  } else {
    bends = Math.min(
      Number(sourceOrientation !== "H") + 1 + Number(targetOrientation !== "V"),
      Number(sourceOrientation !== "V") + 1 + Number(targetOrientation !== "H")
    );
  }
  return [TERMINAL_APPROACH_PX * 2 + dx + dy, bends];
}
__name(endpointPairLowerBound, "endpointPairLowerBound");

// src/rendering-util/layout-algorithms/grid/routerOccupancy.ts
function segmentsTooClose(candidate, committed) {
  if (candidate.orientation !== committed.orientation) {
    return false;
  }
  const horizontal = candidate.orientation === "H";
  const lowOf = /* @__PURE__ */ __name((segment) => horizontal ? Math.min(segment.a.x, segment.b.x) : Math.min(segment.a.y, segment.b.y), "lowOf");
  const highOf = /* @__PURE__ */ __name((segment) => horizontal ? Math.max(segment.a.x, segment.b.x) : Math.max(segment.a.y, segment.b.y), "highOf");
  const overlap = Math.min(highOf(candidate), highOf(committed)) - Math.max(lowOf(candidate), lowOf(committed));
  const separation = horizontal ? Math.abs(candidate.a.y - committed.a.y) : Math.abs(candidate.a.x - committed.a.x);
  return overlap > 0 && separation < EDGE_CLEARANCE_PX;
}
__name(segmentsTooClose, "segmentsTooClose");
var RouteOccupancyIndex = class {
  constructor() {
    this.lines = {
      H: /* @__PURE__ */ new Map(),
      V: /* @__PURE__ */ new Map()
    };
    this.sortedCoordinates = {
      H: void 0,
      V: void 0
    };
    this.log = [];
  }
  static {
    __name(this, "RouteOccupancyIndex");
  }
  get size() {
    return this.log.length;
  }
  add(route, pairKey) {
    for (const segment of nonterminalSegments(route)) {
      const orientation = segment.orientation;
      const coordinate = orientation === "H" ? segment.a.y : segment.a.x;
      const bucket = this.lines[orientation].get(coordinate);
      if (bucket) {
        bucket.push({ segment, pairKey });
      } else {
        this.lines[orientation].set(coordinate, [{ segment, pairKey }]);
        this.sortedCoordinates[orientation] = void 0;
      }
      this.log.push({ orientation, coordinate });
    }
  }
  truncate(size) {
    while (this.log.length > size) {
      const { orientation, coordinate } = this.log.pop();
      this.lines[orientation].get(coordinate)?.pop();
    }
  }
  /** Reports whether a route shares a corridor with a committed route of another edge pair. */
  conflictsWithRoute(route, pairKey) {
    return nonterminalSegments(route).some((segment) => this.conflicts(segment, pairKey));
  }
  conflictsWithArc(from, to, pairKey) {
    const orientation = from.y === to.y ? "H" : "V";
    return this.conflicts({ a: from, b: to, orientation }, pairKey);
  }
  conflicts(candidate, pairKey) {
    const orientation = candidate.orientation;
    if (orientation !== "H" && orientation !== "V") {
      return false;
    }
    const coordinate = orientation === "H" ? candidate.a.y : candidate.a.x;
    const coordinates = this.coordinatesFor(orientation);
    let low = 0;
    let high = coordinates.length;
    while (low < high) {
      const middle = low + high >> 1;
      if (coordinates[middle] <= coordinate - EDGE_CLEARANCE_PX) {
        low = middle + 1;
      } else {
        high = middle;
      }
    }
    for (let index = low; index < coordinates.length; index++) {
      const key = coordinates[index];
      if (key >= coordinate + EDGE_CLEARANCE_PX) {
        break;
      }
      for (const occupied of this.lines[orientation].get(key)) {
        if (occupied.pairKey !== pairKey && segmentsTooClose(candidate, occupied.segment)) {
          return true;
        }
      }
    }
    return false;
  }
  coordinatesFor(orientation) {
    return this.sortedCoordinates[orientation] ??= [...this.lines[orientation].keys()].sort(
      (a, b) => a - b
    );
  }
};

// src/rendering-util/layout-algorithms/grid/routerCompatibility.ts
var ROOT_OUTER_MARGIN = 24;
var SELF_LOOP_PORT_GAP = 18;
var SELF_LOOP_APPROACH = 14;
var SELF_LOOP_CORNER_CLEARANCE = 4;
var SELF_LOOP_TRACK_GAP = 18;
var SELF_LOOP_PORT_OFFSET_STEP = 4;
var MAX_PLANS_FOR_OVERLAP_AVOIDANCE = 64;
var MAX_FAST_ROUTE_SEPARATION_STEPS = 4;
function separateRouteFromOccupied(route, occupancy, pairKey, isAcceptable) {
  if (!occupancy.conflictsWithRoute(route, pairKey)) {
    return [...route];
  }
  const points = normalizePolyline([...route]).points;
  for (let step = 1; step <= MAX_FAST_ROUTE_SEPARATION_STEPS; step++) {
    for (const sign of [1, -1]) {
      const delta = sign * step * LANE_SEPARATION_PX;
      for (let index = 1; index < points.length - 2; index++) {
        const vertical = points[index].x === points[index + 1].x;
        const shifted = points.map(
          (point, pointIndex) => pointIndex === index || pointIndex === index + 1 ? vertical ? { x: point.x + delta, y: point.y } : { x: point.x, y: point.y + delta } : point
        );
        if (!occupancy.conflictsWithRoute(shifted, pairKey) && isAcceptable(shifted)) {
          return shifted;
        }
      }
    }
  }
  return void 0;
}
__name(separateRouteFromOccupied, "separateRouteFromOccupied");
function terminalStubsAreLongEnough(points) {
  const stub = /* @__PURE__ */ __name((a, b) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y), "stub");
  return stub(points[0], points[1]) >= TERMINAL_APPROACH_PX && stub(points.at(-1), points.at(-2)) >= TERMINAL_APPROACH_PX;
}
__name(terminalStubsAreLongEnough, "terminalStubsAreLongEnough");
function boundedAlternativePortalCoordinates(selected, low, high, corridors, limit = 3) {
  const candidates = [
    ...corridors.filter((coordinate) => coordinate >= low && coordinate <= high).sort((a, b) => Math.abs(a - selected) - Math.abs(b - selected) || a - b),
    (low + high) / 2,
    low,
    high
  ];
  const seen = /* @__PURE__ */ new Set([selected]);
  const alternatives = [];
  for (const coordinate of candidates) {
    if (seen.has(coordinate)) {
      continue;
    }
    seen.add(coordinate);
    alternatives.push(coordinate);
    if (alternatives.length === limit) {
      break;
    }
  }
  return alternatives;
}
__name(boundedAlternativePortalCoordinates, "boundedAlternativePortalCoordinates");
function equalPoint(a, b) {
  return Math.abs(a.x - b.x) <= 1e-6 && Math.abs(a.y - b.y) <= 1e-6;
}
__name(equalPoint, "equalPoint");
function areExactlyAxisAligned(a, b) {
  return a.x === b.x || a.y === b.y;
}
__name(areExactlyAxisAligned, "areExactlyAxisAligned");
function chooseIntermediateCoordinate(values, start, end, variant) {
  const sorted = [...values].sort(
    (a, b) => Math.abs(a - start) + Math.abs(a - end) - (Math.abs(b - start) + Math.abs(b - end)) || a - b
  );
  return sorted[Math.min(variant, Math.max(0, sorted.length - 1))] ?? (start + end) / 2;
}
__name(chooseIntermediateCoordinate, "chooseIntermediateCoordinate");
function dedupeConsecutive(points) {
  const out = [];
  for (const point of points) {
    if (out.length === 0 || !equalPoint(out[out.length - 1], point)) {
      out.push(point);
    }
  }
  return out;
}
__name(dedupeConsecutive, "dedupeConsecutive");
function routeWithinContainer(containerId, result, start, end, variant) {
  const container = result.containers.get(containerId);
  if (!container) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing container layout "${containerId}"`);
  }
  const points = [start.port, start.connect];
  if (start.orientation === "V" && end.orientation === "V") {
    if (!equalPoint(start.connect, end.connect) && Math.abs(start.connect.x - end.connect.x) > 1e-6) {
      const y = chooseIntermediateCoordinate(
        container.horizontalCorridors,
        start.connect.y,
        end.connect.y,
        variant
      );
      points.push({ x: start.connect.x, y }, { x: end.connect.x, y });
    } else if (!equalPoint(start.connect, end.connect) && Math.abs(start.connect.y - end.connect.y) > 1e-6 && variant > 0) {
      const alternateCorridors = container.verticalCorridors.filter(
        (value) => Math.abs(value - start.connect.x) > 1e-6
      );
      const x = chooseIntermediateCoordinate(
        alternateCorridors.length > 0 ? alternateCorridors : container.verticalCorridors,
        start.connect.x,
        end.connect.x,
        variant - 1
      );
      points.push({ x, y: start.connect.y }, { x, y: end.connect.y });
    }
  } else if (start.orientation === "H" && end.orientation === "H") {
    if (!equalPoint(start.connect, end.connect) && Math.abs(start.connect.y - end.connect.y) > 1e-6) {
      const x = chooseIntermediateCoordinate(
        container.verticalCorridors,
        start.connect.x,
        end.connect.x,
        variant
      );
      points.push({ x, y: start.connect.y }, { x, y: end.connect.y });
    }
  } else if (start.orientation === "V" && end.orientation === "H") {
    points.push({ x: start.connect.x, y: end.connect.y });
  } else {
    points.push({ x: end.connect.x, y: start.connect.y });
  }
  points.push(end.connect, end.port);
  return normalizePolyline(dedupeConsecutive(points)).points;
}
__name(routeWithinContainer, "routeWithinContainer");
function itemAttachment(ownerId, side, demandKey, containerId, result, demandCoords, coordinate) {
  const owner = result.forest.nodeById.get(ownerId);
  const item = result.itemMeta.get(ownerId);
  if (!owner || !item || item.containerId !== containerId) {
    throw gridError(
      "GRID_ROUTE_NOT_FOUND",
      `Missing item metadata for "${ownerId}" in "${containerId}"`
    );
  }
  const rect = rectForNode(owner);
  const coord = coordinate ?? demandCoords.get(demandKey) ?? (side === "left" || side === "right" ? rect.cy : rect.cx);
  switch (side) {
    case "left":
      return {
        port: { x: rect.left, y: coord },
        connect: { x: item.leftCorridorX, y: coord },
        orientation: "V",
        side
      };
    case "right":
      return {
        port: { x: rect.right, y: coord },
        connect: { x: item.rightCorridorX, y: coord },
        orientation: "V",
        side
      };
    case "top":
      return {
        port: { x: coord, y: rect.top },
        connect: { x: coord, y: item.topCorridorY },
        orientation: "H",
        side
      };
    case "bottom":
      return {
        port: { x: coord, y: rect.bottom },
        connect: { x: coord, y: item.bottomCorridorY },
        orientation: "H",
        side
      };
  }
}
__name(itemAttachment, "itemAttachment");
function boundaryAttachment(containerId, side, demandKey, result, demandCoords) {
  const owner = result.forest.nodeById.get(containerId);
  const container = result.containers.get(containerId);
  if (!owner || !container) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing boundary metadata for "${containerId}"`);
  }
  const rect = rectForNode(owner);
  const coord = demandCoords.get(demandKey) ?? (side === "left" || side === "right" ? rect.cy : rect.cx);
  switch (side) {
    case "left":
      return {
        port: { x: rect.left, y: coord },
        connect: { x: container.verticalCorridors[0], y: coord },
        orientation: "V",
        side
      };
    case "right":
      return {
        port: { x: rect.right, y: coord },
        connect: {
          x: container.verticalCorridors[container.verticalCorridors.length - 1],
          y: coord
        },
        orientation: "V",
        side
      };
    case "top":
      return {
        port: { x: coord, y: rect.top },
        connect: { x: coord, y: container.horizontalCorridors[0] },
        orientation: "H",
        side
      };
    case "bottom":
      return {
        port: { x: coord, y: rect.bottom },
        connect: {
          x: coord,
          y: container.horizontalCorridors[container.horizontalCorridors.length - 1]
        },
        orientation: "H",
        side
      };
  }
}
__name(boundaryAttachment, "boundaryAttachment");
function portalBoundaryPoint(portal) {
  return {
    x: (portal.interior.x + portal.exterior.x) / 2,
    y: (portal.interior.y + portal.exterior.y) / 2
  };
}
__name(portalBoundaryPoint, "portalBoundaryPoint");
function portalAttachment(portal, interior) {
  return {
    ownerId: portal.ownerId,
    port: portalBoundaryPoint(portal),
    connect: interior ? portal.interior : portal.exterior,
    orientation: portal.side === "left" || portal.side === "right" ? "V" : "H",
    side: portal.side
  };
}
__name(portalAttachment, "portalAttachment");
function groupBoundaryEndpointAttachment(ownerId, side, demandKey, result, demandCoords) {
  const owner = result.forest.nodeById.get(ownerId);
  if (!owner?.isGroup) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing group endpoint "${ownerId}"`);
  }
  const rect = rectForNode(owner);
  const coordinate = demandCoords.get(demandKey) ?? (side === "left" || side === "right" ? rect.cy : rect.cx);
  const port = side === "left" || side === "right" ? { x: side === "left" ? rect.left : rect.right, y: coordinate } : { x: coordinate, y: side === "top" ? rect.top : rect.bottom };
  return {
    ownerId,
    port,
    connect: {
      x: port.x + (side === "left" ? TERMINAL_APPROACH_PX : side === "right" ? -TERMINAL_APPROACH_PX : 0),
      y: port.y + (side === "top" ? TERMINAL_APPROACH_PX : side === "bottom" ? -TERMINAL_APPROACH_PX : 0)
    },
    orientation: side === "left" || side === "right" ? "V" : "H",
    side
  };
}
__name(groupBoundaryEndpointAttachment, "groupBoundaryEndpointAttachment");
function reversePoints(points) {
  return [...points].reverse();
}
__name(reversePoints, "reversePoints");
function combinePointChains(chains) {
  const points = [];
  for (const chain of chains) {
    for (const point of chain) {
      if (points.length === 0 || !equalPoint(points[points.length - 1], point)) {
        points.push(point);
      }
    }
  }
  return normalizePolyline(points).points;
}
__name(combinePointChains, "combinePointChains");
function routeSelfLoop(owner, side, index, demandCoord) {
  const rect = rectForNode(owner);
  const depth = SELF_LOOP_APPROACH + (index + 1) * SELF_LOOP_TRACK_GAP;
  const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;
  switch (side) {
    case "right": {
      const startY = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;
      const endY = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;
      return normalizePolyline([
        { x: rect.right, y: startY },
        { x: rect.right + SELF_LOOP_APPROACH, y: startY },
        { x: rect.right + depth, y: startY },
        { x: rect.right + depth, y: endY },
        { x: rect.right + SELF_LOOP_APPROACH, y: endY },
        { x: rect.right, y: endY }
      ]).points;
    }
    case "left": {
      const startY = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;
      const endY = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;
      return normalizePolyline([
        { x: rect.left, y: startY },
        { x: rect.left - SELF_LOOP_APPROACH, y: startY },
        { x: rect.left - depth, y: startY },
        { x: rect.left - depth, y: endY },
        { x: rect.left - SELF_LOOP_APPROACH, y: endY },
        { x: rect.left, y: endY }
      ]).points;
    }
    case "top": {
      const startX = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;
      const endX = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;
      return normalizePolyline([
        { x: startX, y: rect.top },
        { x: startX, y: rect.top - SELF_LOOP_APPROACH },
        { x: startX, y: rect.top - depth },
        { x: endX, y: rect.top - depth },
        { x: endX, y: rect.top - SELF_LOOP_APPROACH },
        { x: endX, y: rect.top }
      ]).points;
    }
    case "bottom": {
      const startX = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;
      const endX = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;
      return normalizePolyline([
        { x: startX, y: rect.bottom },
        { x: startX, y: rect.bottom + SELF_LOOP_APPROACH },
        { x: startX, y: rect.bottom + depth },
        { x: endX, y: rect.bottom + depth },
        { x: endX, y: rect.bottom + SELF_LOOP_APPROACH },
        { x: endX, y: rect.bottom }
      ]).points;
    }
  }
}
__name(routeSelfLoop, "routeSelfLoop");
function labelAwareSelfLoopCandidates(owner, side, index, demandCoord, requirement) {
  const rect = rectForNode(owner);
  const baseDepth = SELF_LOOP_APPROACH + (index + 1) * SELF_LOOP_TRACK_GAP;
  const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;
  const baseSpan = SELF_LOOP_PORT_GAP + portOffset * 2;
  const verticalSide = side === "left" || side === "right";
  const span = Math.max(
    baseSpan,
    (verticalSide ? requirement.cross : requirement.along) + GRID_LABEL_CLEARANCE * 2 + GRID_LABEL_SPAN_MARGIN
  );
  const depth = Math.max(
    baseDepth,
    (verticalSide ? requirement.along : requirement.cross) / 2 + GRID_LABEL_CLEARANCE
  );
  const interval = verticalSide ? [rect.top, rect.bottom] : [rect.left, rect.right];
  const directStart = demandCoord - span / 2;
  const directEnd = demandCoord + span / 2;
  if (directStart - interval[0] >= SELF_LOOP_CORNER_CLEARANCE && interval[1] - directEnd >= SELF_LOOP_CORNER_CLEARANCE) {
    switch (side) {
      case "right":
        return [
          normalizePolyline([
            { x: rect.right, y: directStart },
            { x: rect.right + depth, y: directStart },
            { x: rect.right + depth, y: directEnd },
            { x: rect.right, y: directEnd }
          ]).points
        ];
      case "left":
        return [
          normalizePolyline([
            { x: rect.left, y: directStart },
            { x: rect.left - depth, y: directStart },
            { x: rect.left - depth, y: directEnd },
            { x: rect.left, y: directEnd }
          ]).points
        ];
      case "top":
        return [
          normalizePolyline([
            { x: directStart, y: rect.top },
            { x: directStart, y: rect.top - depth },
            { x: directEnd, y: rect.top - depth },
            { x: directEnd, y: rect.top }
          ]).points
        ];
      case "bottom":
        return [
          normalizePolyline([
            { x: directStart, y: rect.bottom },
            { x: directStart, y: rect.bottom + depth },
            { x: directEnd, y: rect.bottom + depth },
            { x: directEnd, y: rect.bottom }
          ]).points
        ];
    }
  }
  const portStart = demandCoord - SELF_LOOP_PORT_GAP / 2 - portOffset;
  const portEnd = demandCoord + SELF_LOOP_PORT_GAP / 2 + portOffset;
  if (portStart < interval[0] || portEnd > interval[1]) {
    return [];
  }
  const outerStart = demandCoord - span / 2;
  const outerEnd = demandCoord + span / 2;
  const shoulderApproach = Math.max(SELF_LOOP_APPROACH, TERMINAL_APPROACH_PX);
  const shoulderDepth = Math.max(
    depth,
    shoulderApproach + (verticalSide ? requirement.along : requirement.cross) / 2 + GRID_LABEL_CLEARANCE
  );
  switch (side) {
    case "right":
      return [
        normalizePolyline([
          { x: rect.right, y: portStart },
          { x: rect.right + shoulderApproach, y: portStart },
          { x: rect.right + shoulderApproach, y: outerStart },
          { x: rect.right + shoulderDepth, y: outerStart },
          { x: rect.right + shoulderDepth, y: outerEnd },
          { x: rect.right + shoulderApproach, y: outerEnd },
          { x: rect.right + shoulderApproach, y: portEnd },
          { x: rect.right, y: portEnd }
        ]).points
      ];
    case "left":
      return [
        normalizePolyline([
          { x: rect.left, y: portStart },
          { x: rect.left - shoulderApproach, y: portStart },
          { x: rect.left - shoulderApproach, y: outerStart },
          { x: rect.left - shoulderDepth, y: outerStart },
          { x: rect.left - shoulderDepth, y: outerEnd },
          { x: rect.left - shoulderApproach, y: outerEnd },
          { x: rect.left - shoulderApproach, y: portEnd },
          { x: rect.left, y: portEnd }
        ]).points
      ];
    case "top":
      return [
        normalizePolyline([
          { x: portStart, y: rect.top },
          { x: portStart, y: rect.top - shoulderApproach },
          { x: outerStart, y: rect.top - shoulderApproach },
          { x: outerStart, y: rect.top - shoulderDepth },
          { x: outerEnd, y: rect.top - shoulderDepth },
          { x: outerEnd, y: rect.top - shoulderApproach },
          { x: portEnd, y: rect.top - shoulderApproach },
          { x: portEnd, y: rect.top }
        ]).points
      ];
    case "bottom":
      return [
        normalizePolyline([
          { x: portStart, y: rect.bottom },
          { x: portStart, y: rect.bottom + shoulderApproach },
          { x: outerStart, y: rect.bottom + shoulderApproach },
          { x: outerStart, y: rect.bottom + shoulderDepth },
          { x: outerEnd, y: rect.bottom + shoulderDepth },
          { x: outerEnd, y: rect.bottom + shoulderApproach },
          { x: portEnd, y: rect.bottom + shoulderApproach },
          { x: portEnd, y: rect.bottom }
        ]).points
      ];
  }
}
__name(labelAwareSelfLoopCandidates, "labelAwareSelfLoopCandidates");
function orderedSelfLoopSides(node, counts, selfLoopCounts) {
  const sides = node.isGroup && ownerGroupTitle(node) ? ["left", "right", "bottom"] : ["left", "right", "top", "bottom"];
  return sides.sort((a, b) => {
    const aCount = (counts.get(ownerSideKey(node.id, a)) ?? 0) + (selfLoopCounts.get(`${node.id}:${a}`) ?? 0);
    const bCount = (counts.get(ownerSideKey(node.id, b)) ?? 0) + (selfLoopCounts.get(`${node.id}:${b}`) ?? 0);
    return aCount - bCount;
  });
}
__name(orderedSelfLoopSides, "orderedSelfLoopSides");
function selfLoopObstacles(owner, result) {
  const obstacles = [];
  for (const node of result.forest.nodeById.values()) {
    if (node.id !== owner.id && !node.isGroup && node.x !== void 0 && node.y !== void 0) {
      obstacles.push(rectForNode(node));
    }
    if (node.id !== owner.id && node.groupTitleRect) {
      const { left, right, top, bottom } = node.groupTitleRect;
      obstacles.push({
        cx: (left + right) / 2,
        cy: (top + bottom) / 2,
        left,
        right,
        top,
        bottom
      });
    }
  }
  return obstacles;
}
__name(selfLoopObstacles, "selfLoopObstacles");
function routeObstacleClearSelfLoop(owner, ownerSideCounts, selfLoopCounts, result, labelRequirement, metrics) {
  const rect = rectForNode(owner);
  const obstacles = selfLoopObstacles(owner, result);
  for (const side of orderedSelfLoopSides(owner, ownerSideCounts, selfLoopCounts)) {
    const countKey = `${owner.id}:${side}`;
    const index = selfLoopCounts.get(countKey) ?? 0;
    const demandCoord = side === "left" || side === "right" ? rect.cy : rect.cx;
    const candidates = labelRequirement ? labelAwareSelfLoopCandidates(owner, side, index, demandCoord, labelRequirement) : [routeSelfLoop(owner, side, index, demandCoord)];
    if (labelRequirement && metrics) {
      metrics.labelAwareSelfLoopCandidates += candidates.length;
    }
    for (const points of candidates) {
      if (!obstacles.some((obstacle) => polylineIntersectsRect(points, obstacle))) {
        return { points, side, index };
      }
    }
  }
  throw gridError("GRID_ROUTE_NOT_FOUND", `No obstacle-clear self-loop route for "${owner.id}"`, {
    nodeId: owner.id
  });
}
__name(routeObstacleClearSelfLoop, "routeObstacleClearSelfLoop");
function rootContainerMeta(result) {
  if (result.containers.has(ROOT_CONTAINER_ID)) {
    return;
  }
  let minLeft = 0;
  let maxRight = 0;
  let minTop = 0;
  let maxBottom = 0;
  let first = true;
  for (const item of result.itemMeta.values()) {
    if (item.containerId !== ROOT_CONTAINER_ID) {
      continue;
    }
    if (first) {
      minLeft = item.cellLeft;
      maxRight = item.cellLeft + item.cellWidth;
      minTop = item.cellTop;
      maxBottom = item.cellTop + item.cellHeight;
      first = false;
    } else {
      minLeft = Math.min(minLeft, item.cellLeft);
      maxRight = Math.max(maxRight, item.cellLeft + item.cellWidth);
      minTop = Math.min(minTop, item.cellTop);
      maxBottom = Math.max(maxBottom, item.cellTop + item.cellHeight);
    }
  }
  const horizontalCorridors = /* @__PURE__ */ new Set([
    minTop - ROOT_OUTER_MARGIN,
    maxBottom + ROOT_OUTER_MARGIN
  ]);
  const verticalCorridors = /* @__PURE__ */ new Set([
    minLeft - ROOT_OUTER_MARGIN,
    maxRight + ROOT_OUTER_MARGIN
  ]);
  for (const item of result.itemMeta.values()) {
    if (item.containerId !== ROOT_CONTAINER_ID) {
      continue;
    }
    horizontalCorridors.add(item.topCorridorY);
    horizontalCorridors.add(item.bottomCorridorY);
    verticalCorridors.add(item.leftCorridorX);
    verticalCorridors.add(item.rightCorridorX);
  }
  result.containers.set(ROOT_CONTAINER_ID, {
    id: ROOT_CONTAINER_ID,
    left: minLeft - ROOT_OUTER_MARGIN,
    top: minTop - ROOT_OUTER_MARGIN,
    width: maxRight - minLeft + ROOT_OUTER_MARGIN * 2,
    height: maxBottom - minTop + ROOT_OUTER_MARGIN * 2,
    contentLeft: minLeft,
    contentTop: minTop,
    contentRight: maxRight,
    contentBottom: maxBottom,
    verticalCorridors: [...verticalCorridors].sort((a, b) => a - b),
    horizontalCorridors: [...horizontalCorridors].sort((a, b) => a - b)
  });
}
__name(rootContainerMeta, "rootContainerMeta");
function containerBounds(containerId, result) {
  const container = result.containers.get(containerId);
  if (!container) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing container layout "${containerId}"`);
  }
  if (containerId === ROOT_CONTAINER_ID) {
    const rootItems = [...result.itemMeta.values()].filter(
      ({ containerId: ownerContainerId }) => ownerContainerId === ROOT_CONTAINER_ID
    );
    if (rootItems.length > 0) {
      return {
        left: Math.min(...rootItems.map(({ cellLeft }) => cellLeft)) - ROOT_OUTER_MARGIN,
        right: Math.max(...rootItems.map(({ cellLeft, cellWidth }) => cellLeft + cellWidth)) + ROOT_OUTER_MARGIN,
        top: Math.min(...rootItems.map(({ cellTop }) => cellTop)) - ROOT_OUTER_MARGIN,
        bottom: Math.max(...rootItems.map(({ cellTop, cellHeight }) => cellTop + cellHeight)) + ROOT_OUTER_MARGIN
      };
    }
    return {
      left: container.left,
      right: container.left + container.width,
      top: container.top,
      bottom: container.top + container.height
    };
  }
  const owner = result.forest.nodeById.get(containerId);
  if (!owner) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing container owner "${containerId}"`);
  }
  const ownerBounds = routerRect(owner);
  return {
    left: ownerBounds.left + ROUTE_CLEARANCE_PX,
    right: ownerBounds.right - ROUTE_CLEARANCE_PX,
    top: ownerBounds.top + ROUTE_CLEARANCE_PX,
    bottom: ownerBounds.bottom - ROUTE_CLEARANCE_PX
  };
}
__name(containerBounds, "containerBounds");
function portalCoordinate(bounds, side, interior) {
  const boundary = side === "left" ? bounds.left : side === "right" ? bounds.right : side === "top" ? bounds.top : bounds.bottom;
  const towardInterior = side === "left" || side === "top" ? 1 : -1;
  return boundary + towardInterior * ROUTE_CLEARANCE_PX * (interior ? 1 : -1);
}
__name(portalCoordinate, "portalCoordinate");
function containerPortalRanges(containerId, result) {
  const ranges = [];
  if (containerId !== ROOT_CONTAINER_ID) {
    const owner = result.forest.nodeById.get(containerId);
    if (owner) {
      const bounds = routerRect(owner);
      ranges.push(
        ...derivePortalRanges(containerId, bounds, owner.groupTitleRect).map((range) => ({
          ...range,
          coordinate: portalCoordinate(bounds, range.side, true)
        }))
      );
    }
  }
  for (const child of result.forest.childrenByParent.get(containerId) ?? []) {
    if (!child.isGroup) {
      continue;
    }
    const bounds = routerRect(child);
    ranges.push(
      ...derivePortalRanges(child.id, bounds, child.groupTitleRect).map((range) => ({
        ...range,
        coordinate: portalCoordinate(bounds, range.side, false)
      }))
    );
  }
  return ranges;
}
__name(containerPortalRanges, "containerPortalRanges");
function buildRoutingContext(containerIds, result, metrics, options) {
  const context = {
    topologies: /* @__PURE__ */ new Map(),
    fallbackContainers: /* @__PURE__ */ new Map(),
    searchBudget: { expandedStates: 0 },
    searchBudgetWarningEmitted: false,
    baseEstimatedBytes: 0,
    metrics
  };
  let estimatedBytes = 0;
  for (const containerId of [...new Set(containerIds)].sort()) {
    const children = (result.forest.childrenByParent.get(containerId) ?? []).filter(
      (node) => !isEdgeLabelNode(node)
    );
    const title = result.forest.nodeById.get(containerId)?.groupTitleRect;
    try {
      const topology = buildContainerRoutingTopology(
        {
          containerId,
          bounds: containerBounds(containerId, result),
          obstacles: children.map((node) => ({ id: node.id, bounds: routerRect(node) })),
          titleExclusions: title ? [{ id: `${containerId}:title`, bounds: { ...title } }] : void 0,
          portalRanges: containerPortalRanges(containerId, result)
        },
        { caps: options.topologyCaps }
      );
      const invocationMemoryCap = options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES;
      if (estimatedBytes + topology.estimatedBytes > invocationMemoryCap) {
        context.fallbackContainers.set(containerId, "estimated_memory_cap");
        continue;
      }
      estimatedBytes += topology.estimatedBytes;
      context.baseEstimatedBytes = estimatedBytes;
      context.topologies.set(containerId, topology);
      if (metrics) {
        metrics.containersBuilt++;
        metrics.baseTopologyBuilds++;
        metrics.baseVertices += topology.vertices.length;
        metrics.baseAdjacencyEntries += topology.adjacencyEntries;
        metrics.buildSweepEvents += topology.seedCount * 4 + topology.obstacles.length * 4;
        metrics.estimatedBytes = estimatedBytes;
      }
    } catch (error) {
      if (!(error instanceof GridRoutingResourceLimitError)) {
        throw error;
      }
      context.fallbackContainers.set(containerId, error.reason);
    }
  }
  return context;
}
__name(buildRoutingContext, "buildRoutingContext");
function validatedCompatibilitySegment(edgeId, containerId, start, end, route, result, metrics) {
  const points = route();
  if (metrics) {
    metrics.compatibilitySegments++;
  }
  if (validateContainerSegment(points, start.ownerId, end.ownerId, containerId, result)) {
    return points;
  }
  if (metrics) {
    metrics.compatibilityValidationFailures++;
    metrics.routesImpossible++;
  }
  throw gridError("GRID_ROUTE_NOT_FOUND", `Invalid compatibility route for "${edgeId}"`, {
    edgeId,
    containerId
  });
}
__name(validatedCompatibilitySegment, "validatedCompatibilitySegment");
function compatibilityLcaAttachments(plan, result, demandCoords) {
  const sourceFinal = plan.source.chain.at(-1);
  const targetFinal = plan.target.chain.at(-1);
  const finalAttachment = /* @__PURE__ */ __name((endpoint, final) => ({
    ownerId: final.ownerId,
    ...endpoint.finalKind === "boundary" ? boundaryAttachment(plan.lcaContainerId, final.side, final.demandKey, result, demandCoords) : itemAttachment(
      final.ownerId,
      final.side,
      final.demandKey,
      plan.lcaContainerId,
      result,
      demandCoords
    )
  }), "finalAttachment");
  return {
    start: finalAttachment(plan.source, sourceFinal),
    end: finalAttachment(plan.target, targetFinal)
  };
}
__name(compatibilityLcaAttachments, "compatibilityLcaAttachments");
function compatibilityHierarchyAttachments(endpoint, result, demandCoords) {
  return endpoint.chain.slice(0, -1).map((from, index) => {
    const to = endpoint.chain[index + 1];
    return {
      containerId: to.ownerId,
      start: {
        ownerId: from.ownerId,
        ...itemAttachment(
          from.ownerId,
          from.side,
          from.demandKey,
          to.ownerId,
          result,
          demandCoords
        )
      },
      end: {
        ownerId: to.ownerId,
        ...boundaryAttachment(to.ownerId, to.side, to.demandKey, result, demandCoords)
      }
    };
  });
}
__name(compatibilityHierarchyAttachments, "compatibilityHierarchyAttachments");
function compatibilityPlanIsValid(plan, result, demandCoords) {
  const segmentIsValid = /* @__PURE__ */ __name((containerId, start, end) => validateContainerSegment(
    routeWithinContainer(containerId, result, start, end, plan.laneIndex),
    start.ownerId,
    end.ownerId,
    containerId,
    result
  ), "segmentIsValid");
  for (const endpoint of [plan.source, plan.target]) {
    for (const { containerId, start, end } of compatibilityHierarchyAttachments(
      endpoint,
      result,
      demandCoords
    )) {
      if (!segmentIsValid(containerId, start, end)) {
        return false;
      }
    }
  }
  const attachments = compatibilityLcaAttachments(plan, result, demandCoords);
  return segmentIsValid(plan.lcaContainerId, attachments.start, attachments.end);
}
__name(compatibilityPlanIsValid, "compatibilityPlanIsValid");
function prepareRoutingModes(prepared, result, metrics, options) {
  const {
    plans,
    eligiblePlans,
    eligibleIds,
    demandCoords,
    endpointCandidatesByEdge,
    endpointIncidentCounts,
    coordinatedEndpointIds
  } = prepared;
  const hasIsolatedEndpoints = /* @__PURE__ */ __name((plan) => (endpointIncidentCounts.get(plan.edge.start) ?? 0) === plan.bundleSize && (endpointIncidentCounts.get(plan.edge.end) ?? 0) === plan.bundleSize, "hasIsolatedEndpoints");
  const hasAncestorEndpoint = /* @__PURE__ */ __name((plan) => {
    const source = result.forest.nodeById.get(plan.edge.start);
    const target = result.forest.nodeById.get(plan.edge.end);
    return Boolean(
      source && target && (source.isGroup && isAncestorGroup(source.id, target, result.forest.nodeById) || target.isGroup && isAncestorGroup(target.id, source, result.forest.nodeById))
    );
  }, "hasAncestorEndpoint");
  const compatibilityFastRoutes = /* @__PURE__ */ new Map();
  const routeOccupancy = /* @__PURE__ */ new Map();
  const overlapAvoidanceEnabled = plans.length <= MAX_PLANS_FOR_OVERLAP_AVOIDANCE;
  const compatibilityFastPathEnabled = options.topologyCaps === void 0 && options.searchCaps === void 0 && options.onDualRouteComparison === void 0;
  for (const plan of compatibilityFastPathEnabled ? eligiblePlans : []) {
    if (coordinatedEndpointIds.has(plan.edge.id)) {
      continue;
    }
    const candidates = endpointCandidatesByEdge.get(plan.edge.id);
    if (plan.bundleSize !== 1 || !candidates?.sources.length || !candidates.targets.length) {
      continue;
    }
    const source = result.forest.nodeById.get(plan.edge.start);
    const target = result.forest.nodeById.get(plan.edge.end);
    if (!source || !target) {
      continue;
    }
    const attachments = compatibilityLcaAttachments(plan, result, demandCoords);
    const route = routeWithinContainer(
      plan.lcaContainerId,
      result,
      attachments.start,
      attachments.end,
      plan.laneIndex
    );
    const normalized = normalizePolyline(route);
    const first = normalized.points[0];
    const last = normalized.points.at(-1);
    if (!first || !last) {
      continue;
    }
    const sourceCandidate = candidates.sources.find(
      ({ port }) => port.x === first.x && port.y === first.y
    );
    const targetCandidate = candidates.targets.find(
      ({ port }) => port.x === last.x && port.y === last.y
    );
    if (!sourceCandidate || !targetCandidate) {
      continue;
    }
    if (metrics) {
      metrics.compatibilityFastPathAttempts++;
    }
    const lowerBoundLength = Math.abs(first.x - last.x) + Math.abs(first.y - last.y);
    if (!validateSameContainerRoute(route, source, target, plan.lcaContainerId, result)) {
      if (metrics) {
        metrics.compatibilityFastPathValidationFailures++;
      }
      continue;
    }
    if (manhattanLength(normalized.points) !== lowerBoundLength) {
      if (metrics) {
        metrics.compatibilityFastPathNonMinimalRoutes++;
      }
      continue;
    }
    let occupancy = routeOccupancy.get(plan.lcaContainerId);
    if (!occupancy) {
      occupancy = new RouteOccupancyIndex();
      routeOccupancy.set(plan.lcaContainerId, occupancy);
    }
    const conflicting = occupancy.conflictsWithRoute(normalized.points, plan.pairKey);
    if (conflicting && overlapAvoidanceEnabled) {
      continue;
    }
    const separated = separateRouteFromOccupied(
      normalized.points,
      occupancy,
      plan.pairKey,
      (candidate) => terminalStubsAreLongEnough(candidate) && manhattanLength(candidate) === lowerBoundLength && validateSameContainerRoute(candidate, source, target, plan.lcaContainerId, result)
    );
    const finalRoute = separated ?? route;
    occupancy.add(finalRoute, plan.pairKey);
    compatibilityFastRoutes.set(plan.edge.id, finalRoute);
  }
  const sparseCandidate = /* @__PURE__ */ __name((plan) => !eligibleIds.has(plan.edge.id) && plan.edge.start !== plan.edge.end && (plan.bundleSize > 1 || hasIsolatedEndpoints(plan) || !compatibilityPlanIsValid(plan, result, demandCoords)), "sparseCandidate");
  const planningOccupancy = /* @__PURE__ */ new Map();
  const overlappingHierarchyIds = /* @__PURE__ */ new Set();
  if (overlapAvoidanceEnabled) {
    for (const plan of prepared.orderedPlans) {
      if (eligibleIds.has(plan.edge.id) || plan.edge.start === plan.edge.end || hasAncestorEndpoint(plan) || sparseCandidate(plan)) {
        continue;
      }
      const attachments = compatibilityLcaAttachments(plan, result, demandCoords);
      const route = routeWithinContainer(
        plan.lcaContainerId,
        result,
        attachments.start,
        attachments.end,
        plan.laneIndex
      );
      let occupancy = planningOccupancy.get(plan.lcaContainerId);
      if (!occupancy) {
        occupancy = new RouteOccupancyIndex();
        planningOccupancy.set(plan.lcaContainerId, occupancy);
      }
      if (occupancy.conflictsWithRoute(route, plan.pairKey)) {
        overlappingHierarchyIds.add(plan.edge.id);
      } else {
        occupancy.add(route, plan.pairKey);
      }
    }
  }
  const sparseHierarchyIds = /* @__PURE__ */ new Set([
    ...plans.filter(sparseCandidate).map(({ edge }) => edge.id),
    ...overlappingHierarchyIds
  ]);
  const sparseLcaIds = /* @__PURE__ */ new Set([
    ...sparseHierarchyIds,
    ...plans.filter(hasAncestorEndpoint).map(({ edge }) => edge.id)
  ]);
  const routedContainerIds = plans.filter(
    (plan) => eligibleIds.has(plan.edge.id) && !compatibilityFastRoutes.has(plan.edge.id) || sparseLcaIds.has(plan.edge.id) || plan.edge.start === plan.edge.end
  ).flatMap((plan) => [
    plan.lcaContainerId,
    ...plan.source.chain.slice(1).map(({ ownerId }) => ownerId),
    ...plan.target.chain.slice(1).map(({ ownerId }) => ownerId)
  ]);
  return {
    overlapAvoidanceEnabled,
    compatibilityFastRoutes,
    sparseHierarchyIds,
    sparseLcaIds,
    routedContainerIds,
    routeOccupancy
  };
}
__name(prepareRoutingModes, "prepareRoutingModes");

// src/rendering-util/layout-algorithms/grid/routerInstrumentation.ts
var gridRoutingMetricDisposition = {
  containersBuilt: "cumulative",
  baseTopologyBuilds: "cumulative",
  baseVertices: "cumulative",
  baseAdjacencyEntries: "cumulative",
  buildSweepEvents: "cumulative",
  endpointOverlayBuilds: "cumulative",
  endpointOverlayVertices: "cumulative",
  hierarchyPortalPairs: "transactional",
  hierarchyPortalTransitionLength: "transactional",
  hierarchyPortalAlternativeAttempts: "cumulative",
  hierarchyPortalAlternativeSelections: "transactional",
  hierarchyBoundaryTransitions: "transactional",
  labelOverlayBuilds: "cumulative",
  labelOverlayVertices: "cumulative",
  labelSpacingEdgesExamined: "cumulative",
  labelSpacingEligibleEdges: "cumulative",
  labelSpacingBoundariesExpanded: "cumulative",
  labelSpacingPixelsAdded: "cumulative",
  labelAwareSelfLoopCandidates: "cumulative",
  labelAwareSelfLoopsCommitted: "transactional",
  labelAwareSelfLoopFallbacks: "cumulative",
  searches: "cumulative",
  expandedStates: "cumulative",
  maxOpenSet: "cumulative",
  routesFound: "transactional",
  routesImpossible: "transactional",
  resourceLimitFallbacks: "cumulative",
  fallbackReasons: "cumulative",
  fallbackValidationFailures: "cumulative",
  compatibilitySegments: "transactional",
  compatibilityFastPathAttempts: "cumulative",
  compatibilityFastPaths: "cumulative",
  compatibilityFastPathValidationFailures: "cumulative",
  compatibilityFastPathNonMinimalRoutes: "cumulative",
  compatibilityRecoveries: "transactional",
  compatibilityValidationFailures: "cumulative",
  bundleSeparationRelaxations: "transactional",
  routeLength: "transactional",
  bendCount: "transactional",
  crossingCount: "transactional",
  sharedLength: "transactional",
  estimatedBytes: "cumulative",
  searchWorkspaceBytes: "cumulative",
  routeOrder: "transactional",
  routes: "transactional"
};
var transactionalGridRoutingValueMetrics = Object.keys(gridRoutingMetricDisposition).filter(
  (key) => gridRoutingMetricDisposition[key] === "transactional" && key !== "routeOrder" && key !== "routes"
);
function createGridRoutingInstrumentationCheckpoint(metrics) {
  return {
    routeOrderLength: metrics.routeOrder.length,
    routesLength: metrics.routes.length,
    values: Object.fromEntries(
      transactionalGridRoutingValueMetrics.map((key) => [key, metrics[key]])
    )
  };
}
__name(createGridRoutingInstrumentationCheckpoint, "createGridRoutingInstrumentationCheckpoint");
function restoreGridRoutingInstrumentationCheckpoint(metrics, checkpoint) {
  metrics.routeOrder.length = checkpoint.routeOrderLength;
  metrics.routes.length = checkpoint.routesLength;
  Object.assign(metrics, checkpoint.values);
}
__name(restoreGridRoutingInstrumentationCheckpoint, "restoreGridRoutingInstrumentationCheckpoint");
function intervalOverlap(firstStart, firstEnd, secondStart, secondEnd) {
  return Math.max(
    0,
    Math.min(Math.max(firstStart, firstEnd), Math.max(secondStart, secondEnd)) - Math.max(Math.min(firstStart, firstEnd), Math.min(secondStart, secondEnd))
  );
}
__name(intervalOverlap, "intervalOverlap");
function sharedSegmentLength(first, second) {
  const firstSegments = normalizePolyline(first).segments;
  const secondSegments = normalizePolyline(second).segments;
  let total = 0;
  for (const a of firstSegments) {
    for (const b of secondSegments) {
      if (a.orientation !== b.orientation) {
        continue;
      }
      if (a.orientation === "H" && a.a.y === b.a.y) {
        total += intervalOverlap(a.a.x, a.b.x, b.a.x, b.b.x);
      } else if (a.orientation === "V" && a.a.x === b.a.x) {
        total += intervalOverlap(a.a.y, a.b.y, b.a.y, b.b.y);
      }
    }
  }
  return total;
}
__name(sharedSegmentLength, "sharedSegmentLength");
function recordGridRoute(metrics, edgeId, points, previousRoutes, boundaryTransitionCount = 0, laneOffset = 0) {
  const normalized = normalizePolyline(points);
  let crossingCount = 0;
  let sharedLength = 0;
  for (const previous of previousRoutes) {
    const previousSegments = normalizePolyline(previous).segments;
    for (const segment of normalized.segments) {
      for (const previousSegment of previousSegments) {
        if (segmentsCross(segment, previousSegment)) {
          crossingCount++;
        }
      }
    }
    sharedLength += sharedSegmentLength(normalized.points, previous);
  }
  const route = {
    edgeId,
    routeOrder: metrics.routes.length,
    laneOffset,
    routeLength: manhattanLength(normalized.points),
    bendCount: normalized.bends,
    crossingCount,
    sharedLength,
    boundaryTransitionCount,
    routeSignature: JSON.stringify(normalized.points)
  };
  metrics.routeOrder.push(edgeId);
  metrics.routes.push(route);
  metrics.routesFound++;
  metrics.routeLength += route.routeLength;
  metrics.bendCount += route.bendCount;
  metrics.crossingCount += route.crossingCount;
  metrics.sharedLength += route.sharedLength;
  metrics.hierarchyBoundaryTransitions += boundaryTransitionCount;
}
__name(recordGridRoute, "recordGridRoute");

// src/rendering-util/layout-algorithms/grid/routerSearch.ts
var DEFAULT_MAX_EDGE_STATES = 1e5;
var DEFAULT_MAX_INVOCATION_STATES = 2e6;
var RouterSearchWorkspace = class {
  constructor() {
    // Typed arrays are retained across searches to avoid allocating object-heavy state graphs for
    // every endpoint candidate pair. State capacity grows geometrically and never shrinks mid-session.
    this.stateVertices = new Int32Array(256);
    this.orientations = new Uint8Array(256);
    this.gLengths = new Float64Array(256);
    this.gBends = new Float64Array(256);
    this.gBoundaryTransitions = new Float64Array(256);
    this.fLengths = new Float64Array(256);
    this.fBends = new Float64Array(256);
    this.predecessors = new Int32Array(256);
    this.depths = new Int32Array(256);
    this.ancestor4 = new Int32Array(256);
    this.best = new Int32Array(256);
    this.heapChildren = new Int32Array(256);
    this.heapSiblings = new Int32Array(256);
    this.heapPairs = [];
    this.touchedBestIndices = [];
    this.best.fill(-1);
  }
  static {
    __name(this, "RouterSearchWorkspace");
  }
  reset(vertexCount) {
    const bestLength = vertexCount * 3;
    if (this.best.length < bestLength) {
      this.best = new Int32Array(bestLength);
      this.best.fill(-1);
    } else {
      for (const index of this.touchedBestIndices) {
        this.best[index] = -1;
      }
    }
    this.touchedBestIndices.length = 0;
    this.heapPairs.length = 0;
  }
  setBest(index, state) {
    if (this.best[index] < 0) {
      this.touchedBestIndices.push(index);
    }
    this.best[index] = state;
  }
  ensureStateCapacity(required) {
    if (this.stateVertices.length >= required) {
      return;
    }
    const capacity = Math.max(required, this.stateVertices.length * 2);
    this.stateVertices = growTypedArray(this.stateVertices, capacity);
    this.orientations = growTypedArray(this.orientations, capacity);
    this.gLengths = growTypedArray(this.gLengths, capacity);
    this.gBends = growTypedArray(this.gBends, capacity);
    this.gBoundaryTransitions = growTypedArray(this.gBoundaryTransitions, capacity);
    this.fLengths = growTypedArray(this.fLengths, capacity);
    this.fBends = growTypedArray(this.fBends, capacity);
    this.predecessors = growTypedArray(this.predecessors, capacity);
    this.depths = growTypedArray(this.depths, capacity);
    this.ancestor4 = growTypedArray(this.ancestor4, capacity);
    this.heapChildren = growTypedArray(this.heapChildren, capacity);
    this.heapSiblings = growTypedArray(this.heapSiblings, capacity);
  }
  estimatedBytes() {
    return this.stateVertices.byteLength + this.orientations.byteLength + this.gLengths.byteLength + this.gBends.byteLength + this.gBoundaryTransitions.byteLength + this.fLengths.byteLength + this.fBends.byteLength + this.predecessors.byteLength + this.depths.byteLength + this.ancestor4.byteLength + this.best.byteLength + this.heapChildren.byteLength + this.heapSiblings.byteLength + (this.heapPairs.length + this.touchedBestIndices.length) * 8;
  }
};
function assertSearchBudgetAvailable(options) {
  const edgeCap = options.caps?.maxExpandedStates ?? DEFAULT_MAX_EDGE_STATES;
  const invocationCap = options.caps?.maxInvocationExpandedStates ?? DEFAULT_MAX_INVOCATION_STATES;
  const invocationStart = options.budget?.expandedStates ?? options.metrics?.expandedStates ?? 0;
  if (edgeCap > 0 && invocationStart < invocationCap) {
    return;
  }
  throw new GridRoutingResourceLimitError(
    "search_state_cap",
    "Grid routing search-state cap exceeded",
    invocationStart >= invocationCap ? "invocation" : "edge"
  );
}
__name(assertSearchBudgetAvailable, "assertSearchBudgetAvailable");
function growTypedArray(values, capacity) {
  const grown = new values.constructor(capacity);
  grown.set(values);
  return grown;
}
__name(growTypedArray, "growTypedArray");
function compareTupleCost(a, b) {
  for (let index = 0; index < 4; index++) {
    if (a[index] < b[index]) {
      return -1;
    }
    if (a[index] > b[index]) {
      return 1;
    }
  }
  return 0;
}
__name(compareTupleCost, "compareTupleCost");
function minimumBends(dx, dy, incomingOrientation, targetOrientation) {
  if (dx === 0 && dy === 0) {
    return incomingOrientation && targetOrientation ? Number(incomingOrientation !== targetOrientation) : 0;
  }
  if (dx === 0) {
    return (incomingOrientation ? Number(incomingOrientation !== "V") : 0) + (targetOrientation ? Number(targetOrientation !== "V") : 0);
  }
  if (dy === 0) {
    return (incomingOrientation ? Number(incomingOrientation !== "H") : 0) + (targetOrientation ? Number(targetOrientation !== "H") : 0);
  }
  return Math.min(
    (incomingOrientation ? Number(incomingOrientation !== "H") : 0) + 1 + (targetOrientation ? Number(targetOrientation !== "V") : 0),
    (incomingOrientation ? Number(incomingOrientation !== "V") : 0) + 1 + (targetOrientation ? Number(targetOrientation !== "H") : 0)
  );
}
__name(minimumBends, "minimumBends");
function orientationOrdinal(orientation) {
  return orientation === void 0 ? 0 : orientation === "H" ? 1 : 2;
}
__name(orientationOrdinal, "orientationOrdinal");
function movesTowardOwner(from, to, side) {
  return side === "left" ? from.y === to.y && to.x > from.x : side === "right" ? from.y === to.y && to.x < from.x : side === "top" ? from.x === to.x && to.y > from.y : from.x === to.x && to.y < from.y;
}
__name(movesTowardOwner, "movesTowardOwner");
function stateIndex(vertexId, orientation) {
  return vertexId * 3 + orientationOrdinal(orientation);
}
__name(stateIndex, "stateIndex");
function normalizePoints(points) {
  const result = [];
  for (const point of points) {
    const previous = result.at(-1);
    if (previous && previous.x === point.x && previous.y === point.y) {
      continue;
    }
    const beforePrevious = result.at(-2);
    if (beforePrevious && previous && (beforePrevious.x === previous.x && previous.x === point.x || beforePrevious.y === previous.y && previous.y === point.y)) {
      result[result.length - 1] = { ...point };
    } else {
      result.push({ ...point });
    }
  }
  return result;
}
__name(normalizePoints, "normalizePoints");
function reconstruct(stateId, stateVertices, predecessors, cost, vertexAt) {
  const vertexIds = [];
  let current = stateId;
  while (current >= 0) {
    vertexIds.push(stateVertices[current]);
    current = predecessors[current];
  }
  vertexIds.reverse();
  return {
    points: normalizePoints(vertexIds.map((id) => vertexAt(id).point)),
    vertexIds,
    cost
  };
}
__name(reconstruct, "reconstruct");
function validateSearchTopology(topology) {
  for (const vertex of topology.vertices) {
    if (vertex.id < 0 || topology.vertices[vertex.id] !== vertex || !Number.isFinite(vertex.point.x) || !Number.isFinite(vertex.point.y)) {
      throw new Error("Malformed grid routing vertex");
    }
    for (const arc of topology.adjacency.get(vertex.id) ?? []) {
      const target = topology.vertices[arc.to];
      const aligned = target && (arc.orientation === "H" ? vertex.point.y === target.point.y : vertex.point.x === target.point.x);
      const length = target ? Math.abs(vertex.point.x - target.point.x) + Math.abs(vertex.point.y - target.point.y) : Number.NaN;
      if (arc.from !== vertex.id || !aligned || !Number.isFinite(arc.length) || arc.length <= 0 || arc.length !== length) {
        throw new Error("Malformed grid routing arc");
      }
    }
  }
}
__name(validateSearchTopology, "validateSearchTopology");
function search(topology, sourceId, targetId, options) {
  const vertexAt = /* @__PURE__ */ __name((id) => {
    const vertex = topology.getVertex?.(id) ?? topology.vertices[id];
    if (!vertex) {
      throw new Error(`Missing grid routing vertex ${id}`);
    }
    return vertex;
  }, "vertexAt");
  const source = vertexAt(sourceId);
  const target = vertexAt(targetId);
  if (!options.topologyValidated) {
    validateSearchTopology(topology);
  }
  const metrics = options.metrics;
  if (metrics) {
    metrics.searches++;
  }
  assertSearchBudgetAvailable(options);
  const workspace = options.workspace ?? new RouterSearchWorkspace();
  workspace.reset(topology.vertexCount ?? topology.vertices.length);
  let stateVertices = workspace.stateVertices;
  let orientations = workspace.orientations;
  let gLengths = workspace.gLengths;
  let gBends = workspace.gBends;
  let gBoundaryTransitions = workspace.gBoundaryTransitions;
  let fLengths = workspace.fLengths;
  let fBends = workspace.fBends;
  let predecessors = workspace.predecessors;
  let depths = workspace.depths;
  let ancestor4 = workspace.ancestor4;
  let heapChildren = workspace.heapChildren;
  let heapSiblings = workspace.heapSiblings;
  const best = workspace.best;
  const heapPairs = workspace.heapPairs;
  let stateCount = 1;
  const endpointCandidateRank = options.endpointCandidateRank ?? 0;
  const useBendHeuristic = options.heuristic !== "zero";
  function nonCostOrder(a, b) {
    return stateVertices[a] - stateVertices[b] || orientations[a] - orientations[b] || predecessors[a] - predecessors[b] || a - b;
  }
  __name(nonCostOrder, "nonCostOrder");
  function compareStates(a, b) {
    return fLengths[a] - fLengths[b] || fBends[a] - fBends[b] || gBoundaryTransitions[a] - gBoundaryTransitions[b] || (options.queueOrder === "reverse" ? -nonCostOrder(a, b) : nonCostOrder(a, b));
  }
  __name(compareStates, "compareStates");
  function compareChains(a, b) {
    if (a === b) {
      return 0;
    }
    if (a < 0) {
      return -1;
    }
    if (b < 0) {
      return 1;
    }
    const aDepth = depths[a];
    const bDepth = depths[b];
    let alignedA = a;
    let alignedB = b;
    while (depths[alignedA] > depths[alignedB]) {
      alignedA = predecessors[alignedA];
    }
    while (depths[alignedB] > depths[alignedA]) {
      alignedB = predecessors[alignedB];
    }
    if (alignedA === alignedB) {
      return aDepth - bDepth;
    }
    while (ancestor4[alignedA] >= 0 && ancestor4[alignedB] >= 0 && ancestor4[alignedA] !== ancestor4[alignedB]) {
      alignedA = ancestor4[alignedA];
      alignedB = ancestor4[alignedB];
    }
    while (predecessors[alignedA] !== predecessors[alignedB]) {
      alignedA = predecessors[alignedA];
      alignedB = predecessors[alignedB];
    }
    return stateVertices[alignedA] - stateVertices[alignedB] || orientations[alignedA] - orientations[alignedB];
  }
  __name(compareChains, "compareChains");
  let heapRoot = -1;
  let heapSize = 0;
  function heapMeld(first, second) {
    if (first < 0) {
      return second;
    }
    if (second < 0) {
      return first;
    }
    if (compareStates(first, second) <= 0) {
      heapSiblings[second] = heapChildren[first];
      heapChildren[first] = second;
      return first;
    }
    heapSiblings[first] = heapChildren[second];
    heapChildren[second] = first;
    return second;
  }
  __name(heapMeld, "heapMeld");
  const heapPush = /* @__PURE__ */ __name((value) => {
    heapChildren[value] = -1;
    heapSiblings[value] = -1;
    heapRoot = heapMeld(heapRoot, value);
    heapSize++;
  }, "heapPush");
  const heapPop = /* @__PURE__ */ __name(() => {
    if (heapRoot < 0) {
      return void 0;
    }
    const first = heapRoot;
    heapPairs.length = 0;
    let child = heapChildren[first];
    while (child >= 0) {
      const next = heapSiblings[child];
      heapSiblings[child] = -1;
      heapPairs.push(child);
      child = next;
    }
    for (let index = 0; index + 1 < heapPairs.length; index += 2) {
      heapPairs[index >>> 1] = heapMeld(heapPairs[index], heapPairs[index + 1]);
    }
    let pairCount = Math.ceil(heapPairs.length / 2);
    if (heapPairs.length % 2 !== 0) {
      heapPairs[pairCount - 1] = heapPairs[heapPairs.length - 1];
    }
    heapRoot = -1;
    while (pairCount > 0) {
      heapRoot = heapMeld(heapPairs[--pairCount], heapRoot);
    }
    heapSize--;
    return first;
  }, "heapPop");
  let expandedThisSearch = 0;
  const edgeCap = options.caps?.maxExpandedStates ?? DEFAULT_MAX_EDGE_STATES;
  const invocationCap = options.caps?.maxInvocationExpandedStates ?? DEFAULT_MAX_INVOCATION_STATES;
  const invocationStart = options.budget?.expandedStates ?? metrics?.expandedStates ?? 0;
  const recordWorkspaceBytes = /* @__PURE__ */ __name(() => {
    const bytes = workspace.estimatedBytes();
    const totalBytes = (options.estimatedBytesBase ?? 0) + bytes;
    if (metrics) {
      metrics.searchWorkspaceBytes = Math.max(metrics.searchWorkspaceBytes, bytes);
      metrics.estimatedBytes = Math.max(metrics.estimatedBytes, totalBytes);
    }
    if (totalBytes > (options.caps?.maxEstimatedBytes ?? Number.POSITIVE_INFINITY)) {
      throw new GridRoutingResourceLimitError(
        "estimated_memory_cap",
        "Grid routing search workspace memory cap exceeded"
      );
    }
  }, "recordWorkspaceBytes");
  recordWorkspaceBytes();
  const commitExpandedStates = /* @__PURE__ */ __name(() => {
    if (options.budget) {
      options.budget.expandedStates += expandedThisSearch;
    }
    if (metrics) {
      metrics.expandedStates += expandedThisSearch;
    }
  }, "commitExpandedStates");
  const initialLength = options.initialLength ?? 0;
  stateVertices[0] = sourceId;
  orientations[0] = orientationOrdinal(options.initialOrientation);
  gLengths[0] = initialLength;
  gBends[0] = 0;
  gBoundaryTransitions[0] = 0;
  const initialDx = Math.abs(source.point.x - target.point.x);
  const initialDy = Math.abs(source.point.y - target.point.y);
  fLengths[0] = initialLength + (useBendHeuristic ? initialDx + initialDy : 0);
  fBends[0] = useBendHeuristic ? minimumBends(initialDx, initialDy, options.initialOrientation, options.targetOrientation) : 0;
  predecessors[0] = -1;
  depths[0] = 1;
  ancestor4[0] = -1;
  workspace.setBest(stateIndex(sourceId, options.initialOrientation), 0);
  heapPush(0);
  if (metrics) {
    metrics.maxOpenSet = Math.max(metrics.maxOpenSet, heapSize);
  }
  let bestGoalState = -1;
  let bestGoalCost;
  const considerGoal = /* @__PURE__ */ __name((state) => {
    const completedCost = [
      gLengths[state] + (options.targetLength ?? 0),
      gBends[state] + (options.targetOrientation !== void 0 && orientations[state] !== 0 && orientationOrdinal(options.targetOrientation) !== orientations[state] ? 1 : 0),
      gBoundaryTransitions[state],
      endpointCandidateRank
    ];
    if (!bestGoalCost || compareTupleCost(completedCost, bestGoalCost) < 0 || compareTupleCost(completedCost, bestGoalCost) === 0 && compareChains(state, bestGoalState) < 0) {
      bestGoalState = state;
      bestGoalCost = completedCost;
    }
  }, "considerGoal");
  const relaxArc = /* @__PURE__ */ __name((current, currentPoint, to, orientation, arcLength, boundaryTransitions) => {
    const nextPoint = vertexAt(to).point;
    if (options.arcAllowed && !options.arcAllowed(currentPoint, nextPoint)) {
      return;
    }
    if (options.initialSide && predecessors[current] < 0 && movesTowardOwner(currentPoint, nextPoint, options.initialSide)) {
      return;
    }
    if (options.targetSide && to === targetId && movesTowardOwner(target.point, currentPoint, options.targetSide)) {
      return;
    }
    const index = to * 3 + orientation;
    const previous = best[index];
    const length = gLengths[current] + arcLength;
    const bends = gBends[current] + (orientations[current] !== 0 && orientations[current] !== orientation ? 1 : 0);
    const nextBoundaryTransitions = gBoundaryTransitions[current] + boundaryTransitions;
    const previousComparison = previous >= 0 ? length - gLengths[previous] || bends - gBends[previous] || nextBoundaryTransitions - gBoundaryTransitions[previous] : -1;
    if (previous >= 0 && (previousComparison > 0 || previousComparison === 0 && compareChains(current, predecessors[previous]) >= 0)) {
      return;
    }
    const candidate = stateCount++;
    if (stateCount > stateVertices.length) {
      workspace.ensureStateCapacity(stateCount);
      stateVertices = workspace.stateVertices;
      orientations = workspace.orientations;
      gLengths = workspace.gLengths;
      gBends = workspace.gBends;
      gBoundaryTransitions = workspace.gBoundaryTransitions;
      fLengths = workspace.fLengths;
      fBends = workspace.fBends;
      predecessors = workspace.predecessors;
      depths = workspace.depths;
      ancestor4 = workspace.ancestor4;
      heapChildren = workspace.heapChildren;
      heapSiblings = workspace.heapSiblings;
      recordWorkspaceBytes();
    }
    stateVertices[candidate] = to;
    orientations[candidate] = orientation;
    gLengths[candidate] = length;
    gBends[candidate] = bends;
    gBoundaryTransitions[candidate] = nextBoundaryTransitions;
    const candidateDx = Math.abs(nextPoint.x - target.point.x);
    const candidateDy = Math.abs(nextPoint.y - target.point.y);
    fLengths[candidate] = length + (useBendHeuristic ? candidateDx + candidateDy : 0);
    fBends[candidate] = bends + (useBendHeuristic ? minimumBends(
      candidateDx,
      candidateDy,
      orientation === 1 ? "H" : "V",
      options.targetOrientation
    ) : 0);
    predecessors[candidate] = current;
    depths[candidate] = depths[current] + 1;
    const parent2 = predecessors[current];
    const parent3 = parent2 >= 0 ? predecessors[parent2] : -1;
    ancestor4[candidate] = parent3 >= 0 ? predecessors[parent3] : -1;
    workspace.setBest(index, candidate);
    heapPush(candidate);
  }, "relaxArc");
  while (heapSize > 0) {
    const next = heapRoot;
    if (bestGoalCost && (fLengths[next] - bestGoalCost[0] || fBends[next] - bestGoalCost[1] || gBoundaryTransitions[next] - bestGoalCost[2] || endpointCandidateRank - bestGoalCost[3]) > 0) {
      break;
    }
    const current = heapPop();
    if (best[stateVertices[current] * 3 + orientations[current]] !== current) {
      continue;
    }
    if (expandedThisSearch >= edgeCap || invocationStart + expandedThisSearch >= invocationCap) {
      if (bestGoalState >= 0 && bestGoalCost) {
        if (metrics && options.recordOutcome !== false) {
          metrics.routesFound++;
        }
        commitExpandedStates();
        return reconstruct(bestGoalState, stateVertices, predecessors, bestGoalCost, vertexAt);
      }
      commitExpandedStates();
      const searchStateScope = invocationStart + expandedThisSearch >= invocationCap ? "invocation" : "edge";
      throw new GridRoutingResourceLimitError(
        "search_state_cap",
        "Grid routing search-state cap exceeded",
        searchStateScope
      );
    }
    expandedThisSearch++;
    if (stateVertices[current] === targetId) {
      considerGoal(current);
      continue;
    }
    const vertexId = stateVertices[current];
    const currentPoint = vertexAt(vertexId).point;
    const compactArcs = topology.getSearchArcs?.(vertexId) ?? topology.searchAdjacencyByVertex?.[vertexId];
    if (compactArcs) {
      for (const arc of compactArcs) {
        relaxArc(
          current,
          currentPoint,
          arc.to,
          arc.orientationOrdinal,
          arc.length,
          arc.boundaryTransitions
        );
      }
    } else {
      for (const arc of topology.adjacencyByVertex?.[vertexId] ?? topology.adjacency.get(vertexId) ?? []) {
        relaxArc(
          current,
          currentPoint,
          arc.to,
          orientationOrdinal(arc.orientation),
          arc.length,
          arc.kind === "portal" ? 1 : 0
        );
      }
    }
    if (metrics) {
      metrics.maxOpenSet = Math.max(metrics.maxOpenSet, heapSize);
    }
  }
  if (bestGoalState < 0 || !bestGoalCost) {
    commitExpandedStates();
    if (metrics && options.recordOutcome !== false) {
      metrics.routesImpossible++;
    }
    return void 0;
  }
  if (metrics && options.recordOutcome !== false) {
    metrics.routesFound++;
  }
  commitExpandedStates();
  return reconstruct(bestGoalState, stateVertices, predecessors, bestGoalCost, vertexAt);
}
__name(search, "search");
function findShortestRoute(topology, sourceId, targetId, options = {}) {
  return search(topology, sourceId, targetId, options);
}
__name(findShortestRoute, "findShortestRoute");

// src/rendering-util/layout-algorithms/grid/routerSparse.ts
var ROUTER_DEBUG_KEY = "grid-router";
function recordFallback(context, reason, edgeId, containerId, searchStateScope) {
  if (context.metrics) {
    context.metrics.resourceLimitFallbacks++;
    context.metrics.fallbackReasons[reason]++;
  }
  log.debug(ROUTER_DEBUG_KEY, "GRID_ROUTING_RESOURCE_FALLBACK", {
    edgeId,
    containerId,
    reason
  });
  if (reason === "search_state_cap" && searchStateScope === "invocation" && !context.searchBudgetWarningEmitted) {
    context.searchBudgetWarningEmitted = true;
    log.warn(ROUTER_DEBUG_KEY, "GRID_ROUTING_INVOCATION_SEARCH_BUDGET_EXHAUSTED", {
      edgeId,
      containerId,
      expandedStates: context.searchBudget.expandedStates
    });
  }
}
__name(recordFallback, "recordFallback");
function runValidatedFallback({
  context,
  reason,
  edgeId,
  containerId,
  searchStateScope,
  route,
  isValid,
  includeContainerIdInError
}) {
  const fallback = route();
  recordFallback(context, reason, edgeId, containerId, searchStateScope);
  if (isValid(fallback)) {
    return fallback;
  }
  if (context.metrics) {
    context.metrics.fallbackValidationFailures++;
  }
  throw gridError("GRID_ROUTE_NOT_FOUND", `Invalid legacy fallback for "${edgeId}"`, {
    edgeId,
    ...includeContainerIdInError ? { containerId } : {},
    reason
  });
}
__name(runValidatedFallback, "runValidatedFallback");
function sparseSameContainerRoute(plan, sources, targets, source, target, legacyRoute, result, context, searchWorkspace, overlayScratch, options, pairRoutes, occupied) {
  const fallbackReason = context.fallbackContainers.get(plan.lcaContainerId);
  if (fallbackReason) {
    return runValidatedFallback({
      context,
      reason: fallbackReason,
      edgeId: plan.edge.id,
      containerId: plan.lcaContainerId,
      route: legacyRoute,
      isValid: /* @__PURE__ */ __name((legacy) => validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result) && (plan.bundleSize <= 1 || routeSatisfiesPairConstraints(legacy, pairRoutes)), "isValid")
    });
  }
  const topology = context.topologies.get(plan.lcaContainerId);
  if (!topology) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing routing topology "${plan.lcaContainerId}"`);
  }
  if (sources.length === 0 || targets.length === 0) {
    if (context.metrics) {
      context.metrics.routesImpossible++;
    }
    throw gridError(
      "GRID_ROUTE_NOT_FOUND",
      plan.bundleSize > 1 ? `No distinct lane route for "${plan.edge.id}"` : `No legal endpoint candidates for "${plan.edge.id}"`,
      { edgeId: plan.edge.id }
    );
  }
  let best;
  let searchCap;
  const pairs = sources.flatMap(
    (sourceCandidate) => targets.map((targetCandidate) => {
      const pairRank = sourceCandidate.rank * targets.length + targetCandidate.rank;
      const [length, bends] = endpointPairLowerBound(sourceCandidate, targetCandidate);
      const lowerCost = [length, bends, 0, pairRank];
      return { sourceCandidate, targetCandidate, pairRank, lowerCost };
    })
  ).sort(
    (a, b) => compareTupleCost(a.lowerCost, b.lowerCost) || sideOrder(a.sourceCandidate.side) - sideOrder(b.sourceCandidate.side) || sideOrder(a.targetCandidate.side) - sideOrder(b.targetCandidate.side)
  );
  const searchPairs = /* @__PURE__ */ __name((avoidOccupied2, mode = "all") => {
    const arcAllowed = plan.bundleSize > 1 || avoidOccupied2 ? (from, to) => (plan.bundleSize <= 1 || pairArcAllowed(from, to, pairRoutes)) && !(avoidOccupied2 && occupied.index.conflictsWithArc(from, to, occupied.pairKey)) : void 0;
    for (const { sourceCandidate, targetCandidate, pairRank, lowerCost } of pairs) {
      if (mode === "preferred" && pairRank !== 0) {
        continue;
      }
      if (mode === "assigned-side" && (sourceCandidate.onAssignedSide === false || targetCandidate.onAssignedSide === false)) {
        continue;
      }
      if (best && compareTupleCost(best.result.cost, lowerCost) <= 0) {
        break;
      }
      try {
        assertSearchBudgetAvailable({
          metrics: context.metrics,
          caps: options.searchCaps,
          budget: context.searchBudget
        });
        const overlay = buildEndpointRoutingOverlay(
          topology,
          sourceCandidate.connect,
          targetCandidate.connect,
          context.metrics,
          overlayScratch,
          plan.bundleSize > 1 && (sourceCandidate.connect.x === targetCandidate.connect.x || sourceCandidate.connect.y === targetCandidate.connect.y) ? [
            {
              x: (sourceCandidate.connect.x + targetCandidate.connect.x) / 2,
              y: (sourceCandidate.connect.y + targetCandidate.connect.y) / 2
            }
          ] : []
        );
        const liveEstimatedBytes = context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes;
        if (liveEstimatedBytes > (options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES)) {
          throw new GridRoutingResourceLimitError(
            "estimated_memory_cap",
            "Grid routing estimated_memory_cap exceeded"
          );
        }
        if (context.metrics) {
          context.metrics.estimatedBytes = Math.max(
            context.metrics.estimatedBytes,
            liveEstimatedBytes
          );
        }
        const sourceId = overlay.pointVertexIds.get(routingPointKey(sourceCandidate.connect));
        const targetId = overlay.pointVertexIds.get(routingPointKey(targetCandidate.connect));
        if (sourceId === void 0 || targetId === void 0) {
          throw gridError(
            "GRID_ROUTE_NOT_FOUND",
            `Endpoint projection is missing from the routing overlay for "${plan.edge.id}"`,
            {
              edgeId: plan.edge.id,
              containerId: plan.lcaContainerId,
              source: sourceCandidate.connect,
              target: targetCandidate.connect
            }
          );
        }
        const sourceOrientation = sourceCandidate.side === "left" || sourceCandidate.side === "right" ? "H" : "V";
        const targetOrientation = targetCandidate.side === "left" || targetCandidate.side === "right" ? "H" : "V";
        const resultForPair = findShortestRoute(overlay, sourceId, targetId, {
          metrics: context.metrics,
          caps: {
            ...options.searchCaps,
            maxEstimatedBytes: options.searchCaps?.maxEstimatedBytes ?? options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES
          },
          endpointCandidateRank: pairRank,
          recordOutcome: false,
          budget: context.searchBudget,
          initialOrientation: sourceOrientation,
          initialLength: TERMINAL_APPROACH_PX,
          targetOrientation,
          targetLength: TERMINAL_APPROACH_PX,
          topologyValidated: true,
          workspace: searchWorkspace,
          estimatedBytesBase: liveEstimatedBytes,
          arcAllowed
        });
        if (!resultForPair) {
          continue;
        }
        const points = normalizePolyline([
          sourceCandidate.port,
          ...resultForPair.points,
          targetCandidate.port
        ]).points;
        if (!validateSameContainerRoute(points, source, target, plan.lcaContainerId, result)) {
          continue;
        }
        if (plan.bundleSize > 1 && !routeSatisfiesPairConstraints(points, pairRoutes)) {
          continue;
        }
        if (avoidOccupied2 && occupied.index.conflictsWithRoute(points, occupied.pairKey)) {
          continue;
        }
        if (!best || compareTupleCost(resultForPair.cost, best.result.cost) < 0) {
          best = { result: resultForPair, points };
          searchCap = void 0;
        }
      } catch (error) {
        if (!(error instanceof GridRoutingResourceLimitError)) {
          throw error;
        }
        if (best) {
          break;
        }
        searchCap = error;
        break;
      }
    }
  }, "searchPairs");
  const avoidOccupied = occupied !== void 0 && occupied.index.size > 0;
  if (occupied?.prioritizeEndpointCandidates) {
    searchPairs(avoidOccupied, "preferred");
    searchPairs(avoidOccupied, "assigned-side");
  }
  if (!best) {
    searchPairs(avoidOccupied);
  }
  if (!best && !searchCap && occupied !== void 0 && occupied.index.size > 0) {
    searchPairs(false);
  }
  if (searchCap) {
    return runValidatedFallback({
      context,
      reason: searchCap.reason,
      edgeId: plan.edge.id,
      containerId: plan.lcaContainerId,
      searchStateScope: searchCap.searchStateScope,
      route: legacyRoute,
      isValid: /* @__PURE__ */ __name((legacy) => validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result) && (plan.bundleSize <= 1 || routeSatisfiesPairConstraints(legacy, pairRoutes)), "isValid")
    });
  }
  if (!best) {
    if (context.metrics) {
      context.metrics.routesImpossible++;
    }
    throw gridError(
      "GRID_ROUTE_NOT_FOUND",
      plan.bundleSize > 1 ? `No distinct lane route for "${plan.edge.id}"` : `No cell-aware route for "${plan.edge.id}"`,
      {
        edgeId: plan.edge.id
      }
    );
  }
  if (options.onDualRouteComparison) {
    const legacy = legacyRoute();
    const sparseNormalized = normalizePolyline(best.points);
    const legacyNormalized = normalizePolyline(legacy);
    options.onDualRouteComparison({
      edgeId: plan.edge.id,
      sparse: {
        valid: true,
        length: manhattanLength(sparseNormalized.points),
        bends: sparseNormalized.bends
      },
      legacy: {
        valid: validateSameContainerRoute(legacy, source, target, plan.lcaContainerId, result),
        length: manhattanLength(legacyNormalized.points),
        bends: legacyNormalized.bends
      }
    });
  }
  return best.points;
}
__name(sparseSameContainerRoute, "sparseSameContainerRoute");
function selfLoopAttachments(owner, side, index) {
  const interval = sideInterval(owner, side);
  if (!interval || interval.high - interval.low < SELF_LOOP_PORT_GAP) {
    return void 0;
  }
  const rect = rectForNode(owner);
  const center = (interval.low + interval.high) / 2;
  const portOffset = index * SELF_LOOP_PORT_OFFSET_STEP;
  const coordinates = [
    center - SELF_LOOP_PORT_GAP / 2 - portOffset,
    center + SELF_LOOP_PORT_GAP / 2 + portOffset
  ];
  if (coordinates[0] < interval.low || coordinates[1] > interval.high) {
    return void 0;
  }
  const candidate = /* @__PURE__ */ __name((coordinate) => {
    const port = side === "left" || side === "right" ? { x: side === "left" ? rect.left : rect.right, y: coordinate } : { x: coordinate, y: side === "top" ? rect.top : rect.bottom };
    return {
      ownerId: owner.id,
      side,
      port,
      connect: {
        x: port.x + (side === "left" ? -TERMINAL_APPROACH_PX : side === "right" ? TERMINAL_APPROACH_PX : 0),
        y: port.y + (side === "top" ? -TERMINAL_APPROACH_PX : side === "bottom" ? TERMINAL_APPROACH_PX : 0)
      },
      rank: 0
    };
  }, "candidate");
  return { start: candidate(coordinates[0]), target: candidate(coordinates[1]) };
}
__name(selfLoopAttachments, "selfLoopAttachments");
function sparseSelfLoopRoute(plan, owner, result, context, searchWorkspace, overlayScratch, ownerSideCounts, selfLoopCounts, pairRoutes, options) {
  const containerId = owner.parentId ?? ROOT_CONTAINER_ID;
  const labelRequirement = result.labelRequirements.selfLoops.get(plan.edge.id);
  const fallbackReason = context.fallbackContainers.get(containerId);
  const legacyRoute = /* @__PURE__ */ __name(() => routeObstacleClearSelfLoop(
    owner,
    ownerSideCounts,
    selfLoopCounts,
    result,
    labelRequirement,
    context.metrics
  ), "legacyRoute");
  if (fallbackReason) {
    const fallback = runValidatedFallback({
      context,
      reason: fallbackReason,
      edgeId: plan.edge.id,
      containerId,
      route: legacyRoute,
      isValid: /* @__PURE__ */ __name((legacy) => validateSameContainerRoute(legacy.points, owner, owner, containerId, result) && routeSatisfiesPairConstraints(legacy.points, pairRoutes), "isValid")
    });
    if (labelRequirement && context.metrics) {
      context.metrics.labelAwareSelfLoopsCommitted++;
    }
    return fallback;
  }
  const topology = context.topologies.get(containerId);
  if (!topology || !overlayScratch) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing routing topology "${containerId}"`);
  }
  const orderedSides = orderedSelfLoopSides(owner, ownerSideCounts, selfLoopCounts);
  if (labelRequirement) {
    for (const side of orderedSides) {
      const index = selfLoopCounts.get(`${owner.id}:${side}`) ?? 0;
      const rect = rectForNode(owner);
      const demandCoord = side === "left" || side === "right" ? rect.cy : rect.cx;
      const candidates = labelAwareSelfLoopCandidates(
        owner,
        side,
        index,
        demandCoord,
        labelRequirement
      );
      if (context.metrics) {
        context.metrics.labelAwareSelfLoopCandidates += candidates.length;
      }
      for (const points of candidates) {
        if (validateSameContainerRoute(points, owner, owner, containerId, result) && routeSatisfiesPairConstraints(points, pairRoutes)) {
          if (context.metrics) {
            context.metrics.labelAwareSelfLoopsCommitted++;
          }
          return { points, side, index };
        }
      }
    }
    if (context.metrics) {
      context.metrics.labelAwareSelfLoopFallbacks++;
    }
  }
  for (const side of orderedSides) {
    const index = selfLoopCounts.get(`${owner.id}:${side}`) ?? 0;
    const attachments = selfLoopAttachments(owner, side, index);
    if (!attachments) {
      continue;
    }
    const { start, target } = attachments;
    try {
      assertSearchBudgetAvailable({
        metrics: context.metrics,
        caps: options.searchCaps,
        budget: context.searchBudget
      });
      const overlay = buildEndpointRoutingOverlay(
        topology,
        start.connect,
        target.connect,
        context.metrics,
        overlayScratch,
        [
          {
            x: (start.connect.x + target.connect.x) / 2,
            y: (start.connect.y + target.connect.y) / 2
          }
        ]
      );
      const sourceId = overlay.pointVertexIds.get(routingPointKey(start.connect));
      const targetId = overlay.pointVertexIds.get(routingPointKey(target.connect));
      if (sourceId === void 0 || targetId === void 0) {
        throw gridError(
          "GRID_ROUTE_NOT_FOUND",
          `Self-loop endpoint projection is missing from the routing overlay for "${plan.edge.id}"`,
          {
            edgeId: plan.edge.id,
            containerId,
            source: start.connect,
            target: target.connect,
            side
          }
        );
      }
      const orientation = side === "left" || side === "right" ? "H" : "V";
      const route = findShortestRoute(overlay, sourceId, targetId, {
        metrics: context.metrics,
        caps: {
          ...options.searchCaps,
          maxEstimatedBytes: options.searchCaps?.maxEstimatedBytes ?? options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES
        },
        recordOutcome: false,
        budget: context.searchBudget,
        initialOrientation: orientation,
        initialSide: side,
        initialLength: TERMINAL_APPROACH_PX,
        targetOrientation: orientation,
        targetSide: side,
        targetLength: TERMINAL_APPROACH_PX,
        topologyValidated: true,
        workspace: searchWorkspace,
        estimatedBytesBase: context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes,
        arcAllowed: /* @__PURE__ */ __name((from, to) => pairArcAllowed(from, to, pairRoutes), "arcAllowed")
      });
      if (!route) {
        continue;
      }
      const points = normalizePolyline([start.port, ...route.points, target.port]).points;
      if (validateSameContainerRoute(points, owner, owner, containerId, result) && routeSatisfiesPairConstraints(points, pairRoutes)) {
        return {
          points,
          side,
          index
        };
      }
    } catch (error) {
      if (!(error instanceof GridRoutingResourceLimitError)) {
        throw error;
      }
      const fallback = runValidatedFallback({
        context,
        reason: error.reason,
        edgeId: plan.edge.id,
        containerId,
        searchStateScope: error.searchStateScope,
        route: legacyRoute,
        isValid: /* @__PURE__ */ __name((legacy) => validateSameContainerRoute(legacy.points, owner, owner, containerId, result) && routeSatisfiesPairConstraints(legacy.points, pairRoutes), "isValid")
      });
      if (labelRequirement && context.metrics) {
        context.metrics.labelAwareSelfLoopsCommitted++;
      }
      return fallback;
    }
  }
  if (context.metrics) {
    context.metrics.routesImpossible++;
  }
  throw gridError("GRID_ROUTE_NOT_FOUND", `No distinct self-loop route for "${plan.edge.id}"`, {
    edgeId: plan.edge.id,
    nodeId: owner.id
  });
}
__name(sparseSelfLoopRoute, "sparseSelfLoopRoute");
function sparseContainerSegment(edgeId, containerId, start, end, legacyRoute, result, context, searchWorkspace, overlayScratch, options, pairRoutes = [], endAlternatives = () => [], startAlternatives = () => [], allowSharedPairCorridors = false, occupied) {
  const fallbackReason = context.fallbackContainers.get(containerId);
  if (fallbackReason) {
    return runValidatedFallback({
      context,
      reason: fallbackReason,
      edgeId,
      containerId,
      route: legacyRoute,
      isValid: /* @__PURE__ */ __name((legacy) => validateContainerSegment(legacy, start.ownerId, end.ownerId, containerId, result) && routeSatisfiesPairConstraints(legacy, pairRoutes), "isValid"),
      includeContainerIdInError: true
    });
  }
  const topology = context.topologies.get(containerId);
  if (!topology || !overlayScratch) {
    throw gridError("GRID_ROUTE_NOT_FOUND", `Missing routing topology "${containerId}"`);
  }
  const attempts = [{ start, end, select: [] }];
  let alternativesAdded = false;
  const appendAlternatives = /* @__PURE__ */ __name(() => {
    if (alternativesAdded) {
      return;
    }
    alternativesAdded = true;
    const starts = startAlternatives();
    const ends = endAlternatives();
    attempts.push(
      ...ends.map((alternative) => ({
        start,
        end: alternative.attachment,
        select: [alternative.select]
      })),
      ...starts.map((alternative) => ({
        start: alternative.attachment,
        end,
        select: [alternative.select]
      })),
      ...starts.flatMap(
        (startAlternative) => ends.map((endAlternative) => ({
          start: startAlternative.attachment,
          end: endAlternative.attachment,
          select: [startAlternative.select, endAlternative.select]
        }))
      )
    );
  }, "appendAlternatives");
  const passes = occupied !== void 0 && occupied.index.size > 0 ? [true, false] : [false];
  try {
    for (const avoidOccupied of passes) {
      for (const [attemptIndex, attempt] of attempts.entries()) {
        const attemptedStart = attempt.start;
        const attemptedEnd = attempt.end;
        if (attemptIndex > 0 && context.metrics) {
          context.metrics.hierarchyPortalAlternativeAttempts++;
        }
        const aligned = areExactlyAxisAligned(attemptedStart.connect, attemptedEnd.connect);
        if (aligned) {
          const direct = normalizePolyline([
            attemptedStart.port,
            attemptedStart.connect,
            attemptedEnd.connect,
            attemptedEnd.port
          ]).points;
          if (validateContainerSegment(
            direct,
            attemptedStart.ownerId,
            attemptedEnd.ownerId,
            containerId,
            result
          ) && routeSatisfiesPairConstraints(direct, pairRoutes) && !(avoidOccupied && occupied.index.conflictsWithRoute(direct, occupied.pairKey))) {
            for (const select of attempt.select) {
              select();
            }
            if (attemptIndex > 0 && context.metrics) {
              context.metrics.hierarchyPortalAlternativeSelections++;
            }
            return direct;
          }
        }
        assertSearchBudgetAvailable({
          metrics: context.metrics,
          caps: options.searchCaps,
          budget: context.searchBudget
        });
        const overlay = buildEndpointRoutingOverlay(
          topology,
          attemptedStart.connect,
          attemptedEnd.connect,
          context.metrics,
          overlayScratch
        );
        const liveEstimatedBytes = context.baseEstimatedBytes + overlay.estimatedBytes - topology.estimatedBytes;
        if (liveEstimatedBytes > (options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES)) {
          throw new GridRoutingResourceLimitError(
            "estimated_memory_cap",
            "Grid routing estimated_memory_cap exceeded"
          );
        }
        const sourceId = overlay.pointVertexIds.get(routingPointKey(attemptedStart.connect));
        const targetId = overlay.pointVertexIds.get(routingPointKey(attemptedEnd.connect));
        if (sourceId === void 0 || targetId === void 0) {
          if (attemptIndex === 0) {
            appendAlternatives();
          }
          continue;
        }
        const route = findShortestRoute(overlay, sourceId, targetId, {
          metrics: context.metrics,
          caps: {
            ...options.searchCaps,
            maxEstimatedBytes: options.searchCaps?.maxEstimatedBytes ?? options.topologyCaps?.maxEstimatedBytes ?? DEFAULT_MAX_ROUTING_ESTIMATED_BYTES
          },
          recordOutcome: false,
          budget: context.searchBudget,
          initialOrientation: attemptedStart.side === "left" || attemptedStart.side === "right" ? "H" : "V",
          initialSide: attemptedStart.side,
          initialLength: Math.abs(attemptedStart.port.x - attemptedStart.connect.x) + Math.abs(attemptedStart.port.y - attemptedStart.connect.y),
          targetOrientation: attemptedEnd.side === "left" || attemptedEnd.side === "right" ? "H" : "V",
          targetSide: attemptedEnd.side,
          targetLength: Math.abs(attemptedEnd.port.x - attemptedEnd.connect.x) + Math.abs(attemptedEnd.port.y - attemptedEnd.connect.y),
          topologyValidated: true,
          workspace: searchWorkspace,
          estimatedBytesBase: liveEstimatedBytes,
          arcAllowed: pairRoutes.length > 0 || avoidOccupied ? (from, to) => (pairRoutes.length === 0 || pairArcAllowed(from, to, pairRoutes)) && !(avoidOccupied && occupied.index.conflictsWithArc(from, to, occupied.pairKey)) : void 0
        });
        if (!route) {
          if (attemptIndex === 0) {
            appendAlternatives();
          }
          continue;
        }
        const points = normalizePolyline([
          attemptedStart.port,
          ...route.points,
          attemptedEnd.port
        ]).points;
        if (!validateContainerSegment(
          points,
          attemptedStart.ownerId,
          attemptedEnd.ownerId,
          containerId,
          result
        ) || !routeSatisfiesPairConstraints(points, pairRoutes) || avoidOccupied && occupied.index.conflictsWithRoute(points, occupied.pairKey)) {
          if (attemptIndex === 0) {
            appendAlternatives();
          }
          continue;
        }
        for (const select of attempt.select) {
          select();
        }
        if (attemptIndex > 0 && context.metrics) {
          context.metrics.hierarchyPortalAlternativeSelections++;
        }
        return points;
      }
    }
  } catch (error) {
    if (!(error instanceof GridRoutingResourceLimitError)) {
      throw error;
    }
    return runValidatedFallback({
      context,
      reason: error.reason,
      edgeId,
      containerId,
      searchStateScope: error.searchStateScope,
      route: legacyRoute,
      isValid: /* @__PURE__ */ __name((legacy) => validateContainerSegment(legacy, start.ownerId, end.ownerId, containerId, result) && routeSatisfiesPairConstraints(legacy, pairRoutes), "isValid"),
      includeContainerIdInError: true
    });
  }
  const compatibility = legacyRoute();
  if (validateContainerSegment(compatibility, start.ownerId, end.ownerId, containerId, result) && (routeSatisfiesPairConstraints(compatibility, pairRoutes) || allowSharedPairCorridors && routeHasDistinctPairPorts(compatibility, pairRoutes))) {
    if (context.metrics) {
      context.metrics.compatibilitySegments++;
      context.metrics.compatibilityRecoveries++;
    }
    return compatibility;
  }
  throw gridError(
    "GRID_ROUTE_NOT_FOUND",
    `No hierarchy route for "${edgeId}" in "${containerId}" from ${routingPointKey(start.connect)} to ${routingPointKey(end.connect)}`,
    { edgeId, containerId }
  );
}
__name(sparseContainerSegment, "sparseContainerSegment");

// src/rendering-util/layout-algorithms/grid/routerSession.ts
function createBundleCheckpoint(pairPlans, pairRoutes, pairedPortals, demandCoords, instrumentedRoutes, metrics, routeOccupancy) {
  const pairKey = pairPlans[0].pairKey;
  const committedPairRoutes = pairRoutes.get(pairKey);
  const demandKeys = [
    ...new Set(
      pairPlans.flatMap(
        (plan) => [...plan.source.chain, ...plan.target.chain].map(({ demandKey }) => demandKey)
      )
    )
  ];
  const bundlePairedPortals = /* @__PURE__ */ new Map();
  const bundleDemandCoords = /* @__PURE__ */ new Map();
  for (const demandKey of demandKeys) {
    const portal = pairedPortals.get(demandKey);
    if (portal) {
      bundlePairedPortals.set(demandKey, portal);
    }
    const coordinate = demandCoords.get(demandKey);
    if (coordinate !== void 0) {
      bundleDemandCoords.set(demandKey, coordinate);
    }
  }
  const occupancyIndex = routeOccupancy.get(pairPlans[0].lcaContainerId);
  return {
    pairKey,
    occupancy: occupancyIndex ? { index: occupancyIndex, size: occupancyIndex.size } : void 0,
    pairRoutes: committedPairRoutes ? [...committedPairRoutes] : void 0,
    demandKeys,
    pairedPortals: bundlePairedPortals,
    demandCoords: bundleDemandCoords,
    edges: pairPlans.map(({ edge }) => ({
      edge,
      points: edge.points,
      curve: edge.curve,
      cornerRadius: edge.cornerRadius
    })),
    instrumentedRoutesLength: instrumentedRoutes?.length,
    metrics: metrics ? createGridRoutingInstrumentationCheckpoint(metrics) : void 0
  };
}
__name(createBundleCheckpoint, "createBundleCheckpoint");
function restoreBundleCheckpoint(checkpoint, pairRoutes, pairedPortals, demandCoords, instrumentedRoutes, metrics) {
  checkpoint.occupancy?.index.truncate(checkpoint.occupancy.size);
  if (checkpoint.pairRoutes) {
    pairRoutes.set(checkpoint.pairKey, [...checkpoint.pairRoutes]);
  } else {
    pairRoutes.delete(checkpoint.pairKey);
  }
  for (const demandKey of checkpoint.demandKeys) {
    const portal = checkpoint.pairedPortals.get(demandKey);
    if (portal) {
      pairedPortals.set(demandKey, portal);
    } else {
      pairedPortals.delete(demandKey);
    }
    const coordinate = checkpoint.demandCoords.get(demandKey);
    if (coordinate !== void 0) {
      demandCoords.set(demandKey, coordinate);
    } else {
      demandCoords.delete(demandKey);
    }
  }
  for (const edgeCheckpoint of checkpoint.edges) {
    edgeCheckpoint.edge.points = edgeCheckpoint.points;
    edgeCheckpoint.edge.curve = edgeCheckpoint.curve;
    edgeCheckpoint.edge.cornerRadius = edgeCheckpoint.cornerRadius;
  }
  if (instrumentedRoutes && checkpoint.instrumentedRoutesLength !== void 0) {
    instrumentedRoutes.length = checkpoint.instrumentedRoutesLength;
  }
  if (metrics && checkpoint.metrics) {
    restoreGridRoutingInstrumentationCheckpoint(metrics, checkpoint.metrics);
  }
}
__name(restoreBundleCheckpoint, "restoreBundleCheckpoint");
var GridEdgeRoutingSession = class {
  constructor(layout, result, metrics, options) {
    this.layout = layout;
    this.result = result;
    this.metrics = metrics;
    this.options = options;
    this.searchWorkspace = new RouterSearchWorkspace();
    this.pairedPortals = /* @__PURE__ */ new Map();
    this.ownerSideCounts = /* @__PURE__ */ new Map();
    this.selfLoopCounts = /* @__PURE__ */ new Map();
    this.pairRoutes = /* @__PURE__ */ new Map();
    this.routed = false;
  }
  static {
    __name(this, "GridEdgeRoutingSession");
  }
  route() {
    if (this.routed) {
      throw new Error("Grid edge routing session can only be run once");
    }
    this.routed = true;
    this.prepare();
    const plansByPair = /* @__PURE__ */ new Map();
    for (const plan of this.prepared.orderedPlans) {
      const pairPlans = plansByPair.get(plan.pairKey) ?? [];
      pairPlans.push(plan);
      plansByPair.set(plan.pairKey, pairPlans);
    }
    for (const pairPlans of plansByPair.values()) {
      this.routeBundle(pairPlans);
    }
  }
  prepare() {
    rootContainerMeta(this.result);
    this.prepared = prepareEdgeRoutes(this.layout, this.result);
    this.modes = prepareRoutingModes(this.prepared, this.result, this.metrics, this.options);
    this.routingContext = buildRoutingContext(
      this.modes.routedContainerIds,
      this.result,
      this.metrics,
      this.options
    );
    this.endpointOverlayScratch = new Map(
      [...this.routingContext.topologies].map(([containerId, topology]) => [
        containerId,
        new EndpointOverlayScratch(topology)
      ])
    );
    this.instrumentedRoutes = this.metrics ? [] : void 0;
    const countedDemandKeys = /* @__PURE__ */ new Set();
    for (const plan of this.prepared.orderedPlans) {
      if (plan.edge.start === plan.edge.end) {
        continue;
      }
      for (const entry of [...plan.source.chain, ...plan.target.chain]) {
        if (countedDemandKeys.has(entry.demandKey)) {
          continue;
        }
        countedDemandKeys.add(entry.demandKey);
        const key = ownerSideKey(entry.ownerId, entry.side);
        this.ownerSideCounts.set(key, (this.ownerSideCounts.get(key) ?? 0) + 1);
      }
    }
  }
  pairedPortal(entry) {
    const existing = this.pairedPortals.get(entry.demandKey);
    if (existing) {
      return existing;
    }
    const owner = this.result.forest.nodeById.get(entry.ownerId);
    if (!owner?.isGroup) {
      throw gridError("GRID_ROUTE_NOT_FOUND", `Missing portal owner "${entry.ownerId}"`);
    }
    const rect = routerRect(owner);
    const coordinate = this.prepared.demandCoords.get(entry.demandKey) ?? (entry.side === "left" || entry.side === "right" ? (rect.top + rect.bottom) / 2 : (rect.left + rect.right) / 2);
    const range = derivePortalRanges(entry.ownerId, rect, owner.groupTitleRect).find(
      ({ side }) => side === entry.side
    );
    if (!range) {
      throw gridError(
        "GRID_ROUTE_NOT_FOUND",
        `No legal ${entry.side} portal for "${entry.ownerId}"`
      );
    }
    const portal = buildPairedPortal(
      entry.ownerId,
      rect,
      owner.groupTitleRect ? { ...owner.groupTitleRect } : void 0,
      entry.side,
      clamp(coordinate, range.low, range.high)
    );
    this.pairedPortals.set(entry.demandKey, portal);
    if (this.metrics) {
      this.metrics.hierarchyPortalPairs++;
      this.metrics.hierarchyPortalTransitionLength += portal.transition.length;
    }
    return portal;
  }
  alternativePairedPortals(entry, interior = true) {
    const selected = this.pairedPortal(entry);
    const owner = this.result.forest.nodeById.get(entry.ownerId);
    if (!owner?.isGroup) {
      return [];
    }
    const rect = routerRect(owner);
    const range = derivePortalRanges(entry.ownerId, rect, owner.groupTitleRect).find(
      ({ side }) => side === entry.side
    );
    if (!range) {
      return [];
    }
    const container = this.result.containers.get(owner.id);
    const corridors = entry.side === "left" || entry.side === "right" ? container?.horizontalCorridors : container?.verticalCorridors;
    return boundedAlternativePortalCoordinates(
      selected.tangentialCoordinate,
      range.low,
      range.high,
      corridors ?? []
    ).map((coordinate) => {
      const portal = buildPairedPortal(
        entry.ownerId,
        rect,
        owner.groupTitleRect ? { ...owner.groupTitleRect } : void 0,
        entry.side,
        coordinate
      );
      return {
        attachment: portalAttachment(portal, interior),
        select: /* @__PURE__ */ __name(() => {
          this.pairedPortals.set(entry.demandKey, portal);
          this.prepared.demandCoords.set(entry.demandKey, coordinate);
        }, "select")
      };
    });
  }
  itemSegmentAttachment(entry, containerId) {
    return {
      ownerId: entry.ownerId,
      ...itemAttachment(
        entry.ownerId,
        entry.side,
        entry.demandKey,
        containerId,
        this.result,
        this.prepared.demandCoords
      )
    };
  }
  alternativeItemAttachments(plan, entry, containerId) {
    const current = this.itemSegmentAttachment(entry, containerId);
    const owner = this.result.forest.nodeById.get(entry.ownerId);
    if (!owner) {
      return [];
    }
    return ["right", "bottom", "left", "top"].filter((side) => side !== current.side && !(side === "top" && ownerGroupTitle(owner))).map((side) => {
      const interval = sideInterval(owner, side);
      if (!interval) {
        return void 0;
      }
      const rect = rectForNode(owner);
      const center = side === "left" || side === "right" ? rect.cy : rect.cx;
      const coordinate = Math.max(
        interval.low,
        Math.min(interval.high, center + plan.laneOffset)
      );
      return {
        ownerId: entry.ownerId,
        ...itemAttachment(
          entry.ownerId,
          side,
          entry.demandKey,
          containerId,
          this.result,
          this.prepared.demandCoords,
          coordinate
        )
      };
    }).filter((attachment) => attachment !== void 0).slice(0, 3).map((attachment) => ({
      attachment,
      select: /* @__PURE__ */ __name(() => void 0, "select")
    }));
  }
  routePlan(plan, allowHierarchyRelaxation = true) {
    const result = this.result;
    const routingContext = this.routingContext;
    const searchWorkspace = this.searchWorkspace;
    const endpointOverlayScratch = this.endpointOverlayScratch;
    const demandCoords = this.prepared.demandCoords;
    const ownerSideCounts = this.ownerSideCounts;
    const selfLoopCounts = this.selfLoopCounts;
    const pairRoutes = this.pairRoutes;
    const instrumentedRoutes = this.instrumentedRoutes;
    const metrics = this.metrics;
    const options = this.options;
    const eligibleIds = this.prepared.eligibleIds;
    const endpointCandidatesByEdge = this.prepared.endpointCandidatesByEdge;
    const compatibilityFastRoutes = this.modes.compatibilityFastRoutes;
    const sparseHierarchyIds = this.modes.sparseHierarchyIds;
    const sparseLcaIds = this.modes.sparseLcaIds;
    const edge = plan.edge;
    const sourceNode = edge.start ? result.forest.nodeById.get(edge.start) : void 0;
    const targetNode = edge.end ? result.forest.nodeById.get(edge.end) : void 0;
    if (!sourceNode || !targetNode) {
      throw gridError("GRID_MISSING_ENDPOINT", `Missing endpoint for edge "${edge.id}"`, {
        edgeId: edge.id
      });
    }
    if (sourceNode.id === targetNode.id) {
      const committedPairRoutes2 = pairRoutes.get(plan.pairKey) ?? [];
      const { points: points2, side, index } = sparseSelfLoopRoute(
        plan,
        sourceNode,
        result,
        routingContext,
        searchWorkspace,
        endpointOverlayScratch.get(sourceNode.parentId ?? ROOT_CONTAINER_ID),
        ownerSideCounts,
        selfLoopCounts,
        committedPairRoutes2,
        options
      );
      const countKey = `${sourceNode.id}:${side}`;
      selfLoopCounts.set(countKey, index + 1);
      edge.points = points2;
      edge.curve = result.config.curve;
      edge.cornerRadius = result.config.edgeCornerRadius;
      committedPairRoutes2.push(points2);
      pairRoutes.set(plan.pairKey, committedPairRoutes2);
      if (metrics && instrumentedRoutes) {
        recordGridRoute(metrics, edge.id, points2, instrumentedRoutes, 0, plan.laneOffset);
        instrumentedRoutes.push(points2);
      }
      return;
    }
    const sourceFinal = plan.source.chain[plan.source.chain.length - 1];
    const targetFinal = plan.target.chain[plan.target.chain.length - 1];
    const useSparseLca = sparseLcaIds.has(edge.id);
    const compatibilityLca = useSparseLca ? void 0 : compatibilityLcaAttachments(plan, result, demandCoords);
    const lcaStart = compatibilityLca ? compatibilityLca.start : plan.source.finalKind === "boundary" ? groupBoundaryEndpointAttachment(
      sourceFinal.ownerId,
      sourceFinal.side,
      sourceFinal.demandKey,
      result,
      demandCoords
    ) : plan.source.chain.length > 1 ? portalAttachment(this.pairedPortal(sourceFinal), false) : this.itemSegmentAttachment(sourceFinal, plan.lcaContainerId);
    const lcaEnd = compatibilityLca ? compatibilityLca.end : plan.target.finalKind === "boundary" ? groupBoundaryEndpointAttachment(
      targetFinal.ownerId,
      targetFinal.side,
      targetFinal.demandKey,
      result,
      demandCoords
    ) : plan.target.chain.length > 1 ? portalAttachment(this.pairedPortal(targetFinal), false) : this.itemSegmentAttachment(targetFinal, plan.lcaContainerId);
    let legacyLcaPoints;
    const legacyRoute = /* @__PURE__ */ __name(() => legacyLcaPoints ??= routeWithinContainer(
      plan.lcaContainerId,
      result,
      lcaStart,
      lcaEnd,
      plan.laneIndex
    ), "legacyRoute");
    const compatibilityFastRoute = compatibilityFastRoutes.get(edge.id);
    const lcaPoints = compatibilityFastRoute ? (() => {
      if (metrics) {
        metrics.compatibilityFastPaths++;
      }
      return compatibilityFastRoute;
    })() : eligibleIds.has(edge.id) ? sparseSameContainerRoute(
      plan,
      endpointCandidatesByEdge.get(edge.id).sources,
      endpointCandidatesByEdge.get(edge.id).targets,
      sourceNode,
      targetNode,
      legacyRoute,
      result,
      routingContext,
      searchWorkspace,
      endpointOverlayScratch.get(plan.lcaContainerId),
      options,
      pairRoutes.get(plan.pairKey) ?? [],
      {
        index: this.occupancyFor(plan.lcaContainerId),
        pairKey: plan.pairKey,
        prioritizeEndpointCandidates: this.prepared.coordinatedEndpointIds.has(edge.id)
      }
    ) : useSparseLca ? sparseContainerSegment(
      edge.id,
      plan.lcaContainerId,
      lcaStart,
      lcaEnd,
      legacyRoute,
      result,
      routingContext,
      searchWorkspace,
      endpointOverlayScratch.get(plan.lcaContainerId),
      options,
      pairRoutes.get(plan.pairKey) ?? [],
      () => plan.target.finalKind === "item" && plan.target.chain.length > 1 ? this.alternativePairedPortals(targetFinal, false) : [],
      () => plan.source.finalKind === "item" && plan.source.chain.length > 1 ? this.alternativePairedPortals(sourceFinal, false) : [],
      plan.bundleSize > 1,
      this.modes.overlapAvoidanceEnabled ? { index: this.occupancyFor(plan.lcaContainerId), pairKey: plan.pairKey } : void 0
    ) : validatedCompatibilitySegment(
      edge.id,
      plan.lcaContainerId,
      lcaStart,
      lcaEnd,
      legacyRoute,
      result,
      metrics
    );
    const routeHierarchyChain = /* @__PURE__ */ __name((endpoint, chains) => {
      if (!sparseHierarchyIds.has(edge.id)) {
        for (const { containerId, start, end } of compatibilityHierarchyAttachments(
          endpoint,
          result,
          demandCoords
        )) {
          chains.push(
            validatedCompatibilitySegment(
              edge.id,
              containerId,
              start,
              end,
              () => routeWithinContainer(containerId, result, start, end, plan.laneIndex),
              result,
              metrics
            )
          );
        }
        return;
      }
      for (let index = 0; index < endpoint.chain.length - 1; index++) {
        const from = endpoint.chain[index];
        const to = endpoint.chain[index + 1];
        const start = index === 0 ? this.itemSegmentAttachment(from, to.ownerId) : portalAttachment(this.pairedPortal(from), false);
        const end = portalAttachment(this.pairedPortal(to), true);
        chains.push(
          sparseContainerSegment(
            edge.id,
            to.ownerId,
            start,
            end,
            () => routeWithinContainer(to.ownerId, result, start, end, plan.laneIndex),
            result,
            routingContext,
            searchWorkspace,
            endpointOverlayScratch.get(to.ownerId),
            options,
            pairRoutes.get(plan.pairKey) ?? [],
            () => this.alternativePairedPortals(to),
            () => index === 0 ? this.alternativeItemAttachments(plan, from, to.ownerId) : [],
            plan.bundleSize > 1
          )
        );
      }
    }, "routeHierarchyChain");
    const sourceChains = [];
    const targetChains = [];
    routeHierarchyChain(plan.source, sourceChains);
    routeHierarchyChain(plan.target, targetChains);
    const points = combinePointChains([
      ...sourceChains,
      lcaPoints,
      ...targetChains.reverse().map((chain) => reversePoints(chain))
    ]);
    const committedPairRoutes = pairRoutes.get(plan.pairKey) ?? [];
    const satisfiesPairConstraints = routeSatisfiesPairConstraints(points, committedPairRoutes);
    const relaxHierarchySeparation = !satisfiesPairConstraints && plan.bundleSize > 1 && plan.source.chain.length + plan.target.chain.length > 2 && routeHasDistinctPairPorts(points, committedPairRoutes);
    if (plan.bundleSize > 1 && !satisfiesPairConstraints && (!relaxHierarchySeparation || !allowHierarchyRelaxation)) {
      if (metrics) {
        metrics.routesImpossible++;
      }
      throw gridError("GRID_ROUTE_NOT_FOUND", `No distinct lane route for "${edge.id}"`, {
        edgeId: edge.id,
        reason: relaxHierarchySeparation ? "pair-separation" : "no-distinct-route"
      });
    }
    if (relaxHierarchySeparation && metrics) {
      metrics.bundleSeparationRelaxations++;
    }
    edge.points = points;
    edge.curve = result.config.curve;
    edge.cornerRadius = result.config.edgeCornerRadius;
    committedPairRoutes.push(points);
    pairRoutes.set(plan.pairKey, committedPairRoutes);
    if (!compatibilityFastRoute) {
      this.occupancyFor(plan.lcaContainerId).add(lcaPoints, plan.pairKey);
    }
    if (metrics && instrumentedRoutes) {
      const boundaryTransitionCount = plan.source.chain.length + plan.target.chain.length - 2;
      recordGridRoute(
        metrics,
        edge.id,
        points,
        instrumentedRoutes,
        boundaryTransitionCount,
        plan.laneOffset
      );
      instrumentedRoutes.push(points);
    }
  }
  occupancyFor(containerId) {
    let occupancy = this.modes.routeOccupancy.get(containerId);
    if (!occupancy) {
      occupancy = new RouteOccupancyIndex();
      this.modes.routeOccupancy.set(containerId, occupancy);
    }
    return occupancy;
  }
  createBundleCheckpoint(pairPlans) {
    this.occupancyFor(pairPlans[0].lcaContainerId);
    return createBundleCheckpoint(
      pairPlans,
      this.pairRoutes,
      this.pairedPortals,
      this.prepared.demandCoords,
      this.instrumentedRoutes,
      this.metrics,
      this.modes.routeOccupancy
    );
  }
  restoreBundleCheckpoint(checkpoint) {
    restoreBundleCheckpoint(
      checkpoint,
      this.pairRoutes,
      this.pairedPortals,
      this.prepared.demandCoords,
      this.instrumentedRoutes,
      this.metrics
    );
  }
  routeBundle(pairPlans) {
    const canAttemptStrictSeparation = pairPlans.length > 1 && pairPlans.length <= 8 && pairPlans.every(({ edge }) => edge.start !== edge.end);
    if (!canAttemptStrictSeparation) {
      for (const plan of pairPlans) {
        this.routePlan(plan);
      }
      return;
    }
    const checkpoint = this.createBundleCheckpoint(pairPlans);
    let initialError;
    try {
      for (const plan of pairPlans) {
        this.routePlan(plan, false);
      }
      return;
    } catch (error) {
      initialError = error;
      this.restoreBundleCheckpoint(checkpoint);
    }
    if (!isPairSeparationError(initialError)) {
      throw initialError;
    }
    for (const plan of pairPlans) {
      this.routePlan(plan);
    }
  }
};

// src/rendering-util/layout-algorithms/grid/router.ts
function routeGridEdges(layout, result, metrics, options = {}) {
  new GridEdgeRoutingSession(layout, result, metrics, options).route();
}
__name(routeGridEdges, "routeGridEdges");

// src/rendering-util/layout-algorithms/grid/layoutCore.ts
var GROUP_ROUTING_GUTTER = 24;
var GROUP_ROUTING_CLEARANCE = 20;
function titleBandFor(node, titleGap) {
  if (!node.label || !node.labelBBox || !(node.labelBBox.height > 0)) {
    return 0;
  }
  return node.labelBBox.height + titleGap;
}
__name(titleBandFor, "titleBandFor");
function ensureMeasuredNode(node) {
  if (!isFinitePositiveNumber(node.width) || !isFinitePositiveNumber(node.height)) {
    throw gridError(
      "GRID_MISSING_MEASUREMENT",
      `Node "${node.id}" must have width and height greater than 0 (width: ${node.width}, height: ${node.height})`,
      {
        nodeId: node.id,
        width: node.width,
        height: node.height
      }
    );
  }
}
__name(ensureMeasuredNode, "ensureMeasuredNode");
function measureChild(node) {
  ensureMeasuredNode(node);
  return { width: node.width, height: node.height };
}
__name(measureChild, "measureChild");
function layoutContainer(containerId, result, containers, itemMeta, metrics) {
  const { forest, config, sourceOrder } = result;
  const group = containerId === ROOT_CONTAINER_ID ? void 0 : forest.groupById.get(containerId);
  const padding = group ? Math.max(group.padding ?? 0, config.containerPadding) : 0;
  const titleBand = group ? titleBandFor(group, config.titleGap) : 0;
  const routingGutter = group ? GROUP_ROUTING_GUTTER : 0;
  const contentTop = group ? padding + titleBand + routingGutter : 0;
  const directItems = (forest.childrenByParent.get(containerId) ?? []).filter(
    (node) => !isEdgeLabelNode(node)
  );
  const { cells } = resolveGridPlacements(directItems, sourceOrder, config);
  const cellEntries = [...cells.values()].sort((a, b) => a.row - b.row || a.column - b.column);
  const columnWidths = /* @__PURE__ */ new Map();
  const rowHeights = /* @__PURE__ */ new Map();
  const rows = /* @__PURE__ */ new Set();
  const columns = /* @__PURE__ */ new Set();
  for (const cell of cellEntries) {
    let stackWidth = 0;
    let stackHeight = 0;
    for (const placement of cell.items) {
      const size = measureChild(placement.item);
      stackWidth = Math.max(stackWidth, size.width);
      stackHeight += size.height;
    }
    if (cell.items.length > 1) {
      stackHeight += config.cellGap * (cell.items.length - 1);
    }
    cell.width = stackWidth;
    cell.height = stackHeight;
    rows.add(cell.row);
    columns.add(cell.column);
    columnWidths.set(cell.column, Math.max(columnWidths.get(cell.column) ?? 0, stackWidth));
    rowHeights.set(cell.row, Math.max(rowHeights.get(cell.row) ?? 0, stackHeight));
  }
  const sortedRows = [...rows].sort((a, b) => a - b);
  const sortedColumns = [...columns].sort((a, b) => a - b);
  const labelGaps = deriveGridContainerLabelGaps(
    result.labelRequirements.byContainer.get(containerId) ?? [],
    cells,
    rowHeights,
    columnWidths,
    sortedRows,
    sortedColumns,
    config.rowGap,
    config.columnGap,
    metrics
  );
  const rowGapAfter = /* @__PURE__ */ __name((row) => Math.max(config.rowGap, labelGaps.rowGapAfter.get(row) ?? 0), "rowGapAfter");
  const columnGapAfter = /* @__PURE__ */ __name((column) => Math.max(config.columnGap, labelGaps.columnGapAfter.get(column) ?? 0), "columnGapAfter");
  if (metrics) {
    for (const gap of labelGaps.rowGapAfter.values()) {
      if (gap > config.rowGap) {
        metrics.labelSpacingBoundariesExpanded++;
        metrics.labelSpacingPixelsAdded += gap - config.rowGap;
      }
    }
    for (const gap of labelGaps.columnGapAfter.values()) {
      if (gap > config.columnGap) {
        metrics.labelSpacingBoundariesExpanded++;
        metrics.labelSpacingPixelsAdded += gap - config.columnGap;
      }
    }
  }
  const contentWidth = sortedColumns.reduce(
    (total, column, index) => total + (columnWidths.get(column) ?? 0) + (index < sortedColumns.length - 1 ? columnGapAfter(column) : 0),
    0
  );
  const width = group ? Math.max(
    contentWidth + (padding + routingGutter) * 2,
    (group.labelBBox?.width ?? 0) + padding * 2
  ) : contentWidth;
  const contentLeft = group ? (width - contentWidth) / 2 : 0;
  const columnOrigins = /* @__PURE__ */ new Map();
  let xCursor = contentLeft;
  for (const [index, column] of sortedColumns.entries()) {
    columnOrigins.set(column, xCursor);
    xCursor += (columnWidths.get(column) ?? 0) + (index < sortedColumns.length - 1 ? columnGapAfter(column) : 0);
  }
  const rowOrigins = /* @__PURE__ */ new Map();
  let yCursor = contentTop;
  for (const [index, row] of sortedRows.entries()) {
    rowOrigins.set(row, yCursor);
    yCursor += (rowHeights.get(row) ?? 0) + (index < sortedRows.length - 1 ? rowGapAfter(row) : 0);
  }
  const gridHeight = sortedRows.length ? yCursor - contentTop : 0;
  const outerLeftCorridor = group ? contentLeft - GROUP_ROUTING_CLEARANCE : -Math.max(config.columnGap / 2, GRID_DEFAULTS.containerPadding);
  const outerRightCorridor = group ? contentLeft + contentWidth + GROUP_ROUTING_CLEARANCE : contentLeft + contentWidth + Math.max(config.columnGap / 2, GRID_DEFAULTS.containerPadding);
  const outerTopCorridor = group ? contentTop - GROUP_ROUTING_CLEARANCE : -Math.max(config.rowGap / 2, GRID_DEFAULTS.containerPadding);
  const outerBottomCorridor = group ? contentTop + gridHeight + GROUP_ROUTING_CLEARANCE : contentTop + gridHeight + Math.max(config.rowGap / 2, GRID_DEFAULTS.containerPadding);
  const verticalCorridors = /* @__PURE__ */ new Set([outerLeftCorridor, outerRightCorridor]);
  const horizontalCorridors = /* @__PURE__ */ new Set([outerTopCorridor, outerBottomCorridor]);
  const leftCorridorByColumn = /* @__PURE__ */ new Map();
  const rightCorridorByColumn = /* @__PURE__ */ new Map();
  const topCorridorByRow = /* @__PURE__ */ new Map();
  const bottomCorridorByRow = /* @__PURE__ */ new Map();
  if (sortedColumns.length > 0) {
    leftCorridorByColumn.set(sortedColumns[0], outerLeftCorridor);
    rightCorridorByColumn.set(sortedColumns.at(-1), outerRightCorridor);
  }
  for (let index = 0; index < sortedColumns.length - 1; index++) {
    const current = sortedColumns[index];
    const next = sortedColumns[index + 1];
    const corridor = (columnOrigins.get(current) + (columnWidths.get(current) ?? 0) + columnOrigins.get(next)) / 2;
    verticalCorridors.add(corridor);
    rightCorridorByColumn.set(current, corridor);
    leftCorridorByColumn.set(next, corridor);
  }
  if (sortedRows.length > 0) {
    topCorridorByRow.set(sortedRows[0], outerTopCorridor);
    bottomCorridorByRow.set(sortedRows.at(-1), outerBottomCorridor);
  }
  for (let index = 0; index < sortedRows.length - 1; index++) {
    const current = sortedRows[index];
    const next = sortedRows[index + 1];
    const corridor = (rowOrigins.get(current) + (rowHeights.get(current) ?? 0) + rowOrigins.get(next)) / 2;
    horizontalCorridors.add(corridor);
    bottomCorridorByRow.set(current, corridor);
    topCorridorByRow.set(next, corridor);
  }
  for (const cell of cellEntries) {
    const cellLeft = columnOrigins.get(cell.column) ?? contentLeft;
    const cellTop = rowOrigins.get(cell.row) ?? contentTop;
    const cellWidth = columnWidths.get(cell.column) ?? cell.width;
    const cellHeight = rowHeights.get(cell.row) ?? cell.height;
    const verticalFactor = cell.verticalAlign === "top" ? 0 : cell.verticalAlign === "bottom" ? 1 : 0.5;
    const stackTop = cellTop + (cellHeight - cell.height) * verticalFactor;
    let itemTop = stackTop;
    for (const [itemIndex, placement] of cell.items.entries()) {
      const { width: width2, height: height2 } = measureChild(placement.item);
      const horizontalFactor = placement.horizontalAlign === "left" ? 0 : placement.horizontalAlign === "right" ? 1 : 0.5;
      const itemLeft = cellLeft + (cellWidth - width2) * horizontalFactor;
      placement.item.x = itemLeft + width2 / 2;
      placement.item.y = itemTop + height2 / 2;
      const topCorridorY = itemIndex > 0 ? itemTop - config.cellGap / 2 : topCorridorByRow.get(cell.row) ?? outerTopCorridor;
      const bottomCorridorY = itemIndex < cell.items.length - 1 ? itemTop + height2 + config.cellGap / 2 : bottomCorridorByRow.get(cell.row) ?? outerBottomCorridor;
      if (itemIndex > 0) {
        horizontalCorridors.add(topCorridorY);
      }
      if (itemIndex < cell.items.length - 1) {
        horizontalCorridors.add(bottomCorridorY);
      }
      itemMeta.set(placement.item.id, {
        containerId,
        row: cell.row,
        column: cell.column,
        cellLeft,
        cellTop,
        cellWidth,
        cellHeight,
        leftCorridorX: leftCorridorByColumn.get(cell.column) ?? outerLeftCorridor,
        rightCorridorX: rightCorridorByColumn.get(cell.column) ?? outerRightCorridor,
        topCorridorY,
        bottomCorridorY
      });
      itemTop += height2 + config.cellGap;
    }
  }
  const height = group ? gridHeight + titleBand + (padding + routingGutter) * 2 : gridHeight;
  containers.set(containerId, {
    id: containerId,
    left: 0,
    top: 0,
    width,
    height,
    contentLeft,
    contentTop,
    contentRight: group ? contentLeft + contentWidth : contentWidth,
    contentBottom: group ? contentTop + gridHeight : gridHeight,
    verticalCorridors: [...verticalCorridors].sort((a, b) => a - b),
    horizontalCorridors: [...horizontalCorridors].sort((a, b) => a - b)
  });
  if (group) {
    group.width = width;
    group.height = height;
    group.x = width / 2;
    group.y = height / 2;
    if (titleBand > 0) {
      group.groupTitleRect = {
        left: 0,
        right: width,
        top: 0,
        bottom: padding + titleBand
      };
    } else {
      delete group.groupTitleRect;
    }
  }
}
__name(layoutContainer, "layoutContainer");
function translateRect(rect, dx, dy) {
  return {
    left: rect.left + dx,
    right: rect.right + dx,
    top: rect.top + dy,
    bottom: rect.bottom + dy
  };
}
__name(translateRect, "translateRect");
function materializeAbsoluteGeometry(result) {
  const { forest, containers, itemMeta } = result;
  const stack = [
    {
      containerId: ROOT_CONTAINER_ID,
      offsetX: 0,
      offsetY: 0,
      children: forest.childrenByParent.get(ROOT_CONTAINER_ID) ?? [],
      nextChildIndex: 0,
      entered: false
    }
  ];
  while (stack.length > 0) {
    const frame = stack[stack.length - 1];
    if (!frame.entered) {
      frame.entered = true;
      const container = containers.get(frame.containerId);
      if (container) {
        container.left += frame.offsetX;
        container.top += frame.offsetY;
        container.contentLeft += frame.offsetX;
        container.contentRight += frame.offsetX;
        container.contentTop += frame.offsetY;
        container.contentBottom += frame.offsetY;
        container.verticalCorridors = container.verticalCorridors.map(
          (value) => value + frame.offsetX
        );
        container.horizontalCorridors = container.horizontalCorridors.map(
          (value) => value + frame.offsetY
        );
      }
    }
    const child = frame.children[frame.nextChildIndex];
    if (!child) {
      stack.pop();
      continue;
    }
    frame.nextChildIndex += 1;
    if (isEdgeLabelNode(child)) {
      continue;
    }
    const meta = itemMeta.get(child.id);
    if (meta) {
      meta.cellLeft += frame.offsetX;
      meta.cellTop += frame.offsetY;
      meta.leftCorridorX += frame.offsetX;
      meta.rightCorridorX += frame.offsetX;
      meta.topCorridorY += frame.offsetY;
      meta.bottomCorridorY += frame.offsetY;
    }
    child.x = (child.x ?? 0) + frame.offsetX;
    child.y = (child.y ?? 0) + frame.offsetY;
    if (!child.isGroup) {
      continue;
    }
    if (child.groupTitleRect) {
      child.groupTitleRect = translateRect(
        child.groupTitleRect,
        child.x - (child.width ?? 0) / 2,
        child.y - (child.height ?? 0) / 2
      );
    }
    stack.push({
      containerId: child.id,
      offsetX: child.x - (child.width ?? 0) / 2,
      offsetY: child.y - (child.height ?? 0) / 2,
      children: forest.childrenByParent.get(child.id) ?? [],
      nextChildIndex: 0,
      entered: false
    });
  }
}
__name(materializeAbsoluteGeometry, "materializeAbsoluteGeometry");
function commitGridGeometry(source, target) {
  const sourceNodeById = new Map(source.nodes.map((node) => [node.id, node]));
  for (const targetNode of target.nodes) {
    const sourceNode = sourceNodeById.get(targetNode.id);
    if (!sourceNode) {
      continue;
    }
    targetNode.x = sourceNode.x;
    targetNode.y = sourceNode.y;
    targetNode.width = sourceNode.width;
    targetNode.height = sourceNode.height;
    if (sourceNode.groupTitleRect) {
      targetNode.groupTitleRect = { ...sourceNode.groupTitleRect };
    } else {
      delete targetNode.groupTitleRect;
    }
  }
  const sourceEdgeById = new Map(source.edges.map((edge) => [edge.id, edge]));
  for (const targetEdge of target.edges) {
    const sourceEdge = sourceEdgeById.get(targetEdge.id);
    if (!sourceEdge) {
      continue;
    }
    targetEdge.points = sourceEdge.points?.map((point) => ({ ...point }));
    targetEdge.curve = sourceEdge.curve;
    targetEdge.cornerRadius = sourceEdge.cornerRadius;
    targetEdge.portClipping = "outline-orthogonal";
    targetEdge.skipCornerFix = sourceEdge.curve === "linear";
  }
}
__name(commitGridGeometry, "commitGridGeometry");
function cloneGridLayoutData(data) {
  return {
    ...data,
    nodes: data.nodes.map((node) => ({
      ...node,
      labelBBox: node.labelBBox ? { ...node.labelBBox } : node.labelBBox,
      groupTitleRect: node.groupTitleRect ? { ...node.groupTitleRect } : node.groupTitleRect
    })),
    edges: data.edges.map((edge) => ({
      ...edge,
      points: edge.points?.map((point) => ({ ...point }))
    }))
  };
}
__name(cloneGridLayoutData, "cloneGridLayoutData");
function rebindGridForest(forest, nodes) {
  const nodeById = new Map(nodes.map((node) => [node.id, node]));
  const originalNode = /* @__PURE__ */ __name((node) => {
    const original = nodeById.get(node.id);
    if (!original) {
      throw new Error(`Missing committed grid node "${node.id}"`);
    }
    return original;
  }, "originalNode");
  const originalGroup = /* @__PURE__ */ __name((group) => {
    const original = originalNode(group);
    if (!original.isGroup) {
      throw new Error(`Committed grid node "${group.id}" is no longer a group`);
    }
    return original;
  }, "originalGroup");
  return {
    nodeById,
    groupById: new Map(
      [...forest.groupById].map(([groupId, group]) => [groupId, originalGroup(group)])
    ),
    childrenByParent: new Map(
      [...forest.childrenByParent].map(([parentId, children]) => [
        parentId,
        children.map(originalNode)
      ])
    ),
    rootChildren: forest.rootChildren.map(originalNode),
    postOrderGroups: forest.postOrderGroups.map(originalGroup),
    helperNodeIds: new Set(forest.helperNodeIds)
  };
}
__name(rebindGridForest, "rebindGridForest");
function runGridLayoutCoreInPlace(data, options) {
  const forest = buildGridForest(data.nodes);
  const config = readGridConfig(data);
  const sourceOrder = buildGridSourceOrder(data.nodes.filter((node) => !isEdgeLabelNode(node)));
  validateGridPlacementMap(
    data.nodes.filter((node) => !isEdgeLabelNode(node)),
    config
  );
  const result = {
    forest,
    config,
    containers: /* @__PURE__ */ new Map(),
    itemMeta: /* @__PURE__ */ new Map(),
    sourceOrder,
    labelRequirements: buildGridLabelRequirements(data, forest, options.metrics)
  };
  for (const group of forest.postOrderGroups) {
    layoutContainer(group.id, result, result.containers, result.itemMeta, options.metrics);
  }
  layoutContainer(ROOT_CONTAINER_ID, result, result.containers, result.itemMeta, options.metrics);
  materializeAbsoluteGeometry(result);
  routeGridEdges(data, result, options.metrics, options.routing);
  positionGridEdgeLabels(data, void 0, options.metrics);
  return result;
}
__name(runGridLayoutCoreInPlace, "runGridLayoutCoreInPlace");
function runGridLayoutCore(data4Layout, options = {}) {
  const data = data4Layout;
  const working = cloneGridLayoutData(data);
  const result = runGridLayoutCoreInPlace(working, options);
  commitGridGeometry(working, data);
  return {
    ...result,
    forest: rebindGridForest(result.forest, data.nodes)
  };
}
__name(runGridLayoutCore, "runGridLayoutCore");

// src/rendering-util/layout-algorithms/grid/lineHops.ts
function applyGridLineJumps(data, { measure }) {
  const lineHops = normalizeLineHops(data.config.grid?.lineHops);
  if (lineHops === false) {
    return;
  }
  const edges = data.edges.filter(
    (edge) => Array.isArray(edge.points) && edge.points.length >= 2
  ).map((edge) => ({
    id: edge.id,
    points: edge.points,
    curve: edge.curve,
    cornerRadius: edge.cornerRadius,
    arrowTypeStart: edge.arrowTypeStart,
    arrowTypeEnd: edge.arrowTypeEnd
  }));
  applyLineJumpsToSvg(measure.groups.edgePaths, edges, {
    enabled: true,
    jumpRadius: 6,
    jumpStyle: lineHops
  });
}
__name(applyGridLineJumps, "applyGridLineJumps");

// src/rendering-util/layout-algorithms/grid/index.ts
var render = createCommonLayoutRenderer({
  prepareLayout: prepareGridLayout,
  runLayoutCore: /* @__PURE__ */ __name((data4Layout) => runGridLayoutCore(data4Layout), "runLayoutCore"),
  afterPaint: applyGridLineJumps
});
export {
  prepareGridLayout,
  render,
  runGridLayoutCore
};