import { setDiagramTitle as q, getDiagramTitle as J, setAccDescription as Z, getAccDescription as tt, setAccTitle as et, getAccTitle as it, getConfig2 as B, defaultConfig2 as nt, setupGraphViewbox as st, clear as rt, common_default as at } from "./chunk-ABZYJK2D.js";
import { __name as n } from "./chunk-AGHRB4JF.js";
import "../../../../../../d3-transition@3.0.1_d3-selection@3.0.0/node_modules/d3-transition/src/selection/index.js";
import "../../../../../../d3-zoom@3.0.0/node_modules/d3-zoom/src/transform.js";
import ot from "../../../../../../d3-sankey@0.12.3/node_modules/d3-sankey/src/sankey.js";
import { justify as lt, center as ht, right as ct, left as ut } from "../../../../../../d3-sankey@0.12.3/node_modules/d3-sankey/src/align.js";
import yt from "../../../../../../d3-sankey@0.12.3/node_modules/d3-sankey/src/sankeyLinkHorizontal.js";
import pt from "../../../../../../d3-scale@4.0.2/node_modules/d3-scale/src/ordinal.js";
import ft from "../../../../../../d3-scale-chromatic@3.1.0/node_modules/d3-scale-chromatic/src/categorical/Tableau10.js";
import F from "../../../../../../d3-selection@3.0.0/node_modules/d3-selection/src/select.js";
var X = (function() {
  var a = /* @__PURE__ */ n(function(_, t, e, i) {
    for (e = e || {}, i = _.length; i--; e[_[i]] = t) ;
    return e;
  }, "o"), h = [1, 9], d = [1, 10], A = [1, 5, 10, 12], w = {
    trace: /* @__PURE__ */ n(function() {
    }, "trace"),
    yy: {},
    symbols_: { error: 2, start: 3, SANKEY: 4, NEWLINE: 5, csv: 6, opt_eof: 7, record: 8, csv_tail: 9, EOF: 10, "field[source]": 11, COMMA: 12, "field[target]": 13, "field[value]": 14, field: 15, escaped: 16, non_escaped: 17, DQUOTE: 18, ESCAPED_TEXT: 19, NON_ESCAPED_TEXT: 20, $accept: 0, $end: 1 },
    terminals_: { 2: "error", 4: "SANKEY", 5: "NEWLINE", 10: "EOF", 11: "field[source]", 12: "COMMA", 13: "field[target]", 14: "field[value]", 18: "DQUOTE", 19: "ESCAPED_TEXT", 20: "NON_ESCAPED_TEXT" },
    productions_: [0, [3, 4], [6, 2], [9, 2], [9, 0], [7, 1], [7, 0], [8, 5], [15, 1], [15, 1], [16, 3], [17, 1]],
    performAction: /* @__PURE__ */ n(function(t, e, i, o, l, r, T) {
      var x = r.length - 1;
      switch (l) {
        case 7:
          const k = o.findOrCreateNode(r[x - 4].trim().replaceAll('""', '"')), v = o.findOrCreateNode(r[x - 2].trim().replaceAll('""', '"')), M = parseFloat(r[x].trim());
          o.addLink(k, v, M);
          break;
        case 8:
        case 9:
        case 11:
          this.$ = r[x];
          break;
        case 10:
          this.$ = r[x - 1];
          break;
      }
    }, "anonymous"),
    table: [{ 3: 1, 4: [1, 2] }, { 1: [3] }, { 5: [1, 3] }, { 6: 4, 8: 5, 15: 6, 16: 7, 17: 8, 18: h, 20: d }, { 1: [2, 6], 7: 11, 10: [1, 12] }, a(d, [2, 4], { 9: 13, 5: [1, 14] }), { 12: [1, 15] }, a(A, [2, 8]), a(A, [2, 9]), { 19: [1, 16] }, a(A, [2, 11]), { 1: [2, 1] }, { 1: [2, 5] }, a(d, [2, 2]), { 6: 17, 8: 5, 15: 6, 16: 7, 17: 8, 18: h, 20: d }, { 15: 18, 16: 7, 17: 8, 18: h, 20: d }, { 18: [1, 19] }, a(d, [2, 3]), { 12: [1, 20] }, a(A, [2, 10]), { 15: 21, 16: 7, 17: 8, 18: h, 20: d }, a([1, 5, 10], [2, 7])],
    defaultActions: { 11: [2, 1], 12: [2, 5] },
    parseError: /* @__PURE__ */ n(function(t, e) {
      if (e.recoverable)
        this.trace(t);
      else {
        var i = new Error(t);
        throw i.hash = e, i;
      }
    }, "parseError"),
    parse: /* @__PURE__ */ n(function(t) {
      var e = this, i = [0], o = [], l = [null], r = [], T = this.table, x = "", k = 0, v = 0, M = 2, V = 1, K = r.slice.call(arguments, 1), u = Object.create(this.lexer), b = { yy: {} };
      for (var N in this.yy)
        Object.prototype.hasOwnProperty.call(this.yy, N) && (b.yy[N] = this.yy[N]);
      u.setInput(t, b.yy), b.yy.lexer = u, b.yy.parser = this, typeof u.yylloc > "u" && (u.yylloc = {});
      var I = u.yylloc;
      r.push(I);
      var P = u.options && u.options.ranges;
      typeof b.yy.parseError == "function" ? this.parseError = b.yy.parseError : this.parseError = Object.getPrototypeOf(this).parseError;
      function s(f) {
        i.length = i.length - 2 * f, l.length = l.length - f, r.length = r.length - f;
      }
      n(s, "popStack");
      function y() {
        var f;
        return f = o.pop() || u.lex() || V, typeof f != "number" && (f instanceof Array && (o = f, f = o.pop()), f = e.symbols_[f] || f), f;
      }
      n(y, "lex");
      for (var p, O, m, G, C = {}, $, S, Q, j; ; ) {
        if (O = i[i.length - 1], this.defaultActions[O] ? m = this.defaultActions[O] : ((p === null || typeof p > "u") && (p = y()), m = T[O] && T[O][p]), typeof m > "u" || !m.length || !m[0]) {
          var Y = "";
          j = [];
          for ($ in T[O])
            this.terminals_[$] && $ > M && j.push("'" + this.terminals_[$] + "'");
          u.showPosition ? Y = "Parse error on line " + (k + 1) + `:
` + u.showPosition() + `
Expecting ` + j.join(", ") + ", got '" + (this.terminals_[p] || p) + "'" : Y = "Parse error on line " + (k + 1) + ": Unexpected " + (p == V ? "end of input" : "'" + (this.terminals_[p] || p) + "'"), this.parseError(Y, {
            text: u.match,
            token: this.terminals_[p] || p,
            line: u.yylineno,
            loc: I,
            expected: j
          });
        }
        if (m[0] instanceof Array && m.length > 1)
          throw new Error("Parse Error: multiple actions possible at state: " + O + ", token: " + p);
        switch (m[0]) {
          case 1:
            i.push(p), l.push(u.yytext), r.push(u.yylloc), i.push(m[1]), p = null, v = u.yyleng, x = u.yytext, k = u.yylineno, I = u.yylloc;
            break;
          case 2:
            if (S = this.productions_[m[1]][1], C.$ = l[l.length - S], C._$ = {
              first_line: r[r.length - (S || 1)].first_line,
              last_line: r[r.length - 1].last_line,
              first_column: r[r.length - (S || 1)].first_column,
              last_column: r[r.length - 1].last_column
            }, P && (C._$.range = [
              r[r.length - (S || 1)].range[0],
              r[r.length - 1].range[1]
            ]), G = this.performAction.apply(C, [
              x,
              v,
              k,
              b.yy,
              m[1],
              l,
              r
            ].concat(K)), typeof G < "u")
              return G;
            S && (i = i.slice(0, -1 * S * 2), l = l.slice(0, -1 * S), r = r.slice(0, -1 * S)), i.push(this.productions_[m[1]][0]), l.push(C.$), r.push(C._$), Q = T[i[i.length - 2]][i[i.length - 1]], i.push(Q);
            break;
          case 3:
            return !0;
        }
      }
      return !0;
    }, "parse")
  }, c = /* @__PURE__ */ (function() {
    var _ = {
      EOF: 1,
      parseError: /* @__PURE__ */ n(function(e, i) {
        if (this.yy.parser)
          this.yy.parser.parseError(e, i);
        else
          throw new Error(e);
      }, "parseError"),
      // resets the lexer, sets new input
      setInput: /* @__PURE__ */ n(function(t, e) {
        return this.yy = e || this.yy || {}, this._input = t, this._more = this._backtrack = this.done = !1, this.yylineno = this.yyleng = 0, this.yytext = this.matched = this.match = "", this.conditionStack = ["INITIAL"], this.yylloc = {
          first_line: 1,
          first_column: 0,
          last_line: 1,
          last_column: 0
        }, this.options.ranges && (this.yylloc.range = [0, 0]), this.offset = 0, this;
      }, "setInput"),
      // consumes and returns one char from the input
      input: /* @__PURE__ */ n(function() {
        var t = this._input[0];
        this.yytext += t, this.yyleng++, this.offset++, this.match += t, this.matched += t;
        var e = t.match(/(?:\r\n?|\n).*/g);
        return e ? (this.yylineno++, this.yylloc.last_line++) : this.yylloc.last_column++, this.options.ranges && this.yylloc.range[1]++, this._input = this._input.slice(1), t;
      }, "input"),
      // unshifts one char (or a string) into the input
      unput: /* @__PURE__ */ n(function(t) {
        var e = t.length, i = t.split(/(?:\r\n?|\n)/g);
        this._input = t + this._input, this.yytext = this.yytext.substr(0, this.yytext.length - e), this.offset -= e;
        var o = this.match.split(/(?:\r\n?|\n)/g);
        this.match = this.match.substr(0, this.match.length - 1), this.matched = this.matched.substr(0, this.matched.length - 1), i.length - 1 && (this.yylineno -= i.length - 1);
        var l = this.yylloc.range;
        return this.yylloc = {
          first_line: this.yylloc.first_line,
          last_line: this.yylineno + 1,
          first_column: this.yylloc.first_column,
          last_column: i ? (i.length === o.length ? this.yylloc.first_column : 0) + o[o.length - i.length].length - i[0].length : this.yylloc.first_column - e
        }, this.options.ranges && (this.yylloc.range = [l[0], l[0] + this.yyleng - e]), this.yyleng = this.yytext.length, this;
      }, "unput"),
      // When called from action, caches matched text and appends it on next action
      more: /* @__PURE__ */ n(function() {
        return this._more = !0, this;
      }, "more"),
      // When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.
      reject: /* @__PURE__ */ n(function() {
        if (this.options.backtrack_lexer)
          this._backtrack = !0;
        else
          return this.parseError("Lexical error on line " + (this.yylineno + 1) + `. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).
` + this.showPosition(), {
            text: "",
            token: null,
            line: this.yylineno
          });
        return this;
      }, "reject"),
      // retain first n characters of the match
      less: /* @__PURE__ */ n(function(t) {
        this.unput(this.match.slice(t));
      }, "less"),
      // displays already matched input, i.e. for error messages
      pastInput: /* @__PURE__ */ n(function() {
        var t = this.matched.substr(0, this.matched.length - this.match.length);
        return (t.length > 20 ? "..." : "") + t.substr(-20).replace(/\n/g, "");
      }, "pastInput"),
      // displays upcoming input, i.e. for error messages
      upcomingInput: /* @__PURE__ */ n(function() {
        var t = this.match;
        return t.length < 20 && (t += this._input.substr(0, 20 - t.length)), (t.substr(0, 20) + (t.length > 20 ? "..." : "")).replace(/\n/g, "");
      }, "upcomingInput"),
      // displays the character position where the lexing error occurred, i.e. for error messages
      showPosition: /* @__PURE__ */ n(function() {
        var t = this.pastInput(), e = new Array(t.length + 1).join("-");
        return t + this.upcomingInput() + `
` + e + "^";
      }, "showPosition"),
      // test the lexed token: return FALSE when not a match, otherwise return token
      test_match: /* @__PURE__ */ n(function(t, e) {
        var i, o, l;
        if (this.options.backtrack_lexer && (l = {
          yylineno: this.yylineno,
          yylloc: {
            first_line: this.yylloc.first_line,
            last_line: this.last_line,
            first_column: this.yylloc.first_column,
            last_column: this.yylloc.last_column
          },
          yytext: this.yytext,
          match: this.match,
          matches: this.matches,
          matched: this.matched,
          yyleng: this.yyleng,
          offset: this.offset,
          _more: this._more,
          _input: this._input,
          yy: this.yy,
          conditionStack: this.conditionStack.slice(0),
          done: this.done
        }, this.options.ranges && (l.yylloc.range = this.yylloc.range.slice(0))), o = t[0].match(/(?:\r\n?|\n).*/g), o && (this.yylineno += o.length), this.yylloc = {
          first_line: this.yylloc.last_line,
          last_line: this.yylineno + 1,
          first_column: this.yylloc.last_column,
          last_column: o ? o[o.length - 1].length - o[o.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + t[0].length
        }, this.yytext += t[0], this.match += t[0], this.matches = t, this.yyleng = this.yytext.length, this.options.ranges && (this.yylloc.range = [this.offset, this.offset += this.yyleng]), this._more = !1, this._backtrack = !1, this._input = this._input.slice(t[0].length), this.matched += t[0], i = this.performAction.call(this, this.yy, this, e, this.conditionStack[this.conditionStack.length - 1]), this.done && this._input && (this.done = !1), i)
          return i;
        if (this._backtrack) {
          for (var r in l)
            this[r] = l[r];
          return !1;
        }
        return !1;
      }, "test_match"),
      // return next match in input
      next: /* @__PURE__ */ n(function() {
        if (this.done)
          return this.EOF;
        this._input || (this.done = !0);
        var t, e, i, o;
        this._more || (this.yytext = "", this.match = "");
        for (var l = this._currentRules(), r = 0; r < l.length; r++)
          if (i = this._input.match(this.rules[l[r]]), i && (!e || i[0].length > e[0].length)) {
            if (e = i, o = r, this.options.backtrack_lexer) {
              if (t = this.test_match(i, l[r]), t !== !1)
                return t;
              if (this._backtrack) {
                e = !1;
                continue;
              } else
                return !1;
            } else if (!this.options.flex)
              break;
          }
        return e ? (t = this.test_match(e, l[o]), t !== !1 ? t : !1) : this._input === "" ? this.EOF : this.parseError("Lexical error on line " + (this.yylineno + 1) + `. Unrecognized text.
` + this.showPosition(), {
          text: "",
          token: null,
          line: this.yylineno
        });
      }, "next"),
      // return next match that has a token
      lex: /* @__PURE__ */ n(function() {
        var e = this.next();
        return e || this.lex();
      }, "lex"),
      // activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
      begin: /* @__PURE__ */ n(function(e) {
        this.conditionStack.push(e);
      }, "begin"),
      // pop the previously active lexer condition state off the condition stack
      popState: /* @__PURE__ */ n(function() {
        var e = this.conditionStack.length - 1;
        return e > 0 ? this.conditionStack.pop() : this.conditionStack[0];
      }, "popState"),
      // produce the lexer rule set which is active for the currently active lexer condition state
      _currentRules: /* @__PURE__ */ n(function() {
        return this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1] ? this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules : this.conditions.INITIAL.rules;
      }, "_currentRules"),
      // return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available
      topState: /* @__PURE__ */ n(function(e) {
        return e = this.conditionStack.length - 1 - Math.abs(e || 0), e >= 0 ? this.conditionStack[e] : "INITIAL";
      }, "topState"),
      // alias for begin(condition)
      pushState: /* @__PURE__ */ n(function(e) {
        this.begin(e);
      }, "pushState"),
      // return the number of states currently on the stack
      stateStackSize: /* @__PURE__ */ n(function() {
        return this.conditionStack.length;
      }, "stateStackSize"),
      options: { "case-insensitive": !0 },
      performAction: /* @__PURE__ */ n(function(e, i, o, l) {
        switch (o) {
          case 0:
            return this.pushState("csv"), 4;
          case 1:
            return this.pushState("csv"), 4;
          case 2:
            return 10;
          case 3:
            return 5;
          case 4:
            return 12;
          case 5:
            return this.pushState("escaped_text"), 18;
          case 6:
            return 20;
          case 7:
            return this.popState("escaped_text"), 18;
          case 8:
            return 19;
        }
      }, "anonymous"),
      rules: [/^(?:sankey-beta\b)/i, /^(?:sankey\b)/i, /^(?:$)/i, /^(?:((\u000D\u000A)|(\u000A)))/i, /^(?:(\u002C))/i, /^(?:(\u0022))/i, /^(?:([\u0020-\u0021\u0023-\u002B\u002D-\u007E])*)/i, /^(?:(\u0022)(?!(\u0022)))/i, /^(?:(([\u0020-\u0021\u0023-\u002B\u002D-\u007E])|(\u002C)|(\u000D)|(\u000A)|(\u0022)(\u0022))*)/i],
      conditions: { csv: { rules: [2, 3, 4, 5, 6, 7, 8], inclusive: !1 }, escaped_text: { rules: [7, 8], inclusive: !1 }, INITIAL: { rules: [0, 1, 2, 3, 4, 5, 6, 7, 8], inclusive: !0 } }
    };
    return _;
  })();
  w.lexer = c;
  function g() {
    this.yy = {};
  }
  return n(g, "Parser"), g.prototype = w, w.Parser = g, new g();
})();
X.parser = X;
var R = X, z = [], U = [], W = /* @__PURE__ */ new Map(), dt = /* @__PURE__ */ n(() => {
  z = [], U = [], W = /* @__PURE__ */ new Map(), rt();
}, "clear"), L, gt = (L = class {
  constructor(h, d, A = 0) {
    this.source = h, this.target = d, this.value = A;
  }
}, n(L, "SankeyLink"), L), mt = /* @__PURE__ */ n((a, h, d) => {
  z.push(new gt(a, h, d));
}, "addLink"), D, _t = (D = class {
  constructor(h) {
    this.ID = h;
  }
}, n(D, "SankeyNode"), D), xt = /* @__PURE__ */ n((a) => {
  a = at.sanitizeText(a, B());
  let h = W.get(a);
  return h === void 0 && (h = new _t(a), W.set(a, h), U.push(h)), h;
}, "findOrCreateNode"), kt = /* @__PURE__ */ n(() => U, "getNodes"), vt = /* @__PURE__ */ n(() => z, "getLinks"), bt = /* @__PURE__ */ n(() => ({
  nodes: U.map((a) => ({ id: a.ID })),
  links: z.map((a) => ({
    source: a.source.ID,
    target: a.target.ID,
    value: a.value
  }))
}), "getGraph"), St = {
  nodesMap: W,
  getConfig: /* @__PURE__ */ n(() => B().sankey, "getConfig"),
  getNodes: kt,
  getLinks: vt,
  getGraph: bt,
  addLink: mt,
  findOrCreateNode: xt,
  getAccTitle: it,
  setAccTitle: et,
  getAccDescription: tt,
  setAccDescription: Z,
  getDiagramTitle: J,
  setDiagramTitle: q,
  clear: dt
}, E, H = (E = class {
  static next(h) {
    return new E(h + ++E.count);
  }
  constructor(h) {
    this.id = h, this.href = `#${h}`;
  }
  toString() {
    return "url(" + this.href + ")";
  }
}, n(E, "Uid"), E.count = 0, E), Et = {
  left: ut,
  right: ct,
  center: ht,
  justify: lt
}, At = /* @__PURE__ */ n(function(a, h, d, A) {
  const { securityLevel: w, sankey: c } = B(), g = nt.sankey;
  let _;
  w === "sandbox" && (_ = F("#i" + h));
  const t = w === "sandbox" ? F(_.nodes()[0].contentDocument.body) : F("body"), e = w === "sandbox" ? t.select(`[id="${h}"]`) : F(`[id="${h}"]`), i = (c == null ? void 0 : c.width) ?? g.width, o = (c == null ? void 0 : c.height) ?? g.width, l = (c == null ? void 0 : c.useMaxWidth) ?? g.useMaxWidth, r = (c == null ? void 0 : c.nodeAlignment) ?? g.nodeAlignment, T = (c == null ? void 0 : c.prefix) ?? g.prefix, x = (c == null ? void 0 : c.suffix) ?? g.suffix, k = (c == null ? void 0 : c.showValues) ?? g.showValues, v = A.db.getGraph(), M = Et[r];
  ot().nodeId((s) => s.id).nodeWidth(10).nodePadding(10 + (k ? 15 : 0)).nodeAlign(M).extent([
    [0, 0],
    [i, o]
  ])(v);
  const u = pt(ft);
  e.append("g").attr("class", "nodes").selectAll(".node").data(v.nodes).join("g").attr("class", "node").attr("id", (s) => (s.uid = H.next("node-")).id).attr("transform", function(s) {
    return "translate(" + s.x0 + "," + s.y0 + ")";
  }).attr("x", (s) => s.x0).attr("y", (s) => s.y0).append("rect").attr("height", (s) => s.y1 - s.y0).attr("width", (s) => s.x1 - s.x0).attr("fill", (s) => u(s.id));
  const b = /* @__PURE__ */ n(({ id: s, value: y }) => k ? `${s}
${T}${Math.round(y * 100) / 100}${x}` : s, "getText");
  e.append("g").attr("class", "node-labels").attr("font-size", 14).selectAll("text").data(v.nodes).join("text").attr("x", (s) => s.x0 < i / 2 ? s.x1 + 6 : s.x0 - 6).attr("y", (s) => (s.y1 + s.y0) / 2).attr("dy", `${k ? "0" : "0.35"}em`).attr("text-anchor", (s) => s.x0 < i / 2 ? "start" : "end").text(b);
  const N = e.append("g").attr("class", "links").attr("fill", "none").attr("stroke-opacity", 0.5).selectAll(".link").data(v.links).join("g").attr("class", "link").style("mix-blend-mode", "multiply"), I = (c == null ? void 0 : c.linkColor) ?? "gradient";
  if (I === "gradient") {
    const s = N.append("linearGradient").attr("id", (y) => (y.uid = H.next("linearGradient-")).id).attr("gradientUnits", "userSpaceOnUse").attr("x1", (y) => y.source.x1).attr("x2", (y) => y.target.x0);
    s.append("stop").attr("offset", "0%").attr("stop-color", (y) => u(y.source.id)), s.append("stop").attr("offset", "100%").attr("stop-color", (y) => u(y.target.id));
  }
  let P;
  switch (I) {
    case "gradient":
      P = /* @__PURE__ */ n((s) => s.uid, "coloring");
      break;
    case "source":
      P = /* @__PURE__ */ n((s) => u(s.source.id), "coloring");
      break;
    case "target":
      P = /* @__PURE__ */ n((s) => u(s.target.id), "coloring");
      break;
    default:
      P = I;
  }
  N.append("path").attr("d", yt()).attr("stroke", P).attr("stroke-width", (s) => Math.max(1, s.width)), st(void 0, e, 0, l);
}, "draw"), wt = {
  draw: At
}, Tt = /* @__PURE__ */ n((a) => a.replaceAll(/^[^\S\n\r]+|[^\S\n\r]+$/g, "").replaceAll(/([\n\r])+/g, `
`).trim(), "prepareTextForParsing"), It = /* @__PURE__ */ n((a) => `.label {
      font-family: ${a.fontFamily};
    }`, "getStyles"), Pt = It, Ot = R.parse.bind(R);
R.parse = (a) => Ot(Tt(a));
var zt = {
  styles: Pt,
  parser: R,
  db: St,
  renderer: wt
};
export {
  zt as diagram
};
