var _a;
import { t as merge_default } from "./merge-CHn7Yx0N.js";
import { t as memoize_default } from "./memoize-C9ltv0Cw.js";
import { _ as basis_default, a as monotoneX, c as catmullRomOpen_default, d as cardinalOpen_default, f as cardinalClosed_default, g as basisClosed_default, h as basisOpen_default, i as natural_default, l as catmullRomClosed_default, m as bundle_default, n as stepBefore, o as monotoneY, p as cardinal_default, r as step_default, s as linearClosed_default, t as stepAfter, u as catmullRom_default, v as linear_default } from "./step-CWipAYTY.js";
import { i as log, r as __name, t as select_default } from "./src-Bf2iLOlr.js";
import { F as sanitizeDirective, f as detectType, m as directiveRegex, r as assignWithDepth_default, s as common_default } from "./chunk-ABZYJK2D-D0cLy8Bb.js";
import { t as require_dist } from "./dist-BGdYVvOu.js";
var Bump = class {
  constructor(h, W) {
    this._context = h, this._x = W;
  }
  areaStart() {
    this._line = 0;
  }
  areaEnd() {
    this._line = NaN;
  }
  lineStart() {
    this._point = 0;
  }
  lineEnd() {
    (this._line || this._line !== 0 && this._point === 1) && this._context.closePath(), this._line = 1 - this._line;
  }
  point(h, W) {
    switch (h = +h, W = +W, this._point) {
      case 0:
        this._point = 1, this._line ? this._context.lineTo(h, W) : this._context.moveTo(h, W);
        break;
      case 1:
        this._point = 2;
      default:
        this._x ? this._context.bezierCurveTo(this._x0 = (this._x0 + h) / 2, this._y0, this._x0, W, h, W) : this._context.bezierCurveTo(this._x0, this._y0 = (this._y0 + W) / 2, h, this._y0, h, W);
        break;
    }
    this._x0 = h, this._y0 = W;
  }
};
function bumpX(h) {
  return new Bump(h, true);
}
function bumpY(h) {
  return new Bump(h, false);
}
var import_dist = require_dist(), ZERO_WIDTH_SPACE = "\u200B", d3CurveTypes = {
  curveBasis: basis_default,
  curveBasisClosed: basisClosed_default,
  curveBasisOpen: basisOpen_default,
  curveBumpX: bumpX,
  curveBumpY: bumpY,
  curveBundle: bundle_default,
  curveCardinalClosed: cardinalClosed_default,
  curveCardinalOpen: cardinalOpen_default,
  curveCardinal: cardinal_default,
  curveCatmullRomClosed: catmullRomClosed_default,
  curveCatmullRomOpen: catmullRomOpen_default,
  curveCatmullRom: catmullRom_default,
  curveLinear: linear_default,
  curveLinearClosed: linearClosed_default,
  curveMonotoneX: monotoneX,
  curveMonotoneY: monotoneY,
  curveNatural: natural_default,
  curveStep: step_default,
  curveStepAfter: stepAfter,
  curveStepBefore: stepBefore
}, directiveWithoutOpen = /\s*(?:(\w+)(?=:):|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi, detectInit = /* @__PURE__ */ __name(function(h, W) {
  let G = detectDirective(h, /(?:init\b)|(?:initialize\b)/), K = {};
  if (Array.isArray(G)) {
    let h2 = G.map((h3) => h3.args);
    sanitizeDirective(h2), K = assignWithDepth_default(K, [...h2]);
  } else K = G.args;
  if (!K) return;
  let q = detectType(h, W), J = "config";
  return K[J] !== void 0 && (q === "flowchart-v2" && (q = "flowchart"), K[q] = K[J], delete K[J]), K;
}, "detectInit"), detectDirective = /* @__PURE__ */ __name(function(h, W = null) {
  var _a2, _b;
  try {
    let G = RegExp(`[%]{2}(?![{]${directiveWithoutOpen.source})(?=[}][%]{2}).*
`, "ig");
    h = h.trim().replace(G, "").replace(/'/gm, '"'), log.debug(`Detecting diagram directive${W === null ? "" : " type:" + W} based on the text:${h}`);
    let K, q = [];
    for (; (K = directiveRegex.exec(h)) !== null; ) if (K.index === directiveRegex.lastIndex && directiveRegex.lastIndex++, K && !W || W && ((_a2 = K[1]) == null ? void 0 : _a2.match(W)) || W && ((_b = K[2]) == null ? void 0 : _b.match(W))) {
      let h2 = K[1] ? K[1] : K[2], W2 = K[3] ? K[3].trim() : K[4] ? JSON.parse(K[4].trim()) : null;
      q.push({
        type: h2,
        args: W2
      });
    }
    return q.length === 0 ? {
      type: h,
      args: null
    } : q.length === 1 ? q[0] : q;
  } catch (G) {
    return log.error(`ERROR: ${G.message} - Unable to parse directive type: '${W}' based on the text: '${h}'`), {
      type: void 0,
      args: null
    };
  }
}, "detectDirective"), removeDirectives = /* @__PURE__ */ __name(function(h) {
  return h.replace(directiveRegex, "");
}, "removeDirectives"), isSubstringInArray = /* @__PURE__ */ __name(function(h, W) {
  for (let [G, K] of W.entries()) if (K.match(h)) return G;
  return -1;
}, "isSubstringInArray");
function interpolateToCurve(h, W) {
  return h ? d3CurveTypes[`curve${h.charAt(0).toUpperCase() + h.slice(1)}`] ?? W : W;
}
__name(interpolateToCurve, "interpolateToCurve");
function formatUrl(h, W) {
  let G = h.trim();
  if (G) return W.securityLevel === "loose" ? G : (0, import_dist.sanitizeUrl)(G);
}
__name(formatUrl, "formatUrl");
var runFunc = /* @__PURE__ */ __name((h, ...W) => {
  let G = h.split("."), K = G.length - 1, q = G[K], J = window;
  for (let W2 = 0; W2 < K; W2++) if (J = J[G[W2]], !J) {
    log.error(`Function name: ${h} not found in window`);
    return;
  }
  J[q](...W);
}, "runFunc");
function distance(h, W) {
  return !h || !W ? 0 : Math.sqrt((W.x - h.x) ** 2 + (W.y - h.y) ** 2);
}
__name(distance, "distance");
function traverseEdge(h) {
  let W, G = 0;
  return h.forEach((h2) => {
    G += distance(h2, W), W = h2;
  }), calculatePoint(h, G / 2);
}
__name(traverseEdge, "traverseEdge");
function calcLabelPosition(h) {
  return h.length === 1 ? h[0] : traverseEdge(h);
}
__name(calcLabelPosition, "calcLabelPosition");
var roundNumber = /* @__PURE__ */ __name((h, W = 2) => {
  let G = 10 ** W;
  return Math.round(h * G) / G;
}, "roundNumber"), calculatePoint = /* @__PURE__ */ __name((h, W) => {
  let G, K = W;
  for (let W2 of h) {
    if (G) {
      let h2 = distance(W2, G);
      if (h2 === 0) return G;
      if (h2 < K) K -= h2;
      else {
        let q = K / h2;
        if (q <= 0) return G;
        if (q >= 1) return {
          x: W2.x,
          y: W2.y
        };
        if (q > 0 && q < 1) return {
          x: roundNumber((1 - q) * G.x + q * W2.x, 5),
          y: roundNumber((1 - q) * G.y + q * W2.y, 5)
        };
      }
    }
    G = W2;
  }
  throw Error("Could not find a suitable point for the given distance");
}, "calculatePoint"), calcCardinalityPosition = /* @__PURE__ */ __name((h, W, G) => {
  log.info(`our points ${JSON.stringify(W)}`), W[0] !== G && (W = W.reverse());
  let K = calculatePoint(W, 25), q = h ? 10 : 5, J = Math.atan2(W[0].y - K.y, W[0].x - K.x), Y = {
    x: 0,
    y: 0
  };
  return Y.x = Math.sin(J) * q + (W[0].x + K.x) / 2, Y.y = -Math.cos(J) * q + (W[0].y + K.y) / 2, Y;
}, "calcCardinalityPosition");
function calcTerminalLabelPosition(h, W, G) {
  let K = structuredClone(G);
  log.info("our points", K), W !== "start_left" && W !== "start_right" && K.reverse();
  let q = calculatePoint(K, 25 + h), J = 10 + h * 0.5, Y = Math.atan2(K[0].y - q.y, K[0].x - q.x), X = {
    x: 0,
    y: 0
  };
  return W === "start_left" ? (X.x = Math.sin(Y + Math.PI) * J + (K[0].x + q.x) / 2, X.y = -Math.cos(Y + Math.PI) * J + (K[0].y + q.y) / 2) : W === "end_right" ? (X.x = Math.sin(Y - Math.PI) * J + (K[0].x + q.x) / 2 - 5, X.y = -Math.cos(Y - Math.PI) * J + (K[0].y + q.y) / 2 - 5) : W === "end_left" ? (X.x = Math.sin(Y) * J + (K[0].x + q.x) / 2 - 5, X.y = -Math.cos(Y) * J + (K[0].y + q.y) / 2 - 5) : (X.x = Math.sin(Y) * J + (K[0].x + q.x) / 2, X.y = -Math.cos(Y) * J + (K[0].y + q.y) / 2), X;
}
__name(calcTerminalLabelPosition, "calcTerminalLabelPosition");
function getStylesFromArray(h) {
  let W = "", G = "";
  for (let K of h) K !== void 0 && (K.startsWith("color:") || K.startsWith("text-align:") ? G = G + K + ";" : W = W + K + ";");
  return {
    style: W,
    labelStyle: G
  };
}
__name(getStylesFromArray, "getStylesFromArray");
var cnt = 0, generateId = /* @__PURE__ */ __name(() => (cnt++, "id-" + Math.random().toString(36).substr(2, 12) + "-" + cnt), "generateId");
function makeRandomHex(h) {
  let W = "";
  for (let G = 0; G < h; G++) W += "0123456789abcdef".charAt(Math.floor(Math.random() * 16));
  return W;
}
__name(makeRandomHex, "makeRandomHex");
var random = /* @__PURE__ */ __name((h) => makeRandomHex(h.length), "random"), getTextObj = /* @__PURE__ */ __name(function() {
  return {
    x: 0,
    y: 0,
    fill: void 0,
    anchor: "start",
    style: "#666",
    width: 100,
    height: 100,
    textMargin: 0,
    rx: 0,
    ry: 0,
    valign: void 0,
    text: ""
  };
}, "getTextObj"), drawSimpleText = /* @__PURE__ */ __name(function(h, W) {
  let G = W.text.replace(common_default.lineBreakRegex, " "), [, K] = parseFontSize(W.fontSize), q = h.append("text");
  q.attr("x", W.x), q.attr("y", W.y), q.style("text-anchor", W.anchor), q.style("font-family", W.fontFamily), q.style("font-size", K), q.style("font-weight", W.fontWeight), q.attr("fill", W.fill), W.class !== void 0 && q.attr("class", W.class);
  let J = q.append("tspan");
  return J.attr("x", W.x + W.textMargin * 2), J.attr("fill", W.fill), J.text(G), q;
}, "drawSimpleText"), wrapLabel = memoize_default((h, W, G) => {
  if (!h || (G = Object.assign({
    fontSize: 12,
    fontWeight: 400,
    fontFamily: "Arial",
    joinWith: "<br/>"
  }, G), common_default.lineBreakRegex.test(h))) return h;
  let K = h.split(" ").filter(Boolean), q = [], J = "";
  return K.forEach((h2, Y) => {
    let X = calculateTextWidth(`${h2} `, G), Z = calculateTextWidth(J, G);
    if (X > W) {
      let { hyphenatedStrings: K2, remainingWord: Y2 } = breakString(h2, W, "-", G);
      q.push(J, ...K2), J = Y2;
    } else Z + X >= W ? (q.push(J), J = h2) : J = [J, h2].filter(Boolean).join(" ");
    Y + 1 === K.length && q.push(J);
  }), q.filter((h2) => h2 !== "").join(G.joinWith);
}, (h, W, G) => `${h}${W}${G.fontSize}${G.fontWeight}${G.fontFamily}${G.joinWith}`), breakString = memoize_default((h, W, G = "-", K) => {
  K = Object.assign({
    fontSize: 12,
    fontWeight: 400,
    fontFamily: "Arial",
    margin: 0
  }, K);
  let q = [...h], J = [], Y = "";
  return q.forEach((h2, X) => {
    let Z = `${Y}${h2}`;
    if (calculateTextWidth(Z, K) >= W) {
      let h3 = X + 1, W2 = q.length === h3, K2 = `${Z}${G}`;
      J.push(W2 ? Z : K2), Y = "";
    } else Y = Z;
  }), {
    hyphenatedStrings: J,
    remainingWord: Y
  };
}, (h, W, G = "-", K) => `${h}${W}${G}${K.fontSize}${K.fontWeight}${K.fontFamily}`);
function calculateTextHeight(h, W) {
  return calculateTextDimensions(h, W).height;
}
__name(calculateTextHeight, "calculateTextHeight");
function calculateTextWidth(h, W) {
  return calculateTextDimensions(h, W).width;
}
__name(calculateTextWidth, "calculateTextWidth");
var calculateTextDimensions = memoize_default((h, W) => {
  let { fontSize: G = 12, fontFamily: K = "Arial", fontWeight: q = 400 } = W;
  if (!h) return {
    width: 0,
    height: 0
  };
  let [, J] = parseFontSize(G), Y = ["sans-serif", K], X = h.split(common_default.lineBreakRegex), Z = [], Q = select_default("body");
  if (!Q.remove) return {
    width: 0,
    height: 0,
    lineHeight: 0
  };
  let $ = Q.append("svg");
  for (let h2 of Y) {
    let W2 = 0, G2 = {
      width: 0,
      height: 0,
      lineHeight: 0
    };
    for (let K2 of X) {
      let Y2 = getTextObj();
      Y2.text = K2 || "\u200B";
      let X2 = drawSimpleText($, Y2).style("font-size", J).style("font-weight", q).style("font-family", h2), Z2 = (X2._groups || X2)[0][0].getBBox();
      if (Z2.width === 0 && Z2.height === 0) throw Error("svg element not in render tree");
      G2.width = Math.round(Math.max(G2.width, Z2.width)), W2 = Math.round(Z2.height), G2.height += W2, G2.lineHeight = Math.round(Math.max(G2.lineHeight, W2));
    }
    Z.push(G2);
  }
  return $.remove(), Z[isNaN(Z[1].height) || isNaN(Z[1].width) || isNaN(Z[1].lineHeight) || Z[0].height > Z[1].height && Z[0].width > Z[1].width && Z[0].lineHeight > Z[1].lineHeight ? 0 : 1];
}, (h, W) => `${h}${W.fontSize}${W.fontWeight}${W.fontFamily}`), InitIDGenerator = (_a = class {
  constructor(h = false, W) {
    this.count = 0, this.count = W ? W.length : 0, this.next = h ? () => this.count++ : () => Date.now();
  }
}, __name(_a, "InitIDGenerator"), _a), decoder, entityDecode = /* @__PURE__ */ __name(function(h) {
  return decoder || (decoder = document.createElement("div")), h = escape(h).replace(/%26/g, "&").replace(/%23/g, "#").replace(/%3B/g, ";"), decoder.innerHTML = h, unescape(decoder.textContent);
}, "entityDecode");
function isDetailedError(h) {
  return "str" in h;
}
__name(isDetailedError, "isDetailedError");
var insertTitle = /* @__PURE__ */ __name((h, W, G, K) => {
  var _a2;
  if (!K) return;
  let q = (_a2 = h.node()) == null ? void 0 : _a2.getBBox();
  q && h.append("text").text(K).attr("text-anchor", "middle").attr("x", q.x + q.width / 2).attr("y", -G).attr("class", W);
}, "insertTitle"), parseFontSize = /* @__PURE__ */ __name((h) => {
  if (typeof h == "number") return [h, h + "px"];
  let W = parseInt(h ?? "", 10);
  return Number.isNaN(W) ? [void 0, void 0] : h === String(W) ? [W, h + "px"] : [W, h];
}, "parseFontSize");
function cleanAndMerge(W, G) {
  return merge_default({}, W, G);
}
__name(cleanAndMerge, "cleanAndMerge");
var utils_default = {
  assignWithDepth: assignWithDepth_default,
  wrapLabel,
  calculateTextHeight,
  calculateTextWidth,
  calculateTextDimensions,
  cleanAndMerge,
  detectInit,
  detectDirective,
  isSubstringInArray,
  interpolateToCurve,
  calcLabelPosition,
  calcCardinalityPosition,
  calcTerminalLabelPosition,
  formatUrl,
  getStylesFromArray,
  generateId,
  random,
  runFunc,
  entityDecode,
  insertTitle,
  isLabelCoordinateInPath,
  parseFontSize,
  InitIDGenerator
}, encodeEntities = /* @__PURE__ */ __name(function(h) {
  let W = h;
  return W = W.replace(/style.*:\S*#.*;/g, function(h2) {
    return h2.substring(0, h2.length - 1);
  }), W = W.replace(/classDef.*:\S*#.*;/g, function(h2) {
    return h2.substring(0, h2.length - 1);
  }), W = W.replace(/#\w+;/g, function(h2) {
    let W2 = h2.substring(1, h2.length - 1);
    return /^\+?\d+$/.test(W2) ? "\uFB02\xB0\xB0" + W2 + "\xB6\xDF" : "\uFB02\xB0" + W2 + "\xB6\xDF";
  }), W;
}, "encodeEntities"), decodeEntities = /* @__PURE__ */ __name(function(h) {
  return h.replace(/ﬂ°°/g, "&#").replace(/ﬂ°/g, "&").replace(/¶ß/g, ";");
}, "decodeEntities"), getEdgeId = /* @__PURE__ */ __name((h, W, { counter: G = 0, prefix: K, suffix: q }, J) => J || `${K ? `${K}_` : ""}${h}_${W}_${G}${q ? `_${q}` : ""}`, "getEdgeId");
function handleUndefinedAttr(h) {
  return h ?? null;
}
__name(handleUndefinedAttr, "handleUndefinedAttr");
function isLabelCoordinateInPath(h, W) {
  let G = Math.round(h.x), K = Math.round(h.y), q = W.replace(/(\d+\.\d+)/g, (h2) => Math.round(parseFloat(h2)).toString());
  return q.includes(G.toString()) || q.includes(K.toString());
}
__name(isLabelCoordinateInPath, "isLabelCoordinateInPath");
export {
  wrapLabel as _,
  decodeEntities as a,
  getEdgeId as c,
  interpolateToCurve as d,
  isDetailedError as f,
  utils_default as g,
  removeDirectives as h,
  cleanAndMerge as i,
  getStylesFromArray as l,
  random as m,
  calculateTextHeight as n,
  encodeEntities as o,
  parseFontSize as p,
  calculateTextWidth as r,
  generateId as s,
  ZERO_WIDTH_SPACE as t,
  handleUndefinedAttr as u,
  bumpX as v,
  bumpY as y
};
